Loading...
No results found.

Apply your skills in Google Cloud console

API Design and Fundamentals of Google Cloud's Apigee API Platform

Get access to 700+ labs and courses

Apigee Lab 2a: Route Rules and the Debug Tool

Lab 1 hour 30 minutes universal_currency_alt 5 Credits show_chart Introductory
info This lab may incorporate AI tools to support your learning.
Get access to 700+ labs and courses

Overview

In this lab, you will create two target endpoints and conditionally route to them using route rules. You also learn how to troubleshoot your proxies using the Apigee Debug tool.

Objectives

In this lab, you will learn how to perform the following tasks:

  • Create multiple target endpoints within a single proxy.
  • Modify route rules to conditionally route to the target endpoints.
  • Trace API calls flowing through a proxy.
  • Understand the information available in a debug session.
  • Set filters to capture only matching calls.

Setup and requirements

For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.

  1. Sign in to Qwiklabs using an incognito window.

  2. 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.

  3. When ready, click Start lab.

  4. Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.

  5. Click Open Google Console.

  6. 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.

  7. 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.

  1. In Cloud console, on the top right toolbar, click the Open Cloud Shell button.

  2. 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:
gcloud auth list

Output:

Credentialed accounts: - @.com (active)

Example output:

Credentialed accounts: - google1623327_student@qwiklabs.net
  • You can list the project ID with this command:
gcloud config list project

Output:

[core] project =

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: Full documentation of gcloud is available in the gcloud CLI overview guide .

Task 1. Create a new API proxy

In this task, you create a new API proxy that calls the retail backend.

Pin the Apigee console page

  1. In the Google Cloud console, on the Navigation menu (), look for Apigee in the Pinned Products section.

    The Apigee console page will open.

  2. If Apigee is not pinned, search for Apigee in the top search bar and navigate to the Apigee service.

  3. Hover over the name, then click the pin icon ().

    The Apigee console page will now be pinned to the Navigation menu.

Create the proxy

  1. On the left navigation menu, select Proxy development > API proxies.

  2. To start the proxy wizard, click +Create.

  3. For Proxy template, select Reverse proxy (Most common).

  4. Specify the following settings:

    Property Value
    Proxy Name lab2a-v1
    Base path /lab2a/v1
    Target (Existing API) https://gcp-cs-training-01-test.apigee.net/training/db
    Note: Confirm that you are using /lab2a/v1 for the base path, and not /lab2a-v1.
  5. Click Create.

  6. Click the Develop tab.

Task 2. Add a new target endpoint and route rule

In this task, you create a new target endpoint and route rule to call a new backend service.

  1. In the Navigator pane, click the Add target endpoint (+) button for Target endpoints.

  2. In the Add target endpoint pane, specify the following values:

    Property Value
    Target endpoint name uuid_service
    HTTP target https://httpbin.org/uuid

    This service returns a UUID.

    Note: UUIDs, or Universally Unique Identifiers, are used to create globally unique identifiers without requiring a centralized authority to provide them. These are also known as GUIDs, or Globally Unique Identifiers.
  3. Click Add.

    The uuid_service target endpoint appears in the code pane. Functionality that is specific to the target should be placed in the target endpoint flows.

  4. In the Navigator pane, click Proxy endpoints > default.

    The default ProxyEndpoint configuration is displayed in the code box. Examine the RouteRule section in the proxy endpoint.

    When we created the proxy, it had only a single target endpoint. The single route rule routes all traffic to the default target endpoint because there is no condition for the route rule. We need to add a route rule to conditionally route to the uuid_service target endpoint.

  5. Replace the following:

    <RouteRule name="default"> <TargetEndpoint>default</TargetEndpoint> </RouteRule>

    with:

    <RouteRule name="uuid"> <Condition>proxy.pathsuffix == "/uuid"</Condition> <TargetEndpoint>uuid_service</TargetEndpoint> </RouteRule> <RouteRule name="default"> <TargetEndpoint>default</TargetEndpoint> </RouteRule>

    This new route rule routes to the uuid_service target endpoint if the proxy's path suffix is /uuid.

  6. Click Save. If you are notified that the proxy was saved as a new revision.

  7. Click Deploy.

  8. To specify that you want the new revision deployed to the eval environment, select eval as the Environment, and then click Deploy.

    Note: Leave the "Service Account" field empty.
  9. Click Confirm.

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.

While you are waiting

Take note of the following:

Task 3. Test the API proxy

In this task, you call each service.

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).

  1. In Cloud Shell, open a new tab, and then open an SSH connection to your test VM:

    TEST_VM_ZONE=$(gcloud compute instances list --filter="name=('apigeex-test-vm')" --format "value(zone)") gcloud compute ssh apigeex-test-vm --zone=${TEST_VM_ZONE} --force-key-file-overwrite

    The first gcloud command retrieves the zone of the test VM, and the second opens the SSH connection to the VM.

  2. 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.

Call the API

  1. To make a call to proxy hosted in the eval environment, in the Cloud Shell SSH session, send a request to your API proxy by using this command:

    curl -i -k -X GET "https://eval.example.com/lab2a/v1/categories"

    The curl command responds with a JSON array of category objects.

  2. Now, send the following curl command:

    curl -i -k -X GET "https://eval.example.com/lab2a/v1/uuid"

    When you changed the proxy suffix to /uuid, you probably expected the uuid_service target to be called. Instead, you see an HTML error.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
  3. To directly call the backend service you were intending to call, open another tab in your browser, and navigate to the URL you used in the uuid_service target endpoint:

    https://httpbin.org/uuid

    Opening a web page uses a GET verb, and this URL successfully returns a JSON payload with a UUID.

    Something must be going wrong. How do you determine what is happening?

Task 4. Use the debug tool to debug the issue

In this task, you explore how to use the debug tool to debug API proxy issues.

  1. In the proxy wizard, select the Debug tab.

  2. Click Start Debug Session.

  3. In the Start debug session pane, on the Environment dropdown, select eval.

    The deployed revision number will also show in the dropdown.

  4. Click Start.

    A debug session will last a maximum of 10 minutes or until 15 transactions are received, whichever comes first.

  5. Back in the Cloud Shell SSH session, send the following curl command:

    curl -i -k -X GET "https://eval.example.com/lab2a/v1/uuid"

    A transaction for this request should appear in the Transactions pane on the left. When a transaction is selected, you'll see a trace of the request and response through Apigee.

    You should see a 404 Status if your backend URL was correctly set and you correctly sent the curl command.

    • The debug session details pane shows a list of transactions that have been received since the debug session was started.

  6. Click View Options, and then select Show skipped policies and Show all flow conditions.

  7. Click OK.

    S

    • The Transaction Pane in Apigee provides a graphical representation of all policies and flows evaluated during the execution of the selected transaction. It visually maps the request and response flow, displaying the sequence of policy executions and interactions Each step in the transaction is represented by a node, showing key operations such as authentication, transformations, routing, and error handling. You can step through a debug session by using the Previous and Next buttons to inspect each stage of the transaction execution.

    When you select a step on the Transaction pane, the details of that step show up in the details pane. For example, if you click on a policy, you would see details like variables read and updated by the policy, as well as properties set in the policy configuration.

Exploring the transaction

  1. Click the GET 404 transaction.

  2. In the Transaction pane, in the request, click on the Condition for the first route rule.

    This shows the details of the condition you added in the first route rule.

    The condition Expression is proxy.pathsuffix equals "/uuid", and the ExpressionResult is true.

    The true result indicates that your request was handled by the uuid_service target endpoint.

  3. Click Response Start, and then select the Response Content tab.

    The response content shows that the backend server returned 404 Not Found. You need to determine what URL was called on the backend server.

  4. Click AnalyticsPublisher, select the Variables tab, and then scroll down to the request.uri variable.

    Apigee captures analytics for the API calls that travel through your proxies. The AnalyticsPublisher step in the transaction details shows the variables that were captured.

    The variable request.uri contains the path that was called by the Apigee proxy, /uuid/uuid.

    You can probably see the issue now. The request to the backend service was a GET on https://httpbin.org/uuid/uuid, and the backend service returned the HTML error. The backend service URL only requires a single uuid. Why did this happen?

    By default, the path suffix is automatically added to the target endpoint URL. This is why a request to /lab2a/v1/categories went to the categories endpoint in the retail backend service. /categories was the path suffix, which was automatically added to the target endpoint URL.

    In this request, /uuid follows the base path, and is therefore the path suffix. It was being added to the target endpoint URL, which already ends with /uuid.

    You could remove /uuid from the target endpoint URL. Instead, you will change the proxy to not automatically append the path suffix to the target endpoint URL.

Task 5. Update the API proxy

In this task, you add a policy to stop the path suffix from being added to the target service URL.

  1. Click the Develop tab.

  2. In the Navigator pane, click Target endpoints > uuid_service > PreFlow.

    A visual representation of the target endpoint preflow is displayed.

  3. On the Request PreFlow, click Add Policy Step (+).

    This policy must run before we call the backend, so the step must be in the request path.

  4. In the Add policy step pane, select Create new policy, and then select Extension > Javascript.

  5. Specify the following values:

    Property Value
    Name JS-DisablePathSuffixCopy
    Display name JS-DisablePathSuffixCopy
  6. For Javascript file, select Create New Resource.

  7. For Resource name, specify DisablePathSuffixCopy.js.

  8. Click Add.

  9. For Javascript file, select DisablePathSuffixCopy.js.

  10. Click Add.

  11. In another browser tab, open the Flow variables reference page.

    This page lists the available built-in variables and is very useful when building API proxies. In the target section, there is a variable named target.copy.pathsuffix. Setting the variable to false will block the pathsuffix from being automatically copied to the target request URL. You can also specify the backend URL directly using the target.url variable.

  12. In the Navigator pane, click Policies > JS-DisablePathSuffixCopy.

    The policy XML configuration is shown in the Code pane.

    You typically add JavaScript code to the .js file, but in this case the code is only a single line, so we add it directly in the JavaScript configuration.

  13. Replace the current JavaScript configuration:

    <Javascript continueOnError="false" enabled="true" timeLimit="200" name="JS-DisablePathSuffixCopy"> <DisplayName>JS-DisablePathSuffixCopy</DisplayName> <Properties/> <ResourceURL>jsc://DisablePathSuffixCopy.js</ResourceURL> </Javascript>

    with:

    <Javascript continueOnError="false" enabled="true" timeLimit="200" name="JS-DisablePathSuffixCopy"> <Source> context.setVariable("target.copy.pathsuffix", false); </Source> </Javascript>

    The single line of JavaScript sets the target.copy.pathsuffix variable to false.

  14. The .js file is no longer needed, so click Resources > jsc > DisablePathSuffixCopy.js, and then click Delete Resource ().

  15. Confirm the deletion of the script by clicking Delete.

  16. To save the updates, click Save, and then click Save as New Revision.

  17. Click Deploy.

  18. To specify that you want the new revision deployed to the eval environment, click Deploy, and then click Confirm.

  19. Click the Overview tab, and then wait for the revision to deploy.

Task 6. Test the updated proxy

In this task, you verify that the proxy correctly calls the UUID service.

  1. Click the Debug tab, and then click Start Debug Session.

  2. In the Start debug session pane, on the Environment dropdown, select eval.

  3. For Filter, select Custom.

    For this debug session, you will specify a custom filter. Requests that do not match the filter will not be captured. This feature is very important when trying to debug the proxy in production, because the vast majority of the API traffic may not be what you are trying to capture.

  4. For Value, specify this filter:

    proxy.pathsuffix == "/uuid"

    This filter will only capture calls that are going to the UUID service.

  5. Click Start.

  6. In the Cloud Shell SSH session, send the following curl command a few times:

    curl -i -k -X GET "https://eval.example.com/lab2a/v1/uuid"

    You should see a UUID in the curl response.

  7. Send the following curl command a few times too:

    curl -i -k -X GET "https://eval.example.com/lab2a/v1/categories"

    You should see the categories in the curl response.

  8. Return to the debug tool.

    You should only see UUID calls, because the categories calls were filtered out.

  9. Click one of the transactions.

  10. Click on the JS-DisablePathSuffixCopy step, and then click Variables.

    You can see in the policy details that target.copy.pathsuffix was set to false.

Congratulations!

In this lab, you learned about route rules and using multiple targets. You also learned all about the debug tool. Now you should be able to debug issues with your proxies!

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.

Previous Next

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

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

Use private browsing to run the lab

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
Preview