It's important to protect your API from unauthorized access. One way to do that is to validate API keys (also called "public keys", "consumer keys" or "app keys").

The tutorial Part 1: Create your API shows how to create an API proxy to access the Yahoo Weather service. In this tutorial, you create a new version of that API proxy that adds the VerifyAPIKey policy to the API proxy. The advantage of creating a new version of the API proxy is that Apigee Edge creates all of the policies necessary to enforce API keys for you.

If you already have an existing API proxy, you can add the VerifyAPIKey policy at any time. See Verify API Key policy for more.

When an app makes a request to your API, the app must supply a valid key. At runtime, the VerifyAPIKey policy checks the following:

  • That the API key is valid
  • That it hasn't been revoked
  • That it matches the API key for the API product that exposes the requested resources

If the key is valid, the request is allowed. If the key is invalid, the request results in an authorization failure.

For more information on API keys, see Secure APIs with API keys.

Prerequisites for this tutorial

While it is not required, this tutorial assumes that you have competed the first tutorial, where you create an API proxy to access the Yahoo Weather service. If you have not yet completed that tutorial, see Part 1: Create your API.

Step 1: Create an API proxy

Configure an API proxy for the Yahoo! Weather service. This repeats some of the same actions as in the tutorial Part 1: Create your API. However, you'll also add security to your API proxy in this step.

  1. Login to https://enterprise.apigee.com.
  2. In the API Platform UI, select the APIs tab.
  3. Click (+) API Proxy.
  4. Make the following selections and entries in the New API Proxy page.
    Field Value Description
    Choose your starting point
    Starting point radio button Existing Backend Service The API proxy will target an existing service accessible over the Internet.
    Backend Service URL http://weather.yahooapis.com The URL that the API Platform invokes on behalf of apps that call your API through the API proxy URL. This is the URL for the Yahoo! Weather API.
    Identify your API proxy
    Name weatherapikey The name displayed for your API.
    Project Base Path /v1/weatherapikey The base path that the API platform uses to construct the API proxy URL. Apps will call this URL to invoke your API.
    Description Yahoo weather proxy The description of the API.
    Add Features
    Secure with API Keys selected Adds API key-based authentication to your API proxy. When this option is selected, the Impose Quota per Developer option becomes selectable.
    Impose Quota per Developer selected Adds a policy that limits the number of request messages that can be submitted to your API proxy by an individual app over an interval of time.
    Publish API Product cleared When you select the Secure with API Keys option, the Publish API Product option is automatically selected. For the purposes of this tutorial, be sure to clear this option.
    Enable Direct Browser Access for Your API cleared Enables CORS (cross-origin resource sharing) to allow a browser to make direct requests to another domain.

    The completed page should look like this:

  5. Click Build to save the entries you made in the page.
    In response, you should see an acknowledgment that your new API proxy was successfully created and deployed in the 'test' environment.
  6. Click Close.

Learn more:

Step 2: Define an API resource

API keys are mapped to specific API Products. API Products are collections of API resources (URIs). You'll create an API resource to include in your product later in the tutorial.

  1. In the Resources section, click the + Resource button.
  2. Enter the following values:

    • Name: forecast
    • Proxy Endpoint: default
    • Verb: GET
    • Path: /forecastrss
  3. Click the check icon in the Actions columns to validate the resource. The full URL to the resource appears in the URL column.
  4. Click Save. The resource is added to the API proxy.

Learn more:

Step 3: Examine the generated policies

Because you chose the Secure with API Keys and Impose Quota per Developer options when you created the API proxy, Edge automatically added the following policies to your proxy:

Name Policy Type Description
Verify API Key VerifyAPIKey Verifies the API key for an API product, returns an error if it is invalid, and if it is valid, looks up the attributes from the API product.
Remove Query Param AssignMessage Modifies request messages in the API proxy flow to prevent the API key from being sent to the backend URL.
Add Quota Quota Enforces a limit on the number of API calls made by apps over an interval of time
  1. Open the API Proxy Editor by clicking the Develop button in the details page for the weatherapikey API proxy to open the API Proxy Editor.

  2. On the left side of the API Proxy Editor, select PreFlow under Proxy Endpoints > default to show the generated policies in the Policy Designer.


    For more information on Flows and Endpoints, see Understanding APIs and API proxies.
     
  3. Select each policy to examine its settings.

Examine the VerifyAPIKey policy

The first policy to examine is the VerifyAPIKey policy, named Verify API Key. Typically, you want API key validation to happen as soon as a request is received by your API proxy. The PreFlow is always the first flow to execute at an endpoint, and the ProxyEndpoint is the first endpoint in the request pipeline. Because the VerifyAPIKey policy is the first policy in the PreFlow, the API key will be validated by the policy as soon as it's received by the API proxy.

Click the Verify API Key policy icon, and examine the XML for the policy in the Code view. You can also view the values for the policy's XML elements and attributes in the Property Inspector. The XML for the policy should look something like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<VerifyAPIKey async="false" continueOnError="false" enabled="true" name="verify-api-key">
    <DisplayName>Verify API Key</DisplayName>
    <APIKey ref="request.queryparam.apikey"/>
</VerifyAPIKey>   

Note the <APIKey> element, which identifies where the policy should check for the API key. In this example, the policy looks for the API key in a query parameter named 'apikey'.

API keys can be located in a query parameter, a form parameter, or an HTTP header. Apigee Edge provides a message variable for each type of location.

Request variable Where expected key location is provided
request.queryparam.{queryparam_name} query parameter
request.header.{header_name} header
request.formparam.{formparam_name} form parameter
Learn more:

Examine the AssignMessage policy

The next policy in the PreFlow is an AssignMessage policy named Remove Query Param apikey. The AssignMessage policy defines a set of elements that perform actions such as populating or modifying HTTP headers, query parameters, and XML or JSON payload content.

Examine the XML for the AssignMessage policy. The XML for the policy should look like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Remove-Query-Param">
    <DisplayName>Remove Query Param</DisplayName>
    <Remove>
        <QueryParams>
            <QueryParam name="apikey"/>
        </QueryParams>
    </Remove>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

In this example, the policy uses a <Remove> element to remove the query parameter named apikey from the HTTP request message attached to the flow so it is not sent to the backend service. Only the VerifyAPIKey policy needs to be aware of the API key.

Learn more:

Examine the Quota policy

The final policy in the PreFlow is a Quota policy named Impose Quota. This policy enforces a limit on the number of API calls made by apps over an interval of time. The limit can be set in the policy, or in the API product that contains this API proxy. For example, you may want to limit apps to 1 request per minute, or to 10,000 requests per month.

Examine the XML for the Quota. The XML for the policy should look like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Quota async="false" continueOnError="false" enabled="true" name="Add-Quota">
    <DisplayName>Add Quota</DisplayName>
    <Allow countRef="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.limit" count="2000"/>
    <Interval ref="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.interval">1</Interval>
    <Distributed>true</Distributed>
    <Synchronous>true</Synchronous>
    <TimeUnit ref="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.timeunit">month</TimeUnit>
</Quota>

The <Allow> element of the Quota policy sets values for the maximum count of messages for the quota (2000). The <Interval> and <TimeUnit> elements specify the time interval as 1 month. The policy also references variables that are populated by Edge when the VerifyAPIKey policy is enforced. These values take precedence over the values set in the policy. For example, the following specifies a maximum message count for the quota based on the limit set in the API product that is used in validating the request:

<Allow countRef="verifyapikey.Verify-Api-Key.apiproduct.developer.quota.limit" count="5000"/>

Learn more:

Step 4: Request the Yahoo Weather API by using your Edge API proxy

Now that you have an API proxy for the Yahoo Weather API, you can make requests to it through Apigee Edge. The first thing you need to determine is the complete URL of the resource of the API proxy that you want to access. That URL has the form:

http://{org-name}-{env-name}.apigee.net/{project-base-path}/{resource-name}?{query-params}

In your Web browser, enter the following, substituting your Apigee organization name for {org-name}:

http://{org-name}-test.apigee.net/v1/weatherapikey/forecastrss?w=12797282

For example:

http://myorg-test.apigee.net/v1/weatherapikey/forecastrss?w=12797282

Because this API proxy uses the VerifyAPIKey policy, which expects an API key to be passed in a query parameter named 'apikey' the request fails with the following message: 

{"fault":{"faultstring":"Failed to resolve API Key variable request.queryparam.apikey","detail":{"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}

You now have to generate a valid key before you can make a request to this API.

To use a browser to make the request:

  1. Enter the URL in a browser window.

To use the Trace page to make the request:

  1. In management UI, click the APIs tab.
  2. Click weatherapikey in the API Proxies table.
  3. On the weatherapikey detail page, click the Trace button to access the Trace page.
  4. On the Trace page, choose the test environment.
  5. Click Start Trace Session.
  6. Enter the URL in the URL field.
  7. Click Send.

To use the Apigee Console to make the request:

  1. From the Trace page, click Send with the Apigee Console, just below the Send button in the Send Requests area of the Trace page.
    The console appears in another browser window.
  2. Enter the URL of your API.
  3. Click Send.

To use cURL to make the request:

  1. Install cURL.
    The cURL tool is a convenient way to submit URL-based commands from a command line.

  2. Use cURL to request the URL:

    curl "http://myorg-test.apigee.net/v1/weatherapikey/forecastrss?w=12797282"

Step 5: Where to next?

Now that you have a secure API defined on Edge, define the API product, developer, and app required to generate the key necessary to make requests to the API.

Continue on to Part 2: Generate and test an API key to generate the API key.

 

Help or comments?

  • Something's not working: See Apigee Support
  • Something's wrong with the docs: Click Send Feedback in the lower right.
    (Incorrect? Unclear? Broken link? Typo?)