In this lab, you create an integrated developer portal, publish an API product and OpenAPI specification to the portal, and make API calls using the live documentation in the portal.
Objectives
In this lab, you learn how to perform the following tasks:
Support CORS in an API proxy.
Create an integrated developer portal.
Publish APIs as API products on the integrated developer portal.
Sign in as an app developer and use live documentation in the developer portal.
Setup
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
Sign in to Qwiklabs using an incognito window.
Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
There is no pause feature. You can restart if needed, but you have to start at the beginning.
When ready, click Start lab.
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
Click Open Google Console.
Click Use another account and copy/paste credentials for this lab into the prompts.
If you use other credentials, you'll receive errors or incur charges.
Accept the terms and skip the recovery resource page.
Activate Google Cloud Shell
Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.
Google Cloud Shell provides command-line access to your Google Cloud resources.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
You can list the active account name with this command:
[core]
project = qwiklabs-gcp-44776a13dea667a6
Note:
Full documentation of gcloud is available in the
gcloud CLI overview guide
.
Preloaded assets
These assets have already been added to the Apigee organization:
The retail-v1 API proxy
The oauth-v1 API proxy (for generating OAuth tokens)
The backend-credentials shared flow (used by retail-v1)
The TS-Retail target server in the eval environment (used by retail-v1)
These assets will be added to the Apigee organization as soon as the runtime is available:
The API products, developer, and developer app (used by retail-v1)
The ProductsKVM key value map in the eval environment (used by backend-credentials)
The ProductsKVM key value map entries backendId and backendSecret
The highlighted items are used during this lab.
Note:
Revision 1 of the retail-v1 proxy is marked as deployed, and is immutable. If you ever make a mistake in your proxy code that you can't recover from, you can select revision 1 and restart editing from there.
CORS is a protocol that uses HTTP headers to indicate to browsers whether it is safe to access restricted resources from a separate domain. By default, cross-domain requests are forbidden by the same-origin security policy. The same-origin policy protects browser users from unknowingly sharing session information with bad actors.
The same-origin policy means that a web page served from www.example.com could not, by default, make a call to example.com's APIs at api.example.com because the host name is different. CORS can be used to allow this kind of cross-origin access.
You need CORS in the retail API because the developer portal has a domain name of "*.apigee.io," and the API is accessed via a different domain, "*.apigee.net." In order to invoke the API from the documentation, you will add CORS headers to all API responses, including error responses.
CORS also uses preflight requests. The browser sends a preflight request using the OPTIONS verb to find out whether the next call will be allowed.
Apigee provides a CORS policy that sets all of the required CORS security policies for the API proxy.
In the Google Cloud console, on the Navigation menu (), look for Apigee in the Pinned Products section.
The Apigee console page will open.
If Apigee is not pinned, search for Apigee in the top search bar and navigate to the Apigee service.
Hover over the name, then click the pin icon ().
The Apigee console page will now be pinned to the Navigation menu.
Add CORS policy
On the left navigation menu, select Proxy development > API proxies.
Select the retail-v1 proxy.
Click the Develop tab.
You are modifying the version of the retail-v1 proxy that was created during Labs 1 through 12.
In the Navigator menu, click Proxy endpoints > default > PreFlow.
On the Request PreFlow flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select Security > CORS.
Specify the following values:
Property
Value
Name
CORS-AddCORS
Display name
CORS-AddCORS
Click Add.
Click Policies > CORS-AddCORS.
The CORS configuration includes the following settings:
AllowOrigins lists the allowed origins. The default configuration allows any Origin, because it sets the allowed origin equal to the Origin that is passed in the request. In a typical production use case, you might only allow requests from specific hostnames.
AllowMethods specifies the methods that should be allowed for the API.
AllowHeaders lists the headers that may be passed in the request.
ExposeHeaders specifies the headers in the response that should be allowed when being called with an Origin. With the default value of *, no response headers will be stripped from the response.
MaxAge specifies how long a preflight response may be cached by a browser, in seconds.
AllowCredentials indicates whether Authorization headers, TLS client certificates, or cookies can be sent in the request.
GeneratePreflightResponse specifies whether preflight requests with the OPTIONS method will be handled.
Replace the AllowMethods element with:
<AllowMethods>GET, PUT, POST, DELETE, PATCH</AllowMethods>
The retail API uses the apikey header to specify an API key, so that header must be added to be called from a browser.
Replace the MaxAge element with:
<MaxAge>-1</MaxAge>
This disables the browser caching of the preflight response, so that you will always see the preflight request. In a production use case, you should typically allow caching of the response to avoid making two calls for every request.
Replace the AllowCredentials element with:
<AllowCredentials>true</AllowCredentials>
The retail API requires an Authorization header for creating an order.
The CORS policy configuration should now look like this:
<CORS continueOnError="false" enabled="true" name="CORS-AddCORS">
<DisplayName>CORS-AddCORS</DisplayName>
<AllowOrigins>{request.header.origin}</AllowOrigins>
<AllowMethods>GET, PUT, POST, DELETE, PATCH</AllowMethods>
<AllowHeaders>origin, x-requested-with, accept, content-type, apikey</AllowHeaders>
<ExposeHeaders>*</ExposeHeaders>
<MaxAge>-1</MaxAge>
<AllowCredentials>true</AllowCredentials>
<GeneratePreflightResponse>true</GeneratePreflightResponse>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</CORS>
Note: This implementation sends back the request's Origin in the response via the Access-Control-Allow-Origin header. Any Origin will be allowed, which is not a recommended solution for a production-quality API. A better solution is to only accept requests that come from an origin that has been specifically allowed.
In the Navigator menu, click Proxy endpoints > default > PreFlow.
Drag the CORS-AddCORS policy to execute first in the proxy endpoint PreFlow request:
Remove target CORS
You may have noticed during previous labs that the target always returns Access-Control-Allow-Origin with a value of "*". You will remove this header from the backend response to ensure that the retail API's CORS implementation is used.
Note: It is a best practice to remove all headers that are not needed from the backend service response. In this lab, we are only removing the Access-Control-Allow-Origin header.
In the Navigator menu, click Target endpoints > default > PreFlow.
On the Response PreFlow flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select Mediation > Assign Message.
Specify the following values:
Property
Value
Name
AM-StripTargetCORS
Display name
AM-StripTargetCORS
Click Add.
Click Policies > AM-StripTargetCORS.
Replace the AssignMessage policy configuration with:
To specify that you want the new revision deployed to the eval environment, select eval as the Environment, and then click Deploy.
Click Confirm.
Task 2. Create an integrated developer portal
In this task, you create an integrated developer portal for your Apigee organization.
In the Navigator pane, click Distribution > Portals.
Note: The portals functionality is not currently accessible from the Google Cloud console. This lab will use the classic Apigee UI for creating the portal.
If Portals is not yet implmented in the Cloud Console, Click Go to Classic Apigee UI.
The classic UI opens in a new tab.
Click Get started, or click +Portal if you already have a portal.
Enter a name for the portal (retail), and then click Create.
Creation may take a minute, and then the retail portal management page should open.
If a message to "Enroll in beta for team and audience management features" is displayed, click Enroll.
To open the new portal in a new tab, click Live Portal.
Task 3. Modify your OpenAPI specification
In this task, you modify the OpenAPI specification to match your current proxy implementation.
Get the external hostname
This OpenAPI specification specifies the interface of the API proxy that you have created during this lab. The specification will be used to provide live documentation in the developer portal.
The developer portal accesses the Apigee proxy from the external network. The hostname you have been using, eval.example.com, is only available on the internal network.
A load balancer has been provisioned to provide external access to the API proxy. External access uses a hostname provided by nip.io, which is a wildcard DNS provider.
The external hostname will look similar to this:
eval.60.70.80.90.nip.io
This hostname must be specified as a matching hostname for the eval-groupenvironment group.
To determine the external hostname from the external load balancer certificate and add the hostname to the environment group, in Cloud Shell, run the following commands:
The external hostname is taken from the SSL certificate used by the external load balancer. The PATCH command updates the hostnames associated with the eval-group evaluation group. The GET command shows the updated eval-group configuration.
Download the OpenAPI specification
In Cloud Shell, to download the OpenAPI specification for the backend service, run this curl command:
This curl command downloads a file named retail-backend.yaml and stores it in a file with the same name in the home directory.
Note: ?$(date +%s) adds a query parameter to the URL that is a string representation of the current date/time. This dynamically changing variable changes the URL and forces curl to retrieve the latest version of a file, even if a previous version is cached.
View the OpenAPI specification in Cloud Shell Editor
In Cloud Shell, click Open Editor.
In the Cloud Shell Editor, click retail-backend.yaml.
Two changes must be made:
Basic Authentication for updateProductById must be removed. This is a feature of the backend service, not the retail-v1 proxy.
API key support must be added for all calls.
For OpenAPI version 3 specifications, defining security requires two steps:
Define the security scheme
Attach the security scheme to the resources
Note:
If you make a mistake and cannot figure out how to recover, you can start again by redownloading the retail-backend.yaml file. YAML requires specific spacing and indentation to work. Each indentation level is two spaces, and tabs are not allowed. The following changes should have the correct spacing if you keep the spacing and replace entire lines.
Update the specification
Find the securitySchemes section on line 316. The section currently looks like this:
The section defines a scheme named basicAuth that uses the basic authentication scheme. This is no longer required because you only allow API key requests.
Replace the basicAuth scheme with an API key scheme by replacing lines 316-320 with:
The top of your specification should resemble this, but with a different nip.io hostname:
In the IDE menu (), click File > Save As....
For the filename, replace retail-backend with retail-v1, and then click OK.
Click Open Terminal.
Select Cloud Shell's More menu (), and then click Download.
Enter retail-v1.yaml and then click Download.
This will download the file to your local machine. You will use the updated specification with the developer portal.
Close Cloud Shell.
Task 4. Test the CORS functionality
Check deployment status
A proxy that is deployed and ready to take traffic will show a green status on the Overview tab.
When a proxy is marked as deployed but the runtime is not yet available and the environment is not yet attached, you may see a red warning sign. Hold the pointer over the Status icon to see the current status.
If the proxy is deployed and shows as green, your proxy is ready for API traffic. If your proxy is not deployed because there are no runtime pods, you can check the provisioning status.
Check provisioning status
In Cloud Shell, to confirm that the runtime instance has been installed and the eval environment has been attached, run the following commands:
export PROJECT_ID=$(gcloud config list --format 'value(core.project)'); echo "PROJECT_ID=${PROJECT_ID}"; export INSTANCE_NAME=eval-instance; export ENV_NAME=eval; export PREV_INSTANCE_STATE=; echo "waiting for runtime instance ${INSTANCE_NAME} to be active"; while : ; do export INSTANCE_STATE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${PROJECT_ID}/instances/${INSTANCE_NAME}" | jq "select(.state != null) | .state" --raw-output); [[ "${INSTANCE_STATE}" == "${PREV_INSTANCE_STATE}" ]] || (echo; echo "INSTANCE_STATE=${INSTANCE_STATE}"); export PREV_INSTANCE_STATE=${INSTANCE_STATE}; [[ "${INSTANCE_STATE}" != "ACTIVE" ]] || break; echo -n "."; sleep 5; done; echo; echo "instance created, waiting for environment ${ENV_NAME} to be attached to instance"; while : ; do export ATTACHMENT_DONE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${PROJECT_ID}/instances/${INSTANCE_NAME}/attachments" | jq "select(.attachments != null) | .attachments[] | select(.environment == \"${ENV_NAME}\") | .environment" --join-output); [[ "${ATTACHMENT_DONE}" != "${ENV_NAME}" ]] || break; echo -n "."; sleep 5; done; echo "***ORG IS READY TO USE***";
When the script returns ORG IS READY TO USE, you can proceed to the next steps.
On the left navigation menu, select Proxy development > API proxies.
Select the retail-v1 proxy.
Click the Debug tab, and then click Start Debug Session.
In the Start debug session pane, on the Environment dropdown, select eval.
Click Start.
Test the API proxy using private DNS
The eval environment in the Apigee organization can be called using the hostname eval.example.com. The DNS entry for this hostname has been created within your project, and it resolves to the IP address of the Apigee runtime instance. This DNS entry has been created in a private zone, which means it is only visible on the internal network.
Cloud Shell does not reside on the internal network, so Cloud Shell commands cannot resolve this DNS entry. A virtual machine (VM) within your project can access the private zone DNS. A virtual machine named apigeex-test-vm was automatically created for this purpose. You can make API proxy calls from this machine.
The curl command will be used to send API requests to an API proxy. The -k option for curl tells it to skip verification of the TLS certificate. For this lab, the Apigee runtime uses a self-signed certificate. For a production environment, you should use certificates that have been created by a trusted certificate authority (CA).
In Cloud Shell, open a new tab, and then open an SSH connection to your test VM:
This command retrieves a Google Cloud access token for the logged-in user, sending it as a Bearer token to the Apigee API call. It retrieves the retail-app app details as a JSON response, which is parsed by jq to retrieve the app's key. That key is then put into the API_KEY environment variable, and the export command is concatenated onto the .bashrc file which runs automatically when starting a the SSH session.
Note:
If you run the command and it shows API_KEY=null, the runtime instance is probably not yet available.
Test the CORS functionality
Open Cloud Shell, and then drag the Cloud Shell pane so you can see both Cloud Shell and the Debug session.
Make a request to retrieve a single category:
curl -i -k -H "apikey: ${API_KEY}" -X GET "https://eval.example.com/retail/v1/categories/1"
There is no Origin, so the Access-Control-Allow-Origin header is not returned.
Note:
If the call returns an Access-Control-Allow-Origin header with the value of "*", your proxy is not correctly stripping the target CORS from the target response.
Make another request, but include the Origin header this time. This tests a normal CORS request:
The Access-Control-Allow-Origin header should be returned with the Origin value you supplied in the request, and the Access-Control-Expose-Headers and Access-Control-Allow-Credentials headers are also returned.
In the API documentation section, select OpenAPI document, and then click Select Document.
Click on the cloud image to select a file to upload.
Select the OpenAPI spec file you downloaded from Cloud Shell (retail-v1.yaml), and then click Open.
Click Select.
Click Save.
Task 6. Test the API using the developer portal
In this task you use the developer portal and make requests to your API.
Start a new debug session
Return to the Cloud Console tab.
On the left navigation menu, select Proxy development > API proxies.
Select the retail-v1 proxy.
Click the Debug tab, and then click Start Debug Session.
In the Start debug session pane, on the Environment dropdown, select eval.
Click Start.
Test in the developer portal
Return to the Live Portal tab.
Click APIs in the top menu bar.
Refresh the APIs page to see the new API:
Click on the Retail API.
Click Authorize.
In Cloud Shell, to get the API key, run the following command:
echo ${API_KEY}
Note:
If your API key does not show when you use the command, return to task 4 to populate the key in a shell variable.
Copy the API key from Cloud Shell.
In the dialog box, paste the API key, and then click Authorize.
Click OK to close the dialog box.
In the Paths menu on the left, select /categories GET in the left navigation bar, and go to the Try this API section.
Click Execute.
You should see a successful response.
In the Paths menu, click /products GET.
Click Try it out, and then click Execute.
You should see a 200 response, with the list of products in the Response body box.
Copy a random product ID from the response, and note the current overall rating.
Note:
Note the rating in the GET /products call. Do not GET the product by ID, or you will cache the product and will not be able to see updates you make to the product.
In the left navigation bar, select /products/, and then select {productId} PATCH.
In the Try this API section, enter the product ID you chose from the GET /products call, set a new overall_rating in the request body, and click Execute.
You should see two new requests in the debug tool. The first is the CORS preflight with the OPTIONS verb. The proxy returns 200 OK with the CORS headers. The second is the PATCH request.
If you repeat the same call, you will see both the OPTIONS and PATCH requests again because the Access-Control-Max-Age header is not allowing the browser to cache the OPTIONS response.
Note:
If an error message says "TypeError: Failed to fetch", your API's CORS implementation is probably broken. You can use the browser Developer Tools to debug the issue.
In the left navigation bar, select /products/, and then select {productId} GET.
In the Try this API section, enter the same product ID, and click Execute. You should see that the response contains the new overall rating.
Note:
The responses to "GET /products/{productId}" are cached. If your testing seems to indicate that the PATCH command is not working, it may be pulling the previous response from the cache. Choose a different product and try again. Remember, do not perform a "GET /products/{productId}" before you have updated the overall_rating.
Task 7. Sign up as an app developer
In this task, you use the developer portal to sign up as an app developer and get an API key.
Create a new developer account
In the upper-right corner of the portal, click Sign In.
Then click the Create an account link.
Enter your information. The email address must be a valid email account because you will need to open an email to validate the account.
Click Create Account.
An email message should be received in your email box shortly.
When you receive the email, click on the registration link. It must be clicked within 10 minutes.
Click on Sign in in the portal and login using your email address and password.
Click on your email address in the upper-right corner, and then click Apps.
Create an application
Click +New App. Use my-retail-app for your app's name, and optionally add a description.
Click Enable to enable the Retail API.
This will add the Retail API product to the app.
Click Save.
A key and secret are created, and you can copy the API key into your clipboard and start using it.
Test the API key
Click APIs at the top of the portal.
Then click Retail to return to the Retail API page.
Click Authorize.
In the Please select app dropdown, select your my-retail-app to automatically use its API key, or to manually specify the API key, select Manually enter key.
Click OK.
You can continue to test your API in the developer portal. Your API key can also be used from curl or a REST client.
Verify the app in the Apigee console
Return to the Apigee console, and click Distribution > Developers.
Your newly created developer will appear in the list of developers.
Click Distribution > Apps.
Your newly created app will appear in the list of apps.
Congratulations!
In this lab, you learned how to add CORS to your proxy, how to modify your OpenAPI specification for API key use, and how to create, configure, and use an integrated developer portal.
End your lab
When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
1 star = Very dissatisfied
2 stars = Dissatisfied
3 stars = Neutral
4 stars = Satisfied
5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Los labs crean un proyecto de Google Cloud y recursos por un tiempo determinado
.
Los labs tienen un límite de tiempo y no tienen la función de pausa. Si finalizas el lab, deberás reiniciarlo desde el principio.
En la parte superior izquierda de la pantalla, haz clic en Comenzar lab para empezar
Usa la navegación privada
Copia el nombre de usuario y la contraseña proporcionados para el lab
Haz clic en Abrir la consola en modo privado
Accede a la consola
Accede con tus credenciales del lab. Si usas otras credenciales, se generarán errores o se incurrirá en cargos.
Acepta las condiciones y omite la página de recursos de recuperación
No hagas clic en Finalizar lab, a menos que lo hayas terminado o quieras reiniciarlo, ya que se borrará tu trabajo y se quitará el proyecto
Este contenido no está disponible en este momento
Te enviaremos una notificación por correo electrónico cuando esté disponible
¡Genial!
Nos comunicaremos contigo por correo electrónico si está disponible
Un lab a la vez
Confirma para finalizar todos los labs existentes y comenzar este
Usa la navegación privada para ejecutar el lab
Usa una ventana de navegación privada o de Incógnito para ejecutar el lab. Así
evitarás cualquier conflicto entre tu cuenta personal y la cuenta
de estudiante, lo que podría generar cargos adicionales en tu cuenta personal.
In this lab, you'll learn how to configure the integrated developer portal and publish your API products to it.
Duración:
15 min de configuración
·
Acceso por 90 min
·
90 min para completar