
Before you begin
- Labs create a Google Cloud project and resources for a fixed time
- Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
- On the top left of your screen, click Start lab to begin
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.
In this lab, you learn how to perform the following tasks:
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.
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.
Output:
Example output:
Output:
Example output:
These assets have already been added to the Apigee organization:
These assets will be added to the Apigee organization as soon as the runtime is available:
The highlighted items are used during this lab.
In this task, you add CORS (cross-origin resource sharing) to the retail-v1 proxy.
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.
For more information about CORS, refer to the Apigee CORS documentation.
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.
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:
The retail API uses the PATCH method.
Replace the AllowHeaders element with:
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:
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:
The retail API requires an Authorization header for creating an order.
The CORS policy configuration should now look like this:
In the Navigator menu, click Proxy endpoints > default > PreFlow.
Drag the CORS-AddCORS policy to execute first in the proxy endpoint PreFlow request:
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.
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:
Click Save, and then click Save as New Revision.
Click Deploy.
To specify that you want the new revision deployed to the eval environment, select eval as the Environment, and then click Deploy.
Click Confirm.
In this task, you create an integrated developer portal for your Apigee organization.
In the Navigator pane, click Distribution > Portals.
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.
In this task, you modify the OpenAPI specification to match your current proxy implementation.
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:
This hostname must be specified as a matching hostname for the eval-group environment 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.
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.
?$(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.
In Cloud Shell, click Open Editor.
In the Cloud Shell Editor, click retail-backend.yaml.
Two changes must be made:
For OpenAPI version 3 specifications, defining security requires two steps:
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 in and name fields indicate that the API key is found in a header named apikey. Remember to match the indentation of the document.
Remove the basic auth security defined for the updateProductById operation. The security field should be on line 224.
Remove these two lines (224 and 225) without changing the indentation of surrounding lines.
Add API key validation for all resources. Insert it just after the tags section and just before the paths section, starting at line 25:
Inserting this security setting at the top level will cause it to be applied to all operations. When inserted, it should look like this:
Update the top 15 lines to reference your API proxy instead of the backend service. Replace lines 1-15 with:
To update the server URL to use the external hostname, on line 14, replace the eval.example.com
hostname with the nip.io
hostname determined above.
To retrieve the external hostname, you can run the following command:
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.
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.
In Cloud Shell, to confirm that the runtime instance has been installed and the eval environment has been attached, run the following commands:
When the script returns ORG IS READY TO USE
, you can proceed to the next steps.
Read:
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:
The first gcloud command retrieves the zone of the test VM, and the second opens the SSH connection to the VM.
If asked to authorize, click Authorize.
For each question asked in the Cloud Shell, click Enter or Return to specify the default input.
Your logged in identity is the owner of the project, so SSH to this machine is allowed.
Your Cloud Shell session is now running inside the VM.
The API key may be retrieved directly from the app accessible on the Publish > Apps page. It can also be retrieved via Apigee API call.
In the Cloud Shell SSH session, run the following command:
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.
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:
Make another request, but include the Origin header this time. This tests a normal CORS request:
Make a 404 Not Found request to test a fault:
The CORS headers are correctly returned even though a fault was raised and the Response flows were not executed.
Make a preflight request:
The CORS preflight headers are correctly set in the response.
In this task you associate an API product with an OpenAPI specification and publish them to the developer portal.
Return to the portal tab, and then click API catalog.
Click +.
Select the retail (full access) API product, and click Next.
Customize the API details:
Property | Value |
---|---|
Published (listed in the catalog) | selected |
Display title | Retail |
Display description | Retail API v1 |
API visibility | select Public (visible to anyone) |
Click Select image and then click the Image URL link.
Set the image URL to:
Click Select.
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.
In this task you use the developer portal and make requests to your API.
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:
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.
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.
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.
In this task, you use the developer portal to sign up as an app developer and get an API key.
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.
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.
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.
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.
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.
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:
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.
This content is not currently available
We will notify you via email when it becomes available
Great!
We will contact you via email if it becomes available
One lab at a time
Confirm to end all existing labs and start this one