Amazon API Gateway
Amazon API Gateway
Developer Guide
Table of Contents
What Is Amazon API Gateway? ...................................................................................................... 1
API Gateway Concepts .......................................................................................................... 2
Getting Started ............................................................................................................................. 4
Get Ready to Use API Gateway ............................................................................................. 4
Sign Up for AWS .......................................................................................................... 5
Create an IAM User, Group or Role in Your AWS Account .................................................. 5
Grant IAM Users Permissions to Access API Gateway Control and Execution Services ............. 5
Next Step .................................................................................................................... 6
Build an API as an HTTP Proxy .............................................................................................. 6
Create an API from an Example ..................................................................................... 7
Build the API Step By Step .......................................................................................... 14
Map Request Parameters ............................................................................................. 22
Map Response Payload ............................................................................................... 30
Build an API as a Lambda Proxy ........................................................................................... 43
Step 1: Prerequisites ................................................................................................... 44
Step 2: Create an API ................................................................................................. 44
Step 3: Create a Resource ........................................................................................... 44
Step 4: Create Lambda Functions ................................................................................. 44
Step 5: Create and Test a GET Method ......................................................................... 47
Step 6: Create and Test a POST Method ....................................................................... 48
Step 7: Deploy the API ................................................................................................ 49
Step 8: Test the API .................................................................................................... 50
Step 9: Clean Up ........................................................................................................ 51
Next Steps ................................................................................................................. 52
Appendix: Create Lambda Invocation and Execution Roles ................................................ 52
Build an API Using Proxy Integration and a Proxy Resource ...................................................... 54
Create and Test an API with HTTP Proxy Integration through a Proxy Resource .................... 55
Create an API with Lambda Proxy Integration through a Proxy Resource ............................. 59
Create an AWS Service Proxy .............................................................................................. 64
Prerequisites .............................................................................................................. 65
Step 1: Create the Resource ........................................................................................ 65
Step 2: Create the GET Method .................................................................................... 65
Step 3: Create the AWS Service Proxy Execution Role ..................................................... 66
Step 4: Specify Method Settings and Test the Method ...................................................... 67
Step 5: Deploy the API ................................................................................................ 68
Step 6: Test the API .................................................................................................... 68
Step 7: Clean Up ........................................................................................................ 69
Creating an API .......................................................................................................................... 70
Create an API in API Gateway .............................................................................................. 70
Create an API Using the API Gateway Console ............................................................... 70
Create an API Using the API Gateway Control Service API ................................................ 71
Create an API Using the AWS SDK for API Gateway ........................................................ 71
Create an API Using the AWS CLI ................................................................................ 71
Set up Method and Integration .............................................................................................. 71
Before Setting Up Methods and Integration ..................................................................... 71
Configure How a Method Is Integrated with a Back End .................................................... 71
Configure How a User Calls an API Method .................................................................... 73
Configure How Data Is Mapped between Method and Integration ........................................ 75
Configure Mock Integration for a Method ........................................................................ 78
Configure Proxy Integration for a Proxy Resource ............................................................ 80
After Setting Up Methods and Integration ........................................................................ 88
Set Up Payload Mappings .................................................................................................... 88
Models ....................................................................................................................... 89
Mapping Templates ..................................................................................................... 92
Tasks for Models and Mapping Templates ...................................................................... 95
iv
vi
vii
viii
Amazon API Gateway consists of two services: the API Gateway control service and API Gateway
execution service. The control service lets you create a RESTful API to expose selected back-end
features. The back end can be another AWS service, such as AWS Lambda or Amazon DynamoDB,
or it can be an existing web application. The execution service lets an app call the API to access the
exposed back-end features. The app can interact with the API using standard HTTP protocols or using
a platform- or language-specific SDK generated by the API creator.
The API you create in API Gateway consists of a set of resources and methods. A resource is a
logical entity that can be accessed through a resource path using the API. A resource can have one
or more operations that are defined by appropriate HTTP verbs such as GET, POST, and DELETE.
A combination of a resource path and an operation identify a method in the API. Each method
corresponds to a REST API request submitted by the user of your API and the corresponding response
returned to the user. API Gateway integrates the method with a targeted back end by mapping the
method request to an integration request acceptable by the back end and then mapping the integration
response from the back end to the method response returned to the user. As an API developer, you
can configure how methods are mapped to integrations and vice versa by stipulating what parameters
to use and specifying mapping templates to transform payloads of given data models.
You can create an API by using the API Gateway management console, described in Getting
Started (p. 4), or by using the API Gateway API Gateway REST API (p. 292). In addition,
you can integrate API creation with AWS CloudFormation templates or API Gateway Extensions to
Swagger (p. 130). For a list of regions where API Gateway is available, as well as the associated
control service endpoints, see Regions and Endpoints.
API Gateway helps developers deliver robust, secure, and scalable mobile and web application back
ends. API Gateway allows developers to securely connect mobile and web applications to business
logic hosted on AWS Lambda, APIs hosted on Amazon EC2, or other publicly addressable web
services hosted inside or outside of AWS. With API Gateway, developers can create and operate APIs
for their back-end services without developing and maintaining infrastructure to handle authorization
and access control, traffic management, monitoring and analytics, version management, and software
development kit (SDK) generation.
API Gateway is designed for web and mobile developers who want to provide secure, reliable access
to back-end APIs for access from mobile apps, web apps, and server apps that are built internally or by
third-party ecosystem partners. The business logic behind the APIs can either be provided by a publicly
accessible endpoint that API Gateway proxies call, or it can be entirely run as a Lambda function.
To better understand the terminology used in this documentation, you may find it useful to peruse the
API Gateway Concepts (p. 2) section.
An app creator who may or may not have an AWS account and
interacts with the API deployed by the API developer. An app
developer can be represented by an API Key.
API Key
Method request
Integration request
Integration response
headers, and payload that are received from the back end into the
formats defined for an app developer.
Method response
Proxy Integration
Mapping template
Model
Usage plan
The following walkthroughs include hands-on exercises, using the API Gateway console, to help you
learn about API Gateway.
Topics
Get Ready to Use Amazon API Gateway (p. 4)
Build an API Gateway API as an HTTP Proxy (p. 6)
Build an API as a Lambda Proxy (p. 43)
Build an API Gateway API Using Proxy Integration and a Proxy Resource (p. 54)
Create an AWS Service Proxy for Amazon SNS (p. 64)
To grant the stated permissions to a user, attach the policy to the user, a group containing the user. To
attach a policy, see Attaching Managed Policies.
Attaching the preceding policy to an IAM user provides the user with access to all API Gateway
control service actions and resources associated with the AWS account. To learn how to restrict
IAM users to a limited set of API Gateway control service actions and resources, see Set IAM
Permissions (p. 141).
For the API Gateway execution service, the managed policy of
AmazonAPIGatewayInvokeFullAccess ( arn:aws:iam::aws:policy/
AmazonAPIGatewayInvokeFullAccess) provides full access to invoke an API in API Gateway:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": "arn:aws:execute-api:*:*:*"
}
]
}
Attaching the preceding policy to an IAM user provides the user with access to all API Gateway
execution service actions and resources associated with the AWS account. To learn how to restrict
IAM users to a limited set of API Gateway execution service actions and resources, see Set IAM
Permissions (p. 141).
To grant the state permissions to a user, attach the policy to the user, a group containing the user. To
attach a policy, see Attaching Managed Policies.
In this documentation, we will use managed policies, whenever possible. To create and use inline
policies, see Working with Inline Policies.
Note
To complete the steps above, you must have permission to create the IAM policy and attach it
to the desired IAM user.
Next Step
You are now ready to start using API Gateway. See Create an API Gateway API from an
Example (p. 7).
For the first API in your account, choose Get Started from the API Gateway console welcome
page:
If prompted with a modal dialog box containing hints at a stage of the process, choose OK to
close the modal dialog and continue.
b.
2.
For your next API, choose Create API from the API Gateway APIs home page:
Under Create new API, select Examples API and then choose Import to create the example API.
For your first API, the API Gateway console will start with this option as default.
You can scroll down the Swagger definition for details of this example API before choosing
Import.
3.
The API Gateway navigation pane on the left shows your available APIs, any API keys, custom
domain names and client certificates that you created for your APIs, as well as the settings for
logging your APIs' performance metrics. API-specific resources, deployment, custom authorizers
and payload-mapping data models are organized under individual APIs.
The Resources pane in the middle shows the structure of the selected API as a tree of nodes.
API methods defined on each resource are edges of the tree. When a resource is selected, all of
its methods are listed in the Methods pane on the right. Displayed under each method is a brief
summary of the method, including its endpoint URL, authorization type, and API Key requirement.
4.
To view the details of a method, to modify its set-up, or to test the method invocation, choose the
method name from either the method list or the resource tree.
The resulting Method Execution pane for the chosen method presents a logical view of the
method's structure and behaviors: a client accesses a back-end service by interacting with the
API through Method Request. API Gateway translates the client request, if necessary, into the
form acceptable to the back end before forwarding the request to the back end. The transformed
request is known as the integration request and is depicted by Integration Request in the display.
Similarly, the response from the back end goes through Integration Response and then Method
Response before being received by the client. Again, if necessary, API Gateway maps the
response from the form shaped in the back end to a form expected by the client.
For the POST method on this API's root (/) resource, the method's integration request shows that
the method is integrated with the endpoint of http://petstore-demo-endpoint.executeapi.com/petstore/pets in the back end. The method request payload will be passed through
to the integration request without modification. The GET / method request uses the MOCK
integration type and is not tied to any endpoint in the back end. When the method is called, the
API Gateway simply accepts the request and immediately returns a response, by way of from
Integration Response to Method Response. You can use the mock integration to test an API
without requiring a back-end endpoint. You can also use it to serve a local response. In fact, the
example API uses it to return a local HTML page as the home page of the API. It uses a mapping
template to generate the home page in Integration Response.
As an API developer, you control the behaviors of your API's front-end interactions by configuring
the method request and a method response. You control the behaviors of your API's back-end
interactions by setting up the integration request and integration response. They involve data
mappings between a method and its corresponding integration. We will cover the method setup in
Build an API Gateway API as an HTTP Proxy (p. 6). For now, we focus on testing the API to
provide an end-to-end user experience.
5.
Choose Test shown on Client (as shown in the previous image) to start testing. Enter the
following {"type": "dog","price": 249.99} payload into the Request Body before
choosing the Test button.
The input specifies the attributes of the pet that we wish to add to the list of pets on the PetStore
website.
6.
10
The Logs entry of the output shows the state changes from the method request to the integration
request and from the integration response to the method response. This can be useful for
troubleshooting any mapping errors that cause the request to fail. In this example, no mapping is
applied: the method request is identical to the integration request and the integration response is
the same as the method response.
To test the API using a client other than the API Gateway test-invoke-request feature, you must
first deploy the API to a stage.
7.
To deploy the sample API, select the PetStore API and the root / resource, and then choose
Deploy API from the Actions menu.
11
In Deploy API, for Deployment stage, choose [New Stage] because this is the first deployment
of the API. Type a name (e.g., test) in Stage name and, optionally, type descriptions in Stage
description and Deployment description. Choose Deploy.
In the resulting Stage Editor pane, Invoke URL displays the URL to invoke the API's GET /
method request.
12
8.
On Stage Editor, follow the Invoke URL link to submit the GET / method request in a browser.
The result, generated from the mapping template in the integration response, is shown as follows:
9.
In the Stages navigation pane, expand the test stage, select GET on /pets/{petId}, and then
copy the Invoke URL value of https://api-id.execute-api.region.amazonaws.com/
test/pets/{petId}. {petId} stands for a path variable.
Paste the Invoke URL value (obtained in the previous step) into the address bar of a browser,
replacing {petId} by, for example, 1, and press Enter to submit the request. A 200 OK response
should return with the following JSON payload:
{
"id": 1,
"type": "dog",
"price": 249.99
}
Invoking the API method as shown is possible because its Authorization type is set to NONE. If
the AWS_IAM authorization were used, you would sign the request using the Signature Version
13
4 protocols. For an example of such a request, see Build an API Gateway API as an HTTP
Proxy (p. 6).
From Create new API, select New API, type a name in API Name, optionally add a description in
Description, and then choose Create API.
As a result, an empty API is created. The Resources tree shows the root resource (/) without any
methods. In this exercise, we will build the API as an HTTP proxy of the PetStore demo website
(http://petstore-demo-endpoint.execute-api.come.) For illustration purposes, we will create a /
pets resource as a child of the root and expose a GET method on this resource for a client to
retrieve a list of available Pets items from the PetStore website.
2.
To create the /pets resource, select the root, choose Actions and then choose Create
Resource.
Type Pets in Resource Name, leave the Resource Path value as given, and choose Create
Resource.
14
3.
To expose a GET method on the /pets resource, choose Actions and then Create Method.
Choose GET from the list under the /pets resource node and choose the checkmark icon to finish
creating the method.
Note
Other options for an API method include:
POST, primarily used to create child resources.
PUT, primarily used to update existing resources (and, although not recommended, can
be used to create child resources).
DELETE, used to delete resources.
PATCH, used to update resources.
15
HEAD, primarily used in testing scenarios. It is the same as GET but does not return
the resource representation.
OPTIONS, which can be used by callers to get information about available
communication options for the target service.
The method created is not yet integrated with the back end. The next step sets this up.
4.
In the method's Setup pane, select HTTP Proxy for Integration type, select GET from the
HTTP method drop-down list, type http://petstore-demo-endpoint.execute-api.com/
petstore/pets as the Endpoint URL value, and then choose Save.
Note
For the integration request's HTTP method, you must choose one supported by the back
end. For HTTP Proxy or Mock integration, it makes sense that the method request
and the integration request use the same HTTP verb. For other integration types the
method request will likely use an HTTP verb different from the integration request. For
example, to call a Lambda function, the integration request must use POST to invoke the
function, whereas the method request may use any HTTP verb depending on the logic of
the Lambda function.
When the method setup finishes, you are presented with the Method Execution pane, where you
can further configure the method request to add query string or custom header parameters. You
can also update the integration request to map input data from the method request to the format
required by the back end.
The PetStore website allows you to retrieve a list of Pet items by the pet type (e.g., "Dog" or "Cat")
on a given page. It uses the type and page query string parameters to accept such input. As
such, we must add the query string parameters to the method request and map them into the
corresponding query strings of the integration request.
5.
In the GET method's Method Execution pane, choose Method Request, select AWS_IAM for
Authorization, expand the URL Query String Parameters section, and choose Add query
string to create two query string parameters named type and page. Choose the checkmark icon
to save the newly added query string parameters.
16
The client can now supply a pet type and a page number as query string parameters when
submitting a request. These input parameters must be mapped into the integration's query string
parameters to forward the input values to our PetStore website in the back end. Because the
method uses AWS_IAM, you must sign the request to invoke the method.
6.
From the method's Integration Request page, expand the URL Query String Parameters
section. By default, the method request query string parameters are mapped to the like-named
integration request query string parameters. This default mapping works for our demo API. We
will leave them as given. To map a different method request parameter to the corresponding
integration request parameter, choose the pencil icon for the parameter to edit the mapping
expression, shown in the Mapped from column. To map a method request parameter to a
different integration request parameter, first choose the delete icon to remove the existing
integration request parameter, choose Add query string to specify a new name and the desired
method request parameter mapping expression.
17
This completes building the simple demo API. It's time to test the API.
7.
To test the API using the API Gateway console, choose Test from the GET-on-Pets method's
Method Execution pane. In the Method Test pane, enter Dog and 2 for the type and page query
strings, respectively, and then choose Test.
18
The result is shown as follows. (You may need to scroll down to see the test result.)
19
Now that the test is successful, we can deploy the API to make it publicly available.
8.
To deploy the API, select the API and then choose Deploy API from the Actions drop-down
menu.
In the Deploy API dialog, choose a stage (or [New Stage] for the API's first deployment);
enter a name (e.g., "test", "prod", "dev", etc.) in the Stage name input field; optionally, provide a
description in Stage description and/or Deployment description; and then choose Deploy.
20
Once deployed, you can obtain the invocation URLs (Invoke URL) of the API's endpoints. For
example, the GET on Pets method's invocation URL is as follows:
To invoke this API method in a client (e.g., a Postman browser), append the query string
parameters to the stage-specific method invocation URL (as shown in the previous image) to
create the complete method request URL:
https://api-id.execute-api.region.amazonaws.com/test/pets?type=Dog&page=2
Specify this URL in the address bar of the browser. Choose GET as the HTTP verb. Select
AWS Signature for the Authorization type and then specify the required properties (as shown),
following the Signature Version 4 protocols. Finally, send the request.
21
If you use an SDK to create a client, you can call the methods exposed by the SDK to sign the
request. For implementation details, see the AWS SDK of your choosing.
Note
When changes are made to your API, you must redeploy the API to make the new or
updated features available before invoking the request URL again.
If you copy the above URL, paste it into the address bar of a web browser, and hit the Enter or
Return key, you will get the following JSON-formatted response body:
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
The above endpoint can take two query parameters: type and page. For example, if you change the
above URL to the following:
22
http://petstore-demo-endpoint.execute-api.com/petstore/pets?type=cat&page=2
you will receive the following JSON-formatted response payload, displaying page 2 of only the cats:
[
{
"id": 4,
"type": "cat",
"price": 999.99
},
{
"id": 5,
"type": "cat",
"price": 249.99
},
{
"id": 6,
"type": "cat",
"price": 49.97
}
]
This endpoint also supports the use of an item ID, as expressed by a URL path parameter. For
example, if you browse to the following:
http://petstore-demo-endpoint.execute-api.com/petstore/pets/1
In addition to supporting GET operations, this endpoint also take POST requests with a payload. For
example, if you use Postman to send a POST method request to the following:
http://petstore-demo-endpoint.execute-api.com/petstore/pets
including the header Content-type: application/json and the following request body:
{
"type": "dog",
"price": 249.99
}
23
"price": 249.99
},
"message": "success"
}
We now expose these and other features by building an API Gateway API as an HTTP proxy of this
PetStore website. The tasks includes the following:
Create an API with a resource of https://my-api-id.execute-api.regionid.amazonaws.com/test/petstorewalkthrough/pets acting as a proxy to the HTTP endpoint
of http://petstore-demo-endpoint.execute-api.com/petstore/pets.
Enable the API to accept two method request query parameters of petType and petsPage, map
them to the type and page query parameters of the integration request, respectively, and pass the
request to the HTTP endpoint.
Support a path parameter of {petId} on the API's method request URL to specify an item ID, map
it to the {id} path parameter in the integration request URL, and send the request to the HTTP
endpoint.
Enable the method request to accept the JSON payload of the format defined by the back end
website, pass the payload without modifications through the integration request to the back-end
HTTP endpoint.
Topics
Prerequisites (p. 24)
Step 1: Create Resources (p. 24)
Step 2: Create GET and POST Methods (p. 25)
Step 3: Set Up and Test the Methods (p. 25)
Step 4: Deploy the API (p. 28)
Step 5: Test the API (p. 28)
Next Steps (p. 30)
Prerequisites
Before you begin this walkthrough, you should do the following:
1.
Complete the steps in Get Ready to Use API Gateway (p. 4), including assigning API
Gateway access permission to the IAM user.
2.
At a minimum, follow the steps in Build an API Gateway API as an HTTP Proxy (p. 6) to
create a new API named MyDemoAPI in the API Gateway console.
In the Resources pane, select the resource root, as represented by a single forward slash (/),
and then choose Create Resource from the Actions drop-down menu.
2.
24
3.
For Resource Path, accept the default of /petstorewalkthrough, and then choose Create
Resource.
This maps to /petstore in the HTTP endpoint.
In the Resources pane, choose /petstorewalkthrough, and then choose Create Resource.
2.
3.
For Resource Path, accept the default of /petstorewalkthrough/pets, and then choose Create
Resource.
This maps to /petstore/pets in the HTTP endpoint.
In the Resources pane, choose /petstorewalkthrough/pets, and then choose Create Resource.
2.
For Resource Name, type petId. This maps to the item ID in the HTTP endpoint.
3.
For Resource Path, overwrite petid with {petId}. Be sure to use curly braces ({ }) around
petId so that /petstorewalkthrough/pets/{petId} is displayed, and then choose Create
Resource.
This maps to /petstore/pets/my-item-id in the HTTP endpoint.
In the Resources pane, choose /petstorewalkthrough/pets, and then choose Create Method
from the Actions drop-down menu.
2.
For the HTTP method, choose GET, and then save your choice.
2.
For the HTTP method, choose GET, and then save your choice.
In the Resources pane, choose /petstorewalkthrough/pets again, and then choose Create
Method.
2.
For the HTTP method, choose POST, and then save your choice.
25
2.
3.
4.
Choose Save.
5.
In the Method Execution pane, choose Method Request, and then choose the arrow next to
URL Query String Parameters.
6.
7.
8.
9.
"type": "cat",
"price": 999.99
},
{
"id": 5,
"type": "cat",
"price": 249.99
},
{
"id": 6,
"type": "cat",
"price": 49.97
}
]
2.
3.
4.
Choose Save.
5.
In the Method Execution pane, choose Integration Request, and then choose the arrow next to
URL Path Parameters.
6.
7.
8.
9.
Choose Create.
10. Choose Method Execution, and in the Client box, choose TEST. In the Path area, for petId, type
1.
11. Choose Test. If successful, Response Body will display the following:
{
"id": 1,
"type": "dog",
"price": 249.99
}
27
Integrate the method request of POST /petstorewalkthrough/pets with the integration request
of POST https://petstore-demo-endpoint.execute-api.com/petstore/pets.
Pass the method request JSON payload through to the integration request payload, without
modification.
1.
2.
3.
4.
5.
{
"type": "dog",
"price": 249.99
}
6.
Note
3.
4.
In the Stage Editor pane, next to Invoke URL, copy the URL to the clipboard. It should look
something like this:
https://my-api-id.execute-api.region-id.amazonaws.com/test
2.
28
3.
4.
5.
6.
7.
29
{
"id": 1,
"type": "dog",
"price": 249.99
}
8.
Using a web debugging proxy tool or the cURL command-line tool, send a POST method request
to the URL from the previous procedure. Be sure to append /petstorewalkthrough/pets so
that it looks like this:
https://my-api-id.execute-api.region-id.amazonaws.com/test/
petstorewalkthrough/pets
For example, if you use the cURL command-line tool, run a command similar to the following:
curl -H "Content-Type: application/json" -X POST -d "{\"type\":
\"dog\",\"price\": 249.99}" https://my-api-id.execute-api.regionid.amazonaws.com/test/petstorewalkthrough/pets
Next Steps
You may want to begin the next walkthrough, which shows you how to use models and mappings
in API Gateway to transform the output of an API call from one data format to another. See Map
Response Payload (p. 30).
30
instructions and concepts in the Build an API as a Lambda Proxy (p. 43) and the Map Request
Parameters (p. 22). If you have not yet completed those walkthroughs, we suggest you do them
first.
In this walkthrough, you will use API Gateway to get example data from a publicly-accessible HTTP
endpoint and from an AWS Lambda function you will create. Both the HTTP endpoint and the Lambda
function return the same example data:
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
You will use models and mapping templates to transform this data to one or more output formats. In
API Gateway, a model defines the format, also known as the schema or shape, of some data. In API
Gateway, a mapping template is used to transform some data from one format to another. For more
information, see Set Up Payload Mappings (p. 88).
The first model and mapping template is used to rename id to number, type to class, and price to
salesPrice, as follows:
[
{
"number": 1,
"class": "dog",
"salesPrice": 249.99
},
{
"number": 2,
"class": "cat",
"salesPrice": 124.99
},
{
"number": 3,
"class": "fish",
"salesPrice": 0.99
}
]
The second model and mapping template is used to combine id and type into description, and to
rename price to askingPrice, as follows:
[
{
31
The third model and mapping template is used to combine id, type, and price into a set of
listings, as follows:
{
"listings": [
"Item 1 is a dog. The asking price is 249.99.",
"Item 2 is a cat. The asking price is 124.99.",
"Item 3 is a fish. The asking price is 0.99."
]
}
Topics
Prerequisites (p. 32)
Step 1: Create Models (p. 33)
Step 2: Create Resources (p. 35)
Step 3: Create GET Methods (p. 35)
Step 4: Create a Lambda Function (p. 36)
Step 5: Set Up and Test the Methods (p. 37)
Step 6: Deploy the API (p. 41)
Step 7: Test the API (p. 41)
Step 8: Clean Up (p. 43)
Next Steps (p. 43)
Prerequisites
Before you begin this walkthrough, you should have already done the following:
1.
Complete the steps in Get Ready to Use API Gateway (p. 4), including assigning API
Gateway access permission to an IAM user.
2.
Open the API Gateway console and create a new API named MyDemoAPI. For more information,
see Build an API Gateway API as an HTTP Proxy (p. 6).
3.
Create two resources: petstorewalkthrough and pets. For more information, see Create
Resources (p. 24) in the Map Request Parameters (p. 22).
4.
To use the Lambda portions of this walkthrough, make sure the IAM user has full access to
work with Lambda. You can use the IAM console to attach the AWSLambdaFullAccess AWS
managed policy to the IAM user.
5.
Make sure the IAM user has access to create policies and roles in IAM. If you have not done
so already, create a Lambda execution role named APIGatewayLambdaExecRole in IAM. For
32
more information, see Create Lambda Functions (p. 44) in the Build an API as a Lambda
Proxy (p. 43).
2.
3.
Choose Create.
4.
5.
6.
For Model description, type Changes id to number, type to class, and price to
salesPrice.
7.
8.
Choose Create.
2.
3.
4.
For Model description, type Combines id and type into description, and changes
price to askingPrice.
5.
33
6.
Choose Create.
2.
3.
4.
For Model description, type Combines id, type, and price into a set of listings.
5.
6.
Choose Create.
2.
3.
4.
5.
6.
34
3.
4.
In the Resources pane, choose /petstorewalkthrough again, and then choose Create
Resource.
2.
3.
For Resource Path, accept the default of /petstorewalkthrough/flattensome, and then choose
Create Resource.
In the Resources pane, choose /petstorewalkthrough again, and then choose Create
Resource.
For Resource Name, type FlattenAll.
For Resource Path, accept the default of /petstorewalkthrough/flattenall, and then choose
Create Resource.
In the Resources pane, choose /petstorewalkthrough again, and then choose Create
Resource.
For Resource Name, type LambdaFlattenSome.
For Resource Path, accept the default of /petstorewalkthrough/lambdaflattensome, and then
choose Create Resource.
In the Resources list, choose /petstorewalkthrough/flattenall, and then choose Create Method.
2.
For the HTTP method, choose GET, and then save your choice.
35
2.
For the HTTP method, choose GET, and then save your choice.
2.
For the HTTP method, choose GET, and then save your choice.
2.
For the HTTP method, choose GET, and then save your choice.
2.
3.
4.
5.
6.
Tip
In the preceding code, written in Node.js, console.log writes information to an Amazon
CloudWatch log. event contains the event's data. context contains callback context.
Lambda uses context.done to perform follow-up actions. For more information about
how to write Lambda function code, see the "Programming Model" section in AWS
Lambda: How it Works and the sample walkthroughs in the AWS Lambda Developer
Guide.
7.
8.
For Role, choose the Lambda execution role, APIGatewayLambdaExecRole, you created in the
Build an API as a Lambda Proxy (p. 43).
9.
10. In the list of functions, choose GetPetsInfo to show the function's details.
11. Make a note of the AWS region where you created this function. You will need it later.
36
Tip
The empty curly braces mean there are no input values for this Lambda function. This
function simply returns the JSON object containing the pets information, so those key/
value pairs are not required here.
14. Choose Invoke. Execution result shows [{"id":1,"type":"dog","price":249.99},
{"id":2,"type":"cat","price":124.99},{"id":3,"type":"fish","price":0.99}],
which is also written to the CloudWatch logs.
15. Choose Go to function list.
To specify settings for the first GET method and then test it
1.
2.
3.
4.
Choose Save.
5.
In the Method Execution pane, choose Method Response, and then choose the arrow next to
200.
6.
In the Response Models for 200 area, for application/json, choose Edit. For Models, choose
PetsModelFlattenAll, and then choose Save.
7.
Choose Method Execution, choose Integration Response, and then choose the arrow next to
200.
8.
In the Template Mappings area, for Content type, choose application/json, and then
choose Edit. Clear Output passthrough. For Generate template from model, choose
PetsModelFlattenAll. This displays the PetsModelFlattenAll model as a starting point.
9.
37
11. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If
successful, Response Body will display the following:
{
"listings" : [
"Item number 1 is a dog. The asking price is 249.99.",
"Item number 2 is a cat. The asking price is 124.99.",
"Item number 3 is a fish. The asking price is 0.99."
]
}
To specify settings for the second GET method and then test it
1.
2.
3.
For Lambda Region, choose the region identifier that corresponds to the region in which you
created the GetPetsInfo Lambda function. For example, if you created this Lambda in the US
East (N. Virginia) region, you would choose us-east-1. For a list of region names and identifiers,
see AWS Lambda in the Amazon Web Services General Reference.
4.
5.
When you are prompted to give API Gateway permission to invoke your Lambda function, choose
Ok.
6.
7.
8.
9.
Leave Input passthrough cleared. For Generate template from model, choose
PetsLambdaModel. This displays the PetsLambdaModel model as a starting point.
10. In the Input mapping area, modify the code as follows, and then choose Update:
#set($inputRoot = $input.path('$'))
[
#foreach($elem in $inputRoot)
{
"id" : $elem.id,
"type" : "$elem.type",
"price" : $elem.price
}#if($foreach.hasNext),#end
#end
]
11. Choose Method Execution, choose Method Response, and then choose the arrow next to 200.
12. In the Response Models for 200 area, for application/json, choose Edit. For Models, choose
PetsModelFlattenSome, and then choose Save.
13. Choose Method Execution, choose Integration Response, and then choose the arrow next to
200.
14. In the Template Mappings area, for Content type, choose application/json, and then
choose Edit. Clear Output passthrough. For Generate template from model, choose
PetsModelFlattenSome. This displays the PetsModelFlattenSome model as a starting point.
15. Modify the code as follows, and then choose Update:
#set($inputRoot = $input.path('$'))
38
[
#foreach($elem in $inputRoot)
{
"description" : "Item $elem.id is a $elem.type.",
"askingPrice" : $elem.price
}#if($foreach.hasNext),#end
#end
]
16. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If
successful, Response Body will display the following:
[
{
"description" : "Item 1 is a dog.",
"askingPrice" : 249.99
},
{
"description" : "Item 2 is a cat.",
"askingPrice" : 124.99
},
{
"description" : "Item 3 is a fish.",
"askingPrice" : 0.99
}
]
To specify settings for the third GET method and then test it
1.
2.
3.
4.
Choose Save.
5.
In the Method Execution pane, choose Method Response, and then choose the arrow next to
200.
6.
In the Response Models for 200 area, for application/json, choose Edit. For Models, choose
PetsModelFlattenSome, and then choose Save.
7.
Choose Method Execution, choose Integration Response, and then choose the arrow next to
200.
8.
In the Template Mappings area, for Content type, choose application/json, and then
choose Edit. Clear Output passthrough. For Generate template from model, choose
PetsModelFlattenSome. This displays the PetsModelFlattenSome model as a starting point.
9.
39
#end
]
To specify settings for the fourth GET method and then test it
1.
2.
3.
4.
5.
6.
Choose Save.
7.
In the Method Execution pane, choose Method Response, and then expand 200.
8.
In the Response Models for 200 area, for application/json, choose Edit. For Models, choose
PetsModelNoFlatten, and then choose Save.
9.
Choose Method Execution, choose Integration Response, and then choose the arrow next to
200.
10. In the Template Mappings area, for Content type, choose application/json, and then
choose Edit. Clear Output passthrough. For Generate template from model, choose
PetsModelNoFlatten. This displays the PetsModelNoFlatten model as a starting point.
11. Modify the code as follows:
#set($inputRoot = $input.path('$'))
[
#foreach($elem in $inputRoot)
{
"number": $elem.id,
"class": "$elem.type",
"salesPrice": $elem.price
}#if($foreach.hasNext),#end
#end
]
40
13. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If
successful, Response Body will display the following:
[
{
"number": 1,
"class": "dog",
"salesPrice": 249.99
},
{
"number": 2,
"class": "cat",
"salesPrice": 124.99
},
{
"number": 3,
"class": "fish",
"salesPrice": 0.99
}
]
2.
3.
For Deployment description, type Using models and mapping templates walkthrough.
4.
Choose Deploy.
In the Stage Editor pane, next to Invoke URL, copy the URL to the clipboard. It should look
something like this:
https://my-api-id.execute-api.region-id.amazonaws.com/test
2.
3.
41
"class": "dog",
"salesPrice": 249.99
},
{
"number": 2,
"class": "cat",
"salesPrice": 124.99
},
{
"number": 3,
"class": "fish",
"salesPrice": 0.99
}
]
4.
5.
6.
7.
8.
9.
42
Step 8: Clean Up
If you no longer need the Lambda function you created for this walkthrough, you can delete it now. You
can also delete the accompanying IAM resources.
Caution
If you delete a Lambda function your APIs rely on, those APIs will no longer work. Deleting a
Lambda function cannot be undone. If you want to use the Lambda function again, you must
re-create the function.
If you delete an IAM resource a Lambda function relies on, the Lambda function and any
APIs that rely on it will no longer work. Deleting an IAM resource cannot be undone. If you
want to use the IAM resource again, you must re-create the resource. If you plan to continue
experimenting with the resources you created for this and the other walkthroughs, do not
delete the Lambda invocation role or the Lambda execution role.
API Gateway does not currently support the deactivation or deletion of APIs that no longer
work.
Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2.
On the Lambda: Function list page, in the list of functions, choose the button next to
GetPetsInfo, and then choose Actions, Delete. When prompted, choose Delete again.
2.
3.
Select APIGatewayLambdaExecRole, and then choose Role Actions, Delete Role. When
prompted, choose Yes, Delete.
4.
5.
Next Steps
You may want to begin the next walkthrough, which shows you how to create an API Gateway API to
access an AWS service. See Create an AWS Service Proxy (p. 64).
43
walkthrough, you learn how to create Lambda functions and build an API Gateway API to enable a
Web client to call the Lambda functions synchronously. For more information about Lambda, see the
AWS Lambda Developer Guide. For information about asynchronous invocation of Lambda functions,
see Create an API as a Lambda Proxy (p. 229).
Topics
Step 1: Prerequisites (p. 44)
Step 2: Create an API (p. 44)
Step 3: Create a Resource (p. 44)
Step 4: Create Lambda Functions (p. 44)
Step 5: Create and Test a GET Method (p. 47)
Step 6: Create and Test a POST Method (p. 48)
Step 7: Deploy the API (p. 49)
Step 8: Test the API (p. 50)
Step 9: Clean Up (p. 51)
Next Steps (p. 52)
Create Lambda Invocation and Execution Roles (p. 52)
Step 1: Prerequisites
You must grant API Gateway access permission to the IAM user who will perform the tasks
discussed here. The IAM user must have full access to work with Lambda. For this, you can use
or customize the managed policy of AWSLambdaFullAccess (arn:aws:iam::aws:policy/
AWSLambdaFullAccess) and attach it to the IAM user. For more information, see Get Ready to Use
API Gateway (p. 4). The IAM user must also be allowed to create policies and roles in IAM. For
this you can use or customize the managed policy of IAMFullAccess (arn:aws:iam::aws:policy/
IAMFullAccess and attach it to the user.
44
You will use the Lambda console to create the Lambda functions and set up the required execution
role/policy. You will then use the API Gateway console to create an API to integrate API methods with
the Lambda functions; the API Gateway console will set up the required Lambda invocation role/policy.
If you set up the API without using the API Gateway console, such as when importing an API from
Swagger, you must explicitly create, if necessary, and set up an invocation role/policy for API Gateway
to invoke the Lambda functions. For more information on how to set up Lambda invocation and
execution roles, see Create Lambda Invocation and Execution Roles (p. 52). For more information
about Lambda see AWS Lambda Developer Guide.
2.
3.
From Select blueprint, select the hello-world blueprint for nodejs. You may need to type Hello
as the search filter to bring the blueprint in focus.
4.
5.
6.
7.
Under Lambda function code, replace the default code statements in the inline code editor with
the following:
'use strict';
console.log('Loading event');
exports.handler = function(event, context) {
console.log('"Hello":"World"');
context.done(null, {"Hello":"World"}); // SUCCESS with message
};
Tip
The preceding code is written in Node.js. The console.log method writes information
to an Amazon CloudWatch Log. The event parameter contains the event's data. The
context parameter contains callback context. Lambda uses context.done to perform
follow-up actions. For more information about how to write Lambda function code,
see the "Programming Model" section in AWS Lambda: How it Works and the sample
walkthroughs in the AWS Lambda Developer Guide.
8.
Under Lambda function handler and role, leave the default of index.handler for Handler.
9.
For Role, choose * Basic execution role under Create new role.
a.
b.
Leave the default selection of Create a new Role Policy for Policy Name.
c.
Choose Allow.
45
15. For Input test event, replace any default code statements with the following, and then choose
Save and test.
{
}
Tip
This function does not use any input. Therefore, we provide an empty JSON object as the
input.
16. Choose Test to invoke the function. The Execution result section shows {"Hello": "World"}.
The output is also written to CloudWatch Logs.
17. Go to the Functions list to create the next Lambda function.
In addition to the Lambda function, an IAM role (lambda_basic_execution) is also created as
the result of this procedure. You can view this in the IAM console. Attached to this IAM role is the
following inline policy that grants users of your AWS account permission to call the CloudWatch
CreateLogGroup, CreateLogStreams, and PutLogEvents actions on any of the CloudWatch
resources.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
}
]
}
A trusted entity of this IAM role is lambda.amazonaws.com, which has the following trust relationship:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
The combination of this trust relationship and the inline policy makes it possible for the user to invoke
the Lambda function and for Lambda to call the supported CloudWatch actions on the user's behalf.
46
2.
3.
4.
5.
6.
In the code editor under Lambda function code replace the default code statements with the
following:
'use strict';
console.log('Loading event');
exports.handler = function(event, context) {
var name = (event.name === undefined ? 'No-Name' : event.name);
console.log('"Hello":"' + name + '"');
context.done(null, {"Hello":name}); // SUCCESS with message
};
7.
Under Lambda function handler and role, leave the default of index.handler for Handler.
8.
For Role, choose lambda_basic_execution under Use existing role, assuming you have
created the lambda_basic_execution role in the previous procedure.
9.
Leave the default values for Advanced settings. Then choose Next.
Tip
The function calls context.name to read the input name. We expect it to return
{"Hello": "User"}, given the above input.
You can experiment with this function by removing "name": "User" from the Input test event
for the function and choosing Save and test again. You should see the output of {"Hello":
"No-Name"} under Execution result in the Lambda console, as well as in CloudWatch Logs.
47
2.
In the Resources pane, choose /mydemoresource. From Actions, choose Create Method.
Choose GET from the HTTP method drop-down list and then choose the checkmark to create the
method.
3.
In the GET method Setup pane, for Integration type, choose Lambda Function. For Lambda
Region, choose the region (.e.g, us-east-1) where you created the Lambda functions. In
Lambda Function, type GetHelloWorld. Choose Save to finish setting up the integration
request for this method.
For a list of region names and identifiers, see AWS Lambda in the Amazon Web Services General
Reference.
4.
5.
In the Method Execution pane, choose TEST from the Client box, and then choose the Test
button. If successful, Response Body will display the following:
{
"Hello": "World"
}
By default, API Gateway will pass through the request from the API caller. For the GET method call
you just created, as well as for HEAD method calls, a Lambda function will receive an empty JSON
response by default and then return the response from the Lambda function without modifications.
In the next step, you will create a POST method call. For POST and PUT method calls, you can pass
in a request body in JSON format, which the Lambda function will receive as its input event. Optionally,
you can transform the input to the Lambda function by using mapping templates in API Gateway.
In the Resources pane, choose /mydemoresource, and then choose Create Method.
2.
For the HTTP method, choose POST, and then choose the checkmark to save your choice.
3.
4.
For Lambda Region, choose the region identifier that corresponds to the region name in which
you created the GetHelloWithName Lambda function.
48
5.
6.
When you are prompted to give API Gateway permission to invoke your Lambda function, choose
OK.
7.
In the Method Execution pane, in the Client box, and then choose TEST. Expand Request
Body, and type the following:
{
"name": "User"
}
8.
9.
Change Request Body by removing "name": "User" so that only a set of curly braces ({ })
remain, and then choose Test again. If successful, Response Body will display the following:
{
"Hello": "No-Name"
}
The API Gateway console-assisted Lambda function integration uses the AWS service proxy
integration type for Lambda. It streamlines the process to integrate an API method with a Lambda
function by setting up, among other things, the required Lambda function invocation URI and the
invocation role on behalf of the API developer.
The GET and POST methods discussed here are both integrated with a POST request in the back end:
POST /2015-03-31/functions/FunctionArn/invocations?Qualifier=Qualifier
HTTP/1.1
X-Amz-Invocation-Type: RequestReponse
...
Content-Type: application/json
Content-Length: PayloadSize
Payload
49
deployment is accessible. For example, you can define a test stage and deploy your API to it, so that
a resource named MyDemoAPI is accessible through a URI that ends in .../test/MyDemoAPI.
Choose the API from the APIs pane or choose a resource or method from the Resources pane.
Choose Deploy API from the Actions drop-down menu.
2.
3.
Note
The input must be UTF-8 encoded (i.e., unlocalized) text.
4.
5.
6.
Choose Deploy.
In the Stage Editor pane, copy the URL from Invoke URL to the clipboard. It should look
something like this:
https://my-api-id.execute-api.region-id.amazonaws.com/test
2.
In a separate web browser tab or window, paste the URL into the address box. Append the path
to your resource (/mydemoresource) to the end of the URL. The URL should look something like
this:
https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoresource
3.
Browse to this URL. If the GET method is successfully called, the web page will display:
{"Hello":"World"}
You will not be able to test a POST method request with your web browser's address bar. Instead,
use an advanced REST API client, such as Postman, or the cURL command-line tool.
2.
Send a POST method request to the URL from the previous procedure. The URL should look
something like this:
https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoresource
50
{
"name": "User"
}
For example, if you use the cURL command-line tool, run a command similar to the following:
curl -H "Content-Type: application/json" -X POST -d "{\"name\": \"User\"}"
https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoresource
Step 9: Clean Up
If you no longer need the Lambda functions you created for this walkthrough, you can delete them now.
You can also delete the accompanying IAM resources.
Caution
If you plan to complete the other walkthroughs in this series, do not delete the Lambda
execution role or the Lambda invocation role. If you delete a Lambda function that your APIs
rely on, those APIs will no longer work. Deleting a Lambda function cannot be undone. If you
want to use the Lambda function again, you must re-create the function.
If you delete an IAM resource that a Lambda function relies on, that Lambda function will
no longer work, and any APIs that rely on that function will no longer work. Deleting an IAM
resource cannot be undone. If you want to use the IAM resource again, you must re-create
the resource.
Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2.
From the list of functions, choose GetHelloWorld, choose Actions and then choose Delete
function. When prompted, choose Delete again.
3.
From the list of functions, choose GetHelloWithName, choose Actions, and then choose Delete
function. When prompted, choose Delete again.
2.
3.
From the list of roles, choose APIGatewayLambdaExecRole, choose Role Actions and then
choose Delete Role. When prompted, choose Yes, Delete.
4.
5.
From the list of policies, choose APIGatewayLambdaExecPolicy, choose Policy Actions and
then choose Delete. When prompted, choose Delete.
51
Next Steps
You may want to proceed to the next walkthrough, which shows how to map header parameters
from the method request to the integration request and from the integration response to the method
response. It uses the HTTP proxy integration to connect your API to HTTP endpoints in the back end.
For more information about API Gateway, see What Is Amazon API Gateway? (p. 1). For more
information about REST, see RESTful Web Services: A Tutorial.
2.
3.
4.
5.
For Policy Name, type a name for the policy; for example, APIGatewayLambdaInvokePolicy.
6.
7.
For Policy Document, type the following, and then choose Create Policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": [
"*"
],
"Action": [
"lambda:InvokeFunction"
]
}
]
}
8.
9.
10. For Role Name, type a name for the invocation role; for example,
APIGatewayLambdaInvokeRole, and then choose Next Step.
52
11. Under Select Role Type, with the option button next to AWS Service Roles already chosen, for
Amazon API Gateway, choose Select.
12. For Attach Policy, if the policy you want is in the list, choose it before choosing Next Step.
Otherwise, simply choose Next Step to proceed.
13. For Role ARN, make a note of the invocation role's Amazon Resource Name (ARN). You will
need this ARN in later steps when you specify the invocation role explicitly. The ARN should look
similar to this: arn:aws:iam::123456789012:role/APIGatewayLambdaInvokeRole, where
123456789012 is your AWS account ID.
14. Choose Create Role.
The newly created IAM role will have the following trust policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
The preceding policy document enables API Gateway to assume roles taken up by and, hence,
take actions on behalf of your AWS account.
2.
3.
4.
5.
For Policy Name, type a name for the policy (for example, APIGatewayLambdaExecPolicy).
6.
7.
For Policy Document, type the following, and then choose Create Policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:*"
],
"Effect": "Allow",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
53
Note
The preceding policy document permits all log actions on Amazon CloudWatch Logs.
Typically, you would add other permissions required by your Lambda function to interact
with AWS services, such as uploading an object to an Amazon S3 bucket. In this
walkthrough, the Lambda functions you create are very simple; they do not interact with
AWS services.
8.
9.
10. In Role Name, type a name for the execution role (for example, APIGatewayLambdaExecRole),
and then choose Next Step.
11. Next to AWS Lambda, choose Select.
Note
IAM will attach the following resource-policy document in Trust Relationships:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
This policy document enables Lambda to assume roles taken up by and, hence, to take
actions on behalf of your AWS account.
54
To build an API with HTTP Proxy Integration with the PetStore website through a proxy
resource
1.
2.
To create an API, choose Create new API (for creating the first API) or Create API (for creating
any subsequent API). Next, do the following:
a.
b.
c.
d.
To create a child resource, choose a parent resource item under the Resources tree and then
choose Create Resource from the Actions drop-down menu. Then, do the following in the New
Child Resource pane.
a.
Select the Configure as proxy resource option to create a proxy resource. Otherwise, leave
it de-selected.
b.
c.
Type a new name or use the default name in the Resource Path* input text field.
d.
e.
For this tutorial, select Configure as proxy resource. For Resource Name, use the default,
proxy. For Resource Path, use /{proxy+}. Select Enable API Gateway CORS.
55
4.
To set up the ANY method for integration with the HTTP back end, do the following:
a.
b.
c.
56
To test an API integrated with the PetStore website using HTTP proxy integration
through the proxy resource
1.
To use the API Gateway console to test invoking the API, do the following.
a.
b.
c.
From the Method drop-down list, choose an HTTP verb supported by the back end.
d.
Under Path, type a specific path for the proxy resource supporting the chosen operation.
e.
If required, type a supported query expression for the chosen operation under the Query
Strings heading.
f.
If required, type one or more supported header expressions for the chosen operation under
the Headers heading.
g.
If configured, set the required stage variable values for the chosen operation under the Stage
Variables heading.
h.
If prompted and required, choose an API Gateway-generated client certificate under the
Client Certificate heading to the operation to be authenticated by the back end.
i.
If prompted, type an appropriate request body in the text editor under the Request Body
heading.
j.
57
For this tutorial, use GET for the ANY method, use petstore/pets in place of the proxy resource
path ({proxy}), and type=fish for the query string.
Because the back-end website supports the GET /petstore/pets?type=fish request, it will
return a successful response similar to the following:
[
{
"id": 1,
"type": "fish",
"price": 249.99
},
{
"id": 2,
"type": "fish",
58
If you try to call GET /petstore, you will get a 404 response with an error message of Cannot
GET /petstore. This is because the back end does not support the specified operation. On the
other, if you call GET /petstore/pets/1, you will get a 200 OK response with the following
payload, because the request is supported by the PetStore website.
{
"id": 1,
"type": "dog",
"price": 249.99
}
2.
To use a browser to call a GET method on a specific resource of the API, do the following.
a.
If you have not done so, choose Deploy API from the Actions drop-down menu for the API
you created. Follow the instructions to deploy the API to a specific stage. Note the Invoke
URL that displays on the resulting Stage Editor page. This is the base URL of the API.
b.
To submit a GET request on a specific resource, append the resource path, including possible
query string expressions to the Invoke URL value obtained in the previous step, copy the
complete URL into the address bar of a browser, and choose Enter.
For this tutorial, deploy the API to a test stage, append petstore/pets?type=fish to
the API's Invoke URL. This produces a URL of https://4z9giyi2c1.execute-api.uswest-2.amazonaws.com/test/petstore/pets?type=fish.
The result should be the same as the result that is returned when you use TestInvoke from the
API Gateway console.
59
When used with a proxy resource in API Gateway, the input contains an API request marshalled by
API Gateway. The input can include the request's HTTP method, path, query parameters, headers,
and payload as well as the context and stage variables. This example Lambda function parses the
query string parameters of name and httpStatus from the input (event). The function then returns
a greeting to the named user in the message property of the responseBody object. The function also
outputs the caller-supplied HTTP status code as part of a response object. If name and httpStatus
60
query parameters are not set, the default values ("World" and 200, respectively) are returned instead.
In any case, the response body contains event, which is the input to the Lambda function. When
structured as shown, the Lambda function output is un-marshalled by API Gateway and returned to the
client as an HTTP response.
Create a Lambda function for an API with a proxy resource in the Lambda console
For this tutorial, use LambdaForSimpleProxy as the function name and choose the standard Simple
Microservice permissions policy templates to create the required Lambda execution role.
1.
2.
From the upper-right corner of the console, choose an available region for the Lambda function.
3.
4.
b.
c.
d.
e.
f.
g.
Choose Next.
h.
Note
Make note of the region where you created the Lambda function. You will need it next when
creating the API for the function.
2.
To create an API, choose Create new API (for creating the first API) or Create API (for creating
any subsequent API). Next, do the following:
61
a.
b.
c.
d.
To create a child resource, choose a parent resource item under the Resources tree and then
choose Create Resource from the Actions drop-down menu. Then, do the following in the New
Child Resource pane.
a.
Select the Configure as proxy resource option to create a proxy resource. Otherwise, leave
it de-selected.
b.
c.
Type a new name or use the default name in the Resource Path* input text field.
d.
e.
For this tutorial, use the root resource (/) as the parent resource. Select Configure as proxy
resource. For Resource Name, use the default, proxy. For Resource Path, use /{proxy+}.
De-select Enable API Gateway CORS.
4.
To set up the ANY method for integration with the Lambda back end, do the following:
a.
b.
c.
d.
Choose Save.
e.
For this tutorial, use the previously created LambdaForProxyResource for the Lambda
Function.
For the proxy resource API that Lambda just created, API Gateway forwards the raw request from the
client to the back end for the Lambda function to process. The request includes the request method,
its path, query string and headers parameters, any payload, and context and stage variables. The next
procedure describes how to test this.
To use a browser to call a GET method on a specific resource of the API, do the following.
a.
If you have not done so, choose Deploy API from the Actions drop-down menu for the API
you created. Follow the instructions to deploy the API to a specific stage. Note the Invoke
URL that displays on the resulting Stage Editor page. This is the base URL of the API.
b.
To submit a GET request on a specific resource, append the resource path, including possible
query string expressions to the Invoke URL value obtained in the previous step, copy the
complete URL into the address bar of a browser, and choose Enter.
62
For this tutorial, deploy the API to a test stage and append hello?name=me to the
API's base URL to produce a URL of https://wt6mne2s9k.execute-api.uswest-2.amazonaws.com/test/hello?name=me.
The successful response returns a result similar to the following output from the back-end
Lambda function. The input property captures the raw request from API Gateway. The response
contains httpMethod, path, headers, pathParameters, queryStringParameters,
requestContext, and stageVariables.
{
"message": "Hello me!",
"input": {
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/
xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36
OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net
(CloudFront)",
"X-Amz-Cf-Id":
"nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {"proxy": "hello"},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82
Safari/537.36 OPR/39.0.2256.48",
"user": ""
63
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {"name": "me"},
"stageVariables": {"stageVarName": "stageVarValue"}
}
}
You can use a different proxy resource path of /hello/world?name=me to call the Lambda
function. The input.path property value of the JSON payload of the successful response will
become test/hello/world.
If you use POST for the ANY method instead, the input property of the response payload
contains a body JSON property. To test a POST request, you can use the API Gateway console
TestInvoke feature, a Curl command, the Postman extension, or an AWS SDK.
2.
To use the API Gateway console to test invoking the API, do the following.
a.
b.
c.
From the Method drop-down list, choose an HTTP verb supported by the back end.
d.
Under Path, type a specific path for the proxy resource supporting the chosen operation.
e.
If required, type a supported query expression for the chosen operation under the Query
Strings heading.
f.
If required, type one or more supported header expressions for the chosen operation under
the Headers heading.
g.
If configured, set the required stage variable values for the chosen operation under the Stage
Variables heading.
h.
If prompted and required, choose an API Gateway-generated client certificate under the
Client Certificate heading to the operation to be authenticated by the back end.
i.
If prompted, type an appropriate request body in the text editor under the Request Body
heading.
j.
For this tutorial, use GET as the HTTP method, hello as the proxy resource path of {proxy}, and
name=me as the query expression.
The successful response will return a JSON payload that is similar to the payload shown in the
previous step.
set of AWS Lambda functions, and then call the Lambda functions from your API. If you have not yet
completed that walkthrough, we suggest that you do it first.
Topics
Prerequisites (p. 65)
Step 1: Create the Resource (p. 65)
Step 2: Create the GET Method (p. 65)
Step 3: Create the AWS Service Proxy Execution Role (p. 66)
Step 4: Specify Method Settings and Test the Method (p. 67)
Step 5: Deploy the API (p. 68)
Step 6: Test the API (p. 68)
Step 7: Clean Up (p. 69)
Prerequisites
Before you begin this walkthrough, you should have already done the following:
1.
Complete the steps in Get Ready to Use API Gateway (p. 4).
2.
Make sure the IAM user has access to create policies and roles in IAM. You will need to create an
IAM policy and role in this walkthrough.
3.
At a minimum, open the API Gateway console and create a new API named MyDemoAPI. For
more information, see Build an API Gateway API as an HTTP Proxy (p. 6).
4.
Deploy the API at least once to a stage named test. For more information, see Deploy the
API (p. 49) in the Build an API as a Lambda Proxy (p. 43).
5.
Complete the rest of the steps in the Build an API as a Lambda Proxy (p. 43).
6.
Create at least one topic in Amazon Simple Notification Service (Amazon SNS). You will use the
deployed API to get a list of topics in Amazon SNS that are associated with your AWS account.
To learn how to create a topic in Amazon SNS, see Create a Topic. (You do not need to copy the
topic ARN mentioned in step 5.)
2.
3.
In the Resources pane, choose the resource root, represented by a single forward slash (/), and
then choose Create Resource.
4.
For Resource Name, type MyDemoAWSProxy, and then choose Create Resource.
65
In the Resources pane, choose /mydemoawsproxy, and then choose Create Method.
2.
For the HTTP method, choose GET, and then save your choice.
To create the AWS service proxy execution role and its policy
1.
2.
Choose Policies.
3.
4.
5.
For Policy Name, type a name for the policy (for example, APIGatewayAWSProxyExecPolicy).
6.
7.
For Policy Document, type the following, and then choose Create Policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": [
"*"
],
"Action": [
"sns:ListTopics"
]
}
]
}
Note
This policy document allows the caller to get a list of the Amazon SNS topics for the AWS
account.
8.
Choose Roles.
9.
10. For Role Name, type a name for the execution role (for example,
APIGatewayAWSProxyExecRole), and then choose Next Step.
11. Next to Amazon EC2, choose Select.
66
Note
You choose Select here because you need to choose a standard AWS service role
statement before you can continue. There is currently no option to choose a standard API
Gateway service role statement. Later in this step, you will modify the standard Amazon
EC2 service role statement for use with API Gateway.
12. In the list of policies, select APIGatewayAWSProxyExecPolicy, and then choose Next Step.
13. For Role ARN, make a note of the Amazon Resource Name (ARN) for the execution role. You
will need it later. The ARN should look similar to: arn:aws:iam::123456789012:role/
APIGatewayAWSProxyExecRole, where 123456789012 is your AWS account ID.
14. Choose Create Role.
The invocation role IAM just created enables Amazon EC2 to get a list of the Amazon SNS topics
for the AWS account. You will change this role to enable API Gateway to get a list of the Amazon
SNS topics for the AWS account instead.
15. In the list of roles, select APIGatewayAWSProxyExecRole.
16. In the Trust Relationships area, choose Edit Trust Relationship.
17. For Policy Document, replace ec2.amazonaws.com with apigateway.amazonaws.com so
that the access control policy document now looks as follows:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
This policy document enables API Gateway to take actions on behalf of your AWS account.
18. Choose Update Trust Policy.
In the API Gateway console, in the Resources pane for the API named MyDemoAPI, in /
mydemoawsproxy, choose GET.
2.
In the Setup pane, for Integration type, choose Show advanced, and then choose AWS Service
Proxy.
3.
For AWS Region, choose the name of the AWS region where you want to get the Amazon SNS
topics.
4.
5.
67
6.
7.
For Execution Role, type the ARN for the execution role.
3.
4.
In the Stage Editor pane, next to Invoke URL, copy the URL to the clipboard. It should look like
this:
https://my-api-id.execute-api.region-id.amazonaws.com/test
2.
Paste the URL into the address box of a new browser tab.
68
3.
Step 7: Clean Up
You can delete the IAM resources the AWS service proxy needs to work.
Caution
If you delete an IAM resource an AWS service proxy relies on, that AWS service proxy and
any APIs that rely on it will no longer work. Deleting an IAM resource cannot be undone. If you
want to use the IAM resource again, you must re-create it.
You have reached the end of this walkthrough. For more detailed discussions about creating API as an
AWS service proxy, see Create an API as an Amazon S3 Proxy (p. 245), Create an API as a Lambda
Proxy (p. 229) or Create an API as an Amazon Kinesis Proxy (p. 263).
69
70
to Swagger (p. 130). The example provided in Create an API Gateway API from an Example (p. 7)
uses the Import API feature.
71
response specify the contract with the calling app, stipulating which parameters the API can receive
and what the response looks like. The integration request and response specifies how API Gateway
interacts with their back end: enforcing secure communications over HTTPS with the back end and
translating data formats between the client and back end. The following topics describe how to use the
API Gateway console to specify a method settings.
1.
2.
In the Method Execution pane, choose Integration Request. For Integration type, choose one
of the following:
Choose Lambda Function if your API will be communicating with a Lambda function.
Choose HTTP Proxy if your API will be communicating with an HTTP endpoint.
Choose Show Advanced, AWS Service Proxy if your API will be communicating directly with
an AWS service.
Choose Mock Integration if your API is not yet final, but you want to generate API responses
from API Gateway anyway to unblock dependent teams for testing. If you choose this
option, skip the rest of the instructions in this topic and see Configure Mock Integration for a
Method (p. 78).
3.
4.
5.
For Lambda Region, choose the region identifier that corresponds to the region where you
created the Lambda function. For example, if you created the Lambda function in the US East
(N. Virginia) region, you would choose us-east-1. For a list of region names and identifiers,
see AWS Lambda in the Amazon Web Services General Reference.
2.
For Lambda Function, type the name of the Lambda function, and then choose the function's
corresponding ARN.
3.
Choose Save.
For HTTP method, choose the HTTP method type that most closely matches the method in
the HTTP proxy.
2.
For Endpoint URL, type the URL of the HTTP proxy you want this method to use.
3.
Choose Save.
6.
Choose Save.
For AWS Region, choose the AWS region you want this method to use to call the action.
2.
For AWS Service, choose the AWS service you want this method to call.
3.
For HTTP method, choose the HTTP method type that corresponds to the action. For HTTP
method type, see the API reference documentation for the AWS service you chose for AWS
Service.
4.
For Action, type the action you want to use. For a list of available actions, see the API
reference documentation for the AWS service you chose for AWS Service.
5.
For Execution Role, type the ARN of the IAM role the method will use to call the action.
To create the IAM role, you can adapt the instructions in "To create the Lambda invocation
role and its policies" and "To create the Lambda execution role and its policy" in the Create
Lambda Functions (p. 44) section of the Build an API as a Lambda Proxy (p. 43); and specify
an access policy of the following format, with the desired number of action and resource
statements:
{
72
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"action-statement"
],
"Resource": [
"resource-statement"
]
},
...
]
}
For the action and resource statement syntax, see the documentation for the AWS service
you chose for AWS Service.
For the IAM role's trust relationship, specify the following, which enables API Gateway to take
actions on behalf of your AWS account:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
7.
6.
If the action you typed for Action provides a custom resource path you want this method to
use, for Path Override, type this custom resource path. For the custom resource path, see
the API reference documentation for the AWS service you chose for AWS Service.
7.
Choose Save.
73
Note
These instructions assume you have already completed the steps in Configure How a Method
Is Integrated with a Back End (p. 71).
1.
With the method selected in the Resources pane, in the Method Execution pane, choose
Method Request.
2.
To assign custom access permissions to the method, in the Authorization Settings area, for
Authorization Type, choose Edit, and then choose AWS_IAM. Only IAM roles with the correct
IAM policy attached will be allowed to call this method. If you do not want to assign custom access
permissions to the method, choose NONE.
To create the IAM role, specify an access policy with a format like the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"resource-statement"
]
}
]
}
In this access policy, resource-statement is the value of the ARN field in the Authorization
Settings section.
To create the IAM role, you can adapt the instructions in "To create the Lambda invocation role
and its policy" and "To create the Lambda execution role and its policy" in the Create Lambda
Functions (p. 44) section of the Build an API as a Lambda Proxy (p. 43).
To save your choice, choose Update. Otherwise, choose Cancel.
Note
You can also enable an API key. For instructions, see Use an API Key with the API
Gateway Console (p. 155).
3.
Choose the arrow next to URL Query String Parameters, and then choose Add query
string.
b.
c.
Note
To remove the query string parameter, choose Cancel or Remove.
To change the name of the query string parameter, you must remove it and create a new
one.
4.
Choose the arrow next to HTTP Request Headers, and then choose Add header.
b.
74
c.
d.
Optionally, check the Caching option to make this method as an API cache key. For more
information, see Use Method/Integration Parameters as Cache Keys (p. 182).
Choose Create
Tip
5.
6.
In the Method Execution pane, choose Method Response. By default, 200 response is
included in the method responses. You can modify it, e.g., to have the method return 201
instead. In addition, you can add other responses, e.g., 409 for access denial and 500 for
uninitialized stage variables used. Either choose the arrow icon next to 200 to specify settings
for the 200 response, or choose Add Response to specify settings for any other HTTP
response status code. If you choose Add Response, for HTTP Status, choose the response,
choose Create, and choose the arrow next to the response.
Tip
b.
You will use Method Response to specify all possible response codes for your API
and use Integration Response to indicate to API Gateway how back-end errors are
mapped to an HTTP status code.
For each custom header you want to include in the response, in the Response Headers area,
choose Add Header, type the name of the header, and then choose Save. (Choose Remove
to remove a header from this list.)
To specify a response model to transform the output's data from one format to another, in
the Response Models area, choose Add Response Model. Type the content type (for
Content type), choose the model's name (for Models), and then choose Save. Choose Add
Response Model to specify an additional model, or choose Create a model to define a new
model. (Choose Remove to remove a response model selection from this list.)
Note
These instructions assume you have already completed the steps in Configure How a Method
Is Integrated with a Back End (p. 71).
1.
2.
With the method selected in the Resources pane, in the Method Execution pane, choose
Integration Request.
For an HTTP proxy or an AWS service proxy, to associate a path parameter, a query string
parameter, or a header parameter defined in the integration request with a corresponding path
75
parameter, query string parameter, or header parameter in the method request of the HTTP proxy
or AWS service proxy, do the following:
a.
Choose the arrow next to URL Path Parameters, URL Query String Parameters, or HTTP
Headers respectively, and then choose Add path, Add query string, or Add header,
respectively.
b.
For Name, type the name of the path parameter, query string parameter, or header parameter
in the HTTP proxy or AWS service proxy.
c.
For Mapped from, type the mapping value for the path parameter, query string parameter, or
header parameter. Use one of the following formats:
method.request.path.parameter-name for a path parameter named parametername as defined in the Method Request page.
method.request.querystring.parameter-name for a query string parameter named
parameter-name as defined in the Method Request page.
method.request.header.parameter-name for a header parameter named
parameter-name as defined in the Method Request page.
Alternatively, you can set a literal string value (enclosed by a pair of single quotes) to an
integration header.
d.
3.
Choose Create. (To delete a path parameter, query string parameter, or header parameter,
choose Cancel or Remove next to the parameter you want to delete.)
In the Body Mapping Templates area, choose an option for Request body passthrough to
configure how the method request body of an unmapped content type will be passed through the
integration request without transformation to the Lambda function, HTTP proxy, or AWS service
proxy. There are three options:
Choose When no template matches the request Content-Type header if you want
the method request body to pass through the integration request to the back end without
transformation when the method request content type does not match any content types
associated with the mapping templates, as defined in the next step.
Note
When calling the API Gateway API, you choose this option by setting WHEN_NO_MATCH
as the passthroughBehavior property value on the Integration resource.
Choose When there are no templates defined (recommended) if you want the method
request body to pass through the integration request to the back end without transformation
when no mapping template is defined in the integration request. If a template is defined when
this option is selected, the method request of an unmapped content type will be rejected with an
HTTP 415 Unsupported Media Type response.
Note
When calling the API Gateway API, you choose this option by setting
WHEN_NO_TEMPLATE as the passthroughBehavior property value on the Integration
resource.
Choose Never if you do not want the method request to pass through when either the
method request content type does not match any content type associated with the mapping
templates defined in the integration request or no mapping template is defined in the integration
request. The method request of an unmapped content type will be rejected with an HTTP 415
Unsupported Media Type response.
Note
When calling the API Gateway API, you choose this option by setting NEVER as the
passthroughBehavior property value on the Integration resource.
For more information about the integration passthrough behaviors, see Integration Passthrough
Behaviors (p. 123).
76
4.
To define a mapping template for an incoming request, choose Add mapping template under
Content-Type. Type a content type (e.g., application/json) in the input text box and then
choose the check mark icon to save the input. Then, type the mapping template manually or
choose Generate template to create one from a model template. For more information, see Set
Up Payload Mappings (p. 88).
5.
You can map an integration response from the back-end to a method response of the API returned
to the calling app. This includes returning to the client selected response headers from the
available ones from the back end, transforming the data format of the back-end response payload
to an API-specified format. You can specify such mapping by configuring Method Response and
Integration Response from the Method Execution page.
a.
In the Method Execution pane, choose Integration Response. Choose either the arrow next
to 200 to specify settings for a 200 HTTP response code from the method, or choose Add
integration response to specify settings for any other HTTP response status code from the
method.
b.
For Lambda error regex (for a Lambda function) or HTTP status regex (for an HTTP
proxy or AWS service proxy), type a regular expression to specify which Lambda function
error strings (for a Lambda function) or HTTP response status codes (for an HTTP proxy
or AWS service proxy) map to this output mapping. For example, to map all 2xx HTTP
response status codes from an HTTP proxy to this output mapping, type "2\\d{2}" for
HTTP status regex. To return an error message containing "Invalid Request" from a Lambda
function to a 400 Bad Request response, type ".*Invalid request.*" as the Lambda
error regex expression. On the other hand, to return 400 Bad Request for all unmapped
error messages from Lambda, type "(\n|.)+" in Lambda error regex. This last regular
expression can be used for the default error response of an API.
Note
The error patterns are matched against the entire string of the
errorMessage property in the Lambda response, which is populated
by context.fail(errorMessage) in Node.js or by throw new
MyException(errorMessage) in Java. Also, escaped characters are unescaped
before the regular expression is applied.
If you use '.+' as the selection pattern to filter responses, be aware that it may not
match a response containing a newline ('\n') character.
c.
If enabled, for Method response status, choose the HTTP response status code you defined
in the Method Response page.
d.
For Header Mappings, for each header you defined for the HTTP response status code in the
Method Response page, specify a mapping value by choosing Edit. For Mapping value, use
the format integration.response.header.header-name where header-name is the
name of a response header from the backend. For example, to return the backend response's
Date header as an API method's response's Timestamp header, the Response header
column will contain an Timestamp entry and the associated Mapping value should be set to
integration.response.header.Date.
e.
In the Template Mappings area, next to Content type, choose Add. In the Content type
box, type the content type of the data that will be passed from the Lambda function, HTTP
proxy, or AWS service proxy to the method. Choose Update.
f.
Select Output passthrough if you want the method to receive, but not modify, the data from
the Lambda function, HTTP proxy, or AWS service proxy.
g.
If Output passthrough is cleared, for Output mapping, specify the output mapping template
you want the Lambda function, HTTP proxy, or AWS service proxy to use to send data to
the method. You can either type the mapping template manually or choose a model from
Generate template from model.
h.
Choose Save.
77
Prerequisites
You must have the method available in API Gateway. Follow the instructions in Build an API
Gateway API as an HTTP Proxy (p. 6).
Choose an API resource and create a method. In the Setup pane, choose Mock Integration , and
then choose Save.
In the Method Execution pane, choose Integration Request.
By default, mock integrations return a 200 HTTP status code. To customize this default behavior,
do the following:
1.
2.
3.
In the Template editor, type the content of the template you want API Gateway to use to
determine which HTTP status code to use in the integration response. The template must
78
output a JSON payload containing the statusCode property. For more information, see
Example Request Templates (p. 80).
4.
4.
For each query string parameter or header parameter you want to add to the method, do the
following:
1.
2.
Choose the arrow next to URL Query String Parameters or HTTP Request Headers, and
then choose Add query string or Add header, respectively.
3.
For Name, type the name of the query string parameter or header parameter, and then
choose Create a new query string or Create, respectively.
Note
To remove a query string parameter or header parameter, choose Cancel or
Remove. To change the name of a query string parameter or header parameter, you
must remove it and create a new one in its place.
5.
6.
7.
8.
9.
For each Method response status entry you want to use, do the following:
1.
Expand the row that corresponds to the Method response status entry you want to use.
2.
For HTTP status regex, type the matching HTTP Status entry (for example, type 400 for a
400 HTTP Status entry or 500 for a 500 HTTP Status entry). Or specify a range of matching
HTTP status codes (for example, 5/d{2} matches all 5XX HTTP status codes).
3.
4.
5.
In the Template editor, type the contents of the template that you want API Gateway to use to
respond to the caller. For more information, see Example Response Templates (p. 80).
6.
The following example shows a request template that uses the 200 HTTP status code if the request
specifies the petType parameter of cat; 400 if the request specifies dog; and uses 500 otherwise.
This example is based on the one in the Map Request Parameters (p. 22).
{
#if( $input.params('petType') == "cat" )
"statusCode": 200
#elseif( $input.params('petType') == "dog" )
"statusCode": 400
#else
"statusCode": 500
#end
}
The following example shows a response template that responds with the same information every time,
but includes the value the caller specified for the petType parameter. This example is based on the
one in the Map Request Parameters (p. 22).
## Example 200 response for ?petType=cat (response will contain "type":
"cat").
{
"id": 1,
"name": "Kitty",
"type": "$input.params('petType')"
}
80
Note
Greedy path variables, ANY methods, and proxy integration types are independent features,
although they are commonly used together. You can configure a specific HTTP method on a
greedy resource or apply non-proxy integration types to a proxy resource.
Topics
API Gateway Proxy Resource (p. 81)
API Gateway Proxy Integration Types (p. 81)
Set Up a Proxy Resource with the HTTP Proxy Integration (p. 82)
Set Up a Proxy Resource with the Lambda Proxy Integration (p. 85)
Input Format of a Lambda Function for Proxy Integration (p. 86)
Output Format of a Lambda Function for Proxy Integration (p. 88)
81
Similarly, you can apply the Lambda proxy integration to a proxy resource of /api/{proxy+} to set
up a single integration to have a back-end Lambda function react individually to changes in any of the
API resources under /api.
82
"cacheNamespace": "rbftud",
"cacheKeyParameters": [
"method.request.path.proxy"
],
"type": "http_proxy"
}
}
}
}
}
The run-time instances of the ANY method and proxy resource are both valid. The call will return a
200 OK response with the payload containing the first batch of pets, as returned from the back end.
Set ANY as GET and {proxy+} as pets?type=dog
GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets?
type=dog HTTP/1.1
The run-time instances of the ANY method and proxy resource are both valid. The call will return a
200 OK response with the payload containing the first batch of specified dogs, as returned from the
back end.
Set ANY as GET and {proxy+} as pets/{petId}
Method request initiated from the front end:
GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/1
HTTP/1.1
83
The run-time instances of the ANY method and proxy resource are both valid. The call will return a
200 OK response with the payload containing the specified pet, as returned from the back end.
Set ANY as POST and {proxy+} as pets
Method request initiated from the front end:
POST https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets
HTTP/1.1
Content-Type: application/json
Content-Length: ...
{
"type" : "dog",
"price" : 1001.00
}
The run-time instances of the ANY method and proxy resource are both valid. The call will return a
200 OK response with the payload containing the newly created pet, as returned from the back end.
Set ANY as GET and {proxy+} as pets/cat
Method request initiated from the front end:
GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/cat
The run-time instance of the proxy resource path does not correspond to a back-end endpoint and
the resulting request is invalid. As a result, a 400 Bad Request response is returned with the
following error message.
{
"errors": [
{
"key": "Pet2.type",
"message": "Missing required field"
},
{
"key": "Pet2.price",
"message": "Missing required field"
}
84
]
}
The targeted resource is the parent of the proxy resource, but the run-time instance of the ANY
method is not defined in the API on that resource. As a result, this GET request returns a 403
Forbidden response with the "Missing Authentication Token" error message as returned by API
Gateway. If the API exposes the ANY or GET method on the parent resource, (/), the call will return a
404 Not Found response with the Cannot GET /petstore message as returned from the back
end.
For any client request, if the targeted endpoint URL is invalid or the HTTP verb is valid but not
supported, the back end returns a 404 Not Found response. For an unsupported HTTP method, a
403 Forbidden response is returned.
85
"application/json"
],
"parameters": [
{
"name": "proxy",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/
functions/arn:aws:lambda:useast-1:123456789012:function:SimpleLambda4ProxyResource/invocations",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"cacheNamespace": "roq9wj",
"cacheKeyParameters": [
"method.request.path.proxy"
],
"type": "aws_proxy"
}
}
}
}
}
With the Lambda proxy integration, at run time, API Gateway maps an incoming request into the input
event parameter of the Lambda function. The input includes the request method, path, headers, any
query parameters, any payload, associated context, and any defined stage variables. The input format
is explained in Input Format of a Lambda Function for Proxy Integration (p. 86). For API Gateway to
map the Lambda output to HTTP responses successfully, the Lambda function must output the result
in the format explained in Output Format of a Lambda Function for Proxy Integration (p. 88).
With the Lambda proxy integration of a proxy resource through the ANY method, the single back-end
Lambda function serves as the event handler for all requests through the proxy resource. For example,
to log traffic patterns, you can have a mobile device send its location in terms of state, city, street, and
building by submitting a request with /state/city/street/house in the URL path for the proxy
resource. The back-end Lambda function can then parse the URL path and insert the location tuples
into a DynamoDB table.
86
{
"a": 1
}
API Gateway maps the entire client request to the input event parameter of the back-end Lambda
function as follows:
{
"message": "Hello me!",
"input": {
"resource": "/{proxy+}",
"path": "/hello/world",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"cache-control": "no-cache",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"headerName": "headerValue",
"Host": "gy415nuibc.execute-api.us-east-1.amazonaws.com",
"Postman-Token": "9f583ef0-ed83-4a38-aef3-eb9ce3f7a57f",
"User-Agent": "PostmanRuntime/2.4.5",
"Via": "1.1 d98420743a69852491bbdea73f7680bd.cloudfront.net
(CloudFront)",
"X-Amz-Cf-Id": "pnPWIJc6thYnZm5P0NMgOUglL1DYtl0gdeJky8tqsg8iS_sgsKD1A==",
"X-Forwarded-For": "54.240.196.186, 54.182.214.83",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"queryStringParameters": {
"name": "me"
},
"pathParameters": {
"proxy": "hello/world"
},
"stageVariables": {
"stageVariableName": "stageVariableValue"
},
"requestContext": {
"accountId": "12345678912",
"resourceId": "roq9wj",
"stage": "testStage",
"requestId": "deef4878-7910-11e6-8f14-25afc3e9ae33",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": null,
"sourceIp": "192.168.196.186",
"cognitoAuthenticationType": null,
87
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": "PostmanRuntime/2.4.5",
"user": null
},
"resourcePath": "/{proxy+}",
"httpMethod": "POST",
"apiId": "gy415nuibc"
},
"body": "{\r\n\t\"a\": 1\r\n}"
}
}
A Lambda function in Node.js can supply a JSON object of this format as the input to the
context.succeed( {...} ); function call. If the function output is of a different format, API
Gateway will return a 502 Bad Gateway error response.
88
Models
In API Gateway, a model defines the structure or shape of a payload and is also known as the schema
of the payload. API Gateway requires that the JSON Schema be used to describe the model of a JSON
payload.
API Gateway maps a payload according to a mapping template. A model is useful, but not required, to
generate a template. However, models are necessary for generating strongly typed SDK of your API.
They can also be useful to validate a payload.
The following JSON object describes a sample data describing the fruit or vegetable inventory in the
produce department of a likely supermarket:
{
"department": "produce",
"categories": [
"fruit",
"vegetables"
],
"bins": [
{
"category": "fruit",
"type": "apples",
"price": 1.99,
"unit": "pound",
"quantity": 232
},
{
"category": "fruit",
"type": "bananas",
"price": 0.19,
"unit": "each",
"quantity": 112
},
{
"category": "vegetables",
"type": "carrots",
"price": 1.29,
"unit": "bag",
"quantity": 57
}
]
}
89
90
"type": "object",
"properties": {
"department": { "type": "string" },
"categories": {
"type": "array",
"items": { "type": "string" }
},
"bins": {
"type": "array",
"items": {
"$ref": "#/definitions/Bin"
}
}
},
"definitions": {
"Bin" : {
"type": "object",
"properties": {
"category": { "type": "string" },
"type": { "type": "string" },
"price": { "type": "number" },
"unit": { "type": "string" },
"quantity": { "type": "integer" }
}
}
}
}
The definitions section contains the schema definition of the Bin item that is referenced in the
bins array with "ref": "#/definitions/Bin". Using reusable definitions this way makes your
model definition easier to read.
In addition, you can also reference another model schema defined in an external model
file by setting that model's URL as the value of the $ref property: "$ref": "https://
apigateway.amazonaws.com/restapis/{restapi_id}/models/{model_name}". For
example, supposed you have the following full-fledged model named Bin2 created under an API with
an identifier of fugvjdxtri:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "GroceryStoreInputModel",
"type": "object",
"properties": {
"Bin" : {
"type": "object",
"properties": {
"category": { "type": "string" },
"type": { "type": "string" },
"price": { "type": "number" },
"unit": { "type": "string" },
"quantity": { "type": "integer" }
}
}
}
}
You can then reference it from the GroceryStoreInputModel from the same API, as shown as
follows:
91
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "GroceryStoreInputModel",
"type": "object",
"properties": {
"department": { "type": "string" },
"categories": {
"type": "array",
"items": { "type": "string" }
},
"bins": {
"type": "array",
"items": {
"$ref": "https://apigateway.amazonaws.com/restapis/fugvjdxtri/models/
Bin2"
}
}
}
}
The referencing and referenced models must be from the same API.
The examples do not use advanced JSON Schema features, such as specifying required items;
minimum and maximum allowed string lengths, numeric values, and array item lengths; regular
expressions; and more. For more information, see Introducing JSON and JSON Schema.
For more complex JSON data formats and their models, see the following examples:
Input Model (Photos Example) (p. 98) and Output Model (Photos Example) (p. 99) in the
Photos Example (p. 97)
Input Model (News Article Example) (p. 101) and Output Model (News Article Example) (p. 103)
in the News Article Example (p. 100)
Input Model (Sales Invoice Example) (p. 105) and Output Model (Sales Invoice
Example) (p. 107) in the Sales Invoice Example (p. 104)
Input Model (Employee Record Example) (p. 109) and Output Model (Employee Record
Example) (p. 112) in the Employee Record Example (p. 108)
To experiment with models in API Gateway, follow the instructions in Map Response Payload (p. 30),
specifically Step 1: Create Models (p. 33).
Mapping Templates
In API Gateway, a mapping template is used to transform some data from one format to another. You
create and use input mapping templates and output mapping templates when you need to inform API
Gateway about the schema of the data being sent from or returned to the caller, respectively. API
Gateway uses the Velocity Template Language (VTL) and JSONPath expressions to define mapping
templates.
For an example of an input mapping template, consider the example JSON data from the previous
section. The following input mapping template makes no transform to the JSON data as API Gateway
receives the JSON data from the caller:
#set($inputRoot = $input.path('$'))
{
"department": "$inputRoot.department",
92
"categories": [
#foreach($elem in $inputRoot.categories)
"$elem"#if($foreach.hasNext),#end
#end
],
"bins" : [
#foreach($elem in $inputRoot.bins)
{
"category" : "$elem.category",
"type" : "$elem.type",
"price" : $elem.price,
"unit" : "$elem.unit",
"quantity" : $elem.quantity
}#if($foreach.hasNext),#end
#end
]
}
Note
None of the array and object names in this JSON data schema match the JSON data from the
previous section:
{
"choices": [
{
"kind": "apples",
"suggestedPrice": "1.99 per pound",
"available": 232
},
{
"kind": "bananas",
"suggestedPrice": "0.19 per each",
"available": 112
},
93
{
"kind": "carrots",
"suggestedPrice": "1.29 per bag",
"available": 57
}
]
}
To transform the example JSON data from the previous section into this JSON data schema, you
would use the following model:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "GroceryStoreOutputModel",
"type": "object",
"properties": {
"choices": {
"type": "array",
"items": {
"type": "object",
"properties": {
"kind": { "type": "string" },
"suggestedPrice": { "type": "string" },
"available": { "type": "integer" }
}
}
}
}
}
94
95
Prerequisites
You must have an API available in API Gateway. Follow the instructions in Creating an
API (p. 70).
2.
In the box that contains the name of the API where you want to create the model, choose Models.
3.
Choose Create.
4.
5.
For Content Type, type the model's content type (for example, application/json for JSON).
6.
7.
For Model schema, type the model's schema. For more information about model schemas, see
Set Up Payload Mappings (p. 88).
8.
Prerequisites
You must have at least one model in API Gateway. Follow the instructions in Create a
Model (p. 95).
2.
In the box that contains the name of the API, choose Models.
Warning
Deleting a model may cause part or all of the corresponding API to become unusable by API
callers. Deleting a model cannot be undone.
96
2.
In the box that contains the name of the API for the model, choose Models.
3.
In the Models pane, choose the model you want to delete, and then choose Delete Model.
4.
97
}
}
98
"id": "$elem.id",
"owner": "$elem.owner",
"secret": "$elem.secret",
"server": "$elem.server",
"farm": $elem.farm,
"title": "$elem.title",
"ispublic": $elem.ispublic,
"isfriend": $elem.isfriend,
"isfamily": $elem.isfamily
}#if($foreach.hasNext),#end
#end
]
}
}
99
100
{
"count": 1,
"items": [
{
"last_updated_date": "2015-04-24",
"expire_date": "2016-04-25",
"author_first_name": "John",
"description": "Sample Description",
"creation_date": "2015-04-20",
"title": "Sample Title",
"allow_comment": "1",
"author": {
"last_name": "Doe",
"email": "[email protected]",
"first_name": "John"
},
"body": "Sample Body",
"publish_date": "2015-04-25",
"version": "1",
"author_last_name": "Doe",
"parent_id": 2345678901,
"article_url": "http://www.example.com/articles/3456789012"
}
],
"version": 1
}
101
},
"body": { "type": "string" },
"publish_date": { "type": "string" },
"version": { "type": "string" },
"author_last_name": { "type": "string" },
"parent_id": { "type": "integer" },
"article_url": { "type": "string" }
}
}
},
"version": { "type": "integer" }
}
}
102
"count": 1,
"items": [
{
"creation_date": "2015-04-20",
"title": "Sample Title",
"author": "John Doe",
"body": "Sample Body",
"publish_date": "2015-04-25",
"article_url": "http://www.example.com/articles/3456789012"
}
],
"version": 1
}
103
"body": "$elem.body",
"publish_date": "$elem.publish_date",
"article_url": "$elem.article_url"
}#if($foreach.hasNext),#end
#end
],
"version": $inputRoot.version
}
104
}
],
"Vendor": {
"value": "GHI456",
"name": "Sample Bank"
},
"APRef": {
"value": "HIJ567",
"name": "Accounts Payable"
},
"TotalAmt": 1990.19
}
105
},
"LineStatus": { "type": "string" }
}
}
}
}
},
"Vendor": {
"type": "object",
"properties": {
"value": { "type": "string" },
"name": { "type": "string" }
}
},
"APRef": {
"type": "object",
"properties": {
"value": { "type": "string" },
"name": { "type": "string" }
}
},
"TotalAmt": { "type": "number" }
}
}
106
#end
],
"Vendor": {
"value": "$inputRoot.Vendor.value",
"name": "$inputRoot.Vendor.name"
},
"APRef": {
"value": "$inputRoot.APRef.value",
"name": "$inputRoot.APRef.name"
},
"TotalAmt": $inputRoot.TotalAmt
}
107
108
109
110
{
"QueryResponse": {
"maxResults": "$inputRoot.QueryResponse.maxResults",
"startPosition": "$inputRoot.QueryResponse.startPosition",
"Employee": {
"Organization": "$inputRoot.QueryResponse.Employee.Organization",
"Title": "$inputRoot.QueryResponse.Employee.Title",
"GivenName": "$inputRoot.QueryResponse.Employee.GivenName",
"MiddleName": "$inputRoot.QueryResponse.Employee.MiddleName",
"FamilyName": "$inputRoot.QueryResponse.Employee.FamilyName",
"DisplayName": "$inputRoot.QueryResponse.Employee.DisplayName",
"PrintOnCheckName":
"$inputRoot.QueryResponse.Employee.PrintOnCheckName",
"Active": "$inputRoot.QueryResponse.Employee.Active",
"PrimaryPhone": { "FreeFormNumber":
"$inputRoot.QueryResponse.Employee.PrimaryPhone.FreeFormNumber" },
"PrimaryEmailAddr": { "Address":
"$inputRoot.QueryResponse.Employee.PrimaryEmailAddr.Address" },
"EmployeeType": "$inputRoot.QueryResponse.Employee.EmployeeType",
"status": "$inputRoot.QueryResponse.Employee.status",
"Id": "$inputRoot.QueryResponse.Employee.Id",
"SyncToken": "$inputRoot.QueryResponse.Employee.SyncToken",
"MetaData": {
"CreateTime":
"$inputRoot.QueryResponse.Employee.MetaData.CreateTime",
"LastUpdatedTime":
"$inputRoot.QueryResponse.Employee.MetaData.LastUpdatedTime"
},
"PrimaryAddr" : {
"Line1": "$inputRoot.QueryResponse.Employee.PrimaryAddr.Line1",
"City": "$inputRoot.QueryResponse.Employee.PrimaryAddr.City",
"CountrySubDivisionCode":
"$inputRoot.QueryResponse.Employee.PrimaryAddr.CountrySubDivisionCode",
"PostalCode":
"$inputRoot.QueryResponse.Employee.PrimaryAddr.PostalCode"
}
}
},
"time": "$inputRoot.time"
}
111
"Active": "true",
"PrimaryPhone": "505.555.9999",
"Email": [
{
"type": "primary",
"Address": "[email protected]"
}
],
"EmployeeType": "Regular",
"PrimaryAddr": {
"Line1": "123 Any Street",
"City": "Any City",
"CountrySubDivisionCode": "WA",
"PostalCode": "01234"
}
}
]
},
"time": "2015-04-27T22:12:32.012Z"
}
112
113
]
},
"time": "$inputRoot.time"
}
Mapping expression
method.request.path.PARAM_NAME
method.request.querystring.PARAM_NAME
method.request.header.PARAM_NAME
method.request.body
method.request.body.JSONPath_EXPRESSION.
Stage variables
stageVariables.VARIABLE_NAME
Context variables
Static value
Here, PARAM_NAME is the name of a method request parameter of the given parameter type. It must
have been defined before it can be referenced. JSONPath_EXPRESSION is a JSONPath expression for
a JSON field of the body of a request or response. However, the "$." prefix is omitted in this syntax.
114
...
"requestParameters" : {
"integration.request.path.integrationPathParam" :
"method.request.header.methodRequestHeaderParam",
"integration.request.querystring.integrationQueryParam" :
"method.request.querystring.methodRequestQueryParam"
}
...
Integration request parameters can also be mapped from fields in the JSON request body using a
JSONPath expression. The following table shows the mapping expressions for a method request body
and its JSON fields.
...
"requestParameters" : {
"integration.request.header.body-header" : "method.request.body",
"integration.request.path.pet-name" :
"method.request.body.petstore.pets[0].name",
}
...
Mapping expression
integration.response.header.PARAM_NAME
integration.response.body
115
Mapping expression
integration.response.body.JSONPath_EXPRESSION
Stage variable
stageVariables.VARIABLE_NAME
Context variable
Static value
...
"responseParameters" : {
"method.response.header.location" :
"integration.response.body.redirect.url",
"method.response.header.id" : "integration.response.header.x-app-id",
}
...
116
Description
$context.apiId
$context.authorizer.principalId
$context.authorizer.claims.property
Note
Calling
$context.authorizer.claims
returns null.
$context.httpMethod
$context.identity.accountId
$context.identity.apiKey
$context.identity.caller
$context.identity.cognitoAuthenticationProvider
The Amazon Cognito authentication provider
used by the caller making the request. Available
only if the request was signed with Amazon
Cognito credentials.
117
Parameter
Description
$context.identity.cognitoAuthenticationType
The Amazon Cognito authentication type of
the caller making the request. Available only if
the request was signed with Amazon Cognito
credentials.
$context.identity.cognitoIdentityId
$context.identity.user
$context.identity.userAgent
$context.identity.userArn
$context.requestId
$context.resourceId
$context.resourcePath
$context.stage
Example
You may want to use the $context variable if you're using AWS Lambda as the target backend
that the API method calls. For example, you may want to perform two different actions depending on
whether the stage is in Beta or in Prod.
118
"caller" : "$context.identity.caller",
"user" : "$context.identity.user",
"user_arn" : "$context.identity.userArn"
}
Function Reference
Variable and Function
Description
$input.body
$input.json(x)
$input.params()
$input.params(x)
$input.path(x)
Examples
You may want to use the $input variable to get query strings and the request body with or without
using models. You may also want to get the parameter and the payload, or a subsection of the
payload, into your AWS Lambda function. The examples below show how to do this.
119
"name" : "$input.params('name')",
"body" : $input.json('$')
}
If the JSON input contains unescaped characters that cannot be parsed by JavaScript, a 400 response
may be returned. Applying $util.escapeJavaScript($input.json('$')) above will ensure that
the JSON input can be parsed properly.
If a method request payload contains unescaped characters that cannot be parsed by JavaScript, you
may get 400 response. In this case, you need to call $util.escapeJavaScript() function in the
mapping template, as shown as follows:
{
"name" : "$input.params('name')",
"body" : $util.escapeJavaScript($input.json('$.mykey'))
}
In effect, this mapping template outputs all the request parameters in the payload as outlined as
follows:
{
"parameters" : {
120
"path" : {
"path_name" : "path_value",
...
}
"header" : {
"header_name" : "header_value",
...
}
'querystring" : {
"querystring_name" : "querystring_value",
...
}
}
}
Response:
{
"id": "abc",
"count": "3",
"things": {
"1": {},
"2": {},
"3": {}
}
}
For more mapping examples, see Set Up Payload Mappings (p. 88)
121
$stageVariables Reference
Syntax
Description
$stageVariables.<variable_name>
$stageVariables['<variable_name>']
${stageVariables['<variable_name>']}
Note
Unless otherwise specified, the default character set is UTF-8.
Description
$util.escapeJavaScript()
Note
This function will turn any regular single
quotes (') into escaped ones (\').
However, the escaped single quotes
are not valid in JSON. Thus, when the
output from this function is used in
a JSON property, you must turn any
escaped single quotes (\') back to
regular single quotes ('). This is shown
in the following example:
$util.escapeJavaScript(data).replaceAll("\'","'"
$util.parseJson()
{"errorMessage":"{\"key1\":\"var1\",
\"key2\":{\"arr\":[1,2,3]}}"}
122
Function
Description
}
$util.urlDecode()
$util.base64Encode()
$util.base64Decode()
WHEN_NO_MATCH
WHEN_NO_TEMPLATE
NEVER
None (default to
application/json
application/json
application/xml
Example 2: One mapping template is defined in the integration request for the application/xml
content type.
123
Content-Type
header\Selected
passthrough option
WHEN_NO_MATCH
WHEN_NO_TEMPLATE
NEVER
None (default to
application/json
application/json
application/xml
Note
For RAML API definitions, you can continue to use API Gateway Importer.
Besides making explicit calls to the REST API, as described below, you can also use the Import API
feature in the API Gateway console. The option is available as an item in the Actions drop-down
menu. For an example of using the Import API feature from the API Gateway console, see Create an
API Gateway API from an Example (p. 7).
124
POST /restapis?mode=import
Host:apigateway.<region>.amazonaws.com
Content-Type: application/json
Content-Length: ...
Swagger API definition in JSON (p. 242)
PUT /restapis/<restapi_id>?mode=merge
Host:apigateway.<region>.amazonaws.com
Content-Type: application/json
Content-Length: ...
The merging update operation takes two complete API definitions and merges them together. For a
small and incremental change, you can use the resource update operation.
To overwrite an API, submit a PUT request to https://apigateway.<region>.amazonaws.com/
restapis/<restapi_id>?mode=overwrite. The restapi_id path parameter specifies the API
that will be overwritten with the supplied API definitions.
The following code snippet shows an example of an overwriting request with the payload of a JSONformatted Swagger definition:
125
PUT /restapis/<restapi_id>?mode=overwrite
Host:apigateway.<region>.amazonaws.com
Content-Type: application/json
Content-Length: ...
A Swagger API definition in JSON (p. 242)
Note
The PUT operations are idempotent, but not atomic. That means if a system error occurs part
way through processing, the API can end up in a bad state. However, repeating the operation
will put the API into the same final state as if the first operation had succeeded.
Swagger basePath
In Swagger, you can use the basePath property to provide one or more path parts that precede each
path defined in the paths property. Because API Gateway has several ways to express a resources
path, the Import API feature provides three options for interpreting the basePath property during an
import:
ignore
If the Swagger file has a basePath value of "/a/b/c" and the paths property contains "/e" and "/
f", the following POST or PUT request:
POST /restapis?mode=import&basepath=ignore
PUT /restapis/api_id?basepath=ignore
Note
API Gateway will automatically create a root resource for you, even if it is not explicitly
declared in your definition file.
prepend
If the Swagger file has a basePath value of "/a/b/c" and the paths property contains "/e" and "/
f", the following POST or PUT request:
POST /restapis?mode=import&basepath=prepend
126
PUT /restapis/api_id?basepath=prepend
Note
API Gateway will automatically create intermediate resources for you, even if they are not
explicitly declared in your definition.
split
If the Swagger file has a basePath value of "/a/b/c" and the paths property contains "/e" and "/
f", the following POST or PUT request:
POST /restapis?mode=import&basepath=split
PUT /restapis/api_id?basepath=split
127
failonwarnings is set to false. In such cases, warnings are returned as a field in the resulting
RestApi resource. Otherwise, warnings are returned as a message in the exception.
https://<host>/restapis/<restapi_id>/stages/<stage_name>/exports/swagger
You can append the extensions query string to specify whether to include API Gateway extensions
(with the integration value) or Postman extensions (with the postman value).
In addition, you can set the Accept header to application/json or application/yaml to receive
the API definition output in JSON or YAML format, respectively.
For more information about submitting GET requests using the API Gateway Export API, see Making
HTTP Requests.
Note
If you define models in your API, they must be for the content type of "application/json" for API
Gateway to export the model. Otherwise, API Gateway throws an exception with the "Only
found non-JSON body models for ..." error message.
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger
Host: apigateway.<region>.amazonaws.com
Accept: application/json
Here, <region> could be, for example, us-east-1. For all the regions where API Gateway is
available, see Regions and Endpoints
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger
Host: apigateway.<region>.amazonaws.com
128
Accept: application/yaml
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?
extensions=postman
Host: apigateway.<region>.amazonaws.com
Accept: application/json
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?
extensions=integration
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
129
Tip
To understand how the API Gateway extensions are used in an app, you can use the
API Gateway console to create an API and export it to a Swagger definition file. For more
information on how to export an API, see Export an API (p. 128).
Topics
x-amazon-apigateway-any-method Object (p. 130)
x-amazon-apigateway-authorizer Object (p. 131)
x-amazon-apigateway-authtype Property (p. 133)
x-amazon-apigateway-integration Object (p. 133)
x-amazon-apigateway-integration.requestTemplates Object (p. 135)
x-amazon-apigateway-integration.requestParameters Object (p. 136)
x-amazon-apigateway-integration.responses Object (p. 137)
x-amazon-apigateway-integration.response Object (p. 138)
x-amazon-apigateway-integration.responseTemplates Object (p. 139)
x-amazon-apigateway-integration.responseParameters Object (p. 139)
x-amazon-apigateway-any-method Object
Specifies the Swagger Operation Object for the API Gateway catch-all ANY method in a Swagger Path
Item Object. This object can exist alongside other Operation objects and will catch any HTTP method
that was not explicitly declared.
The following table lists the properties extended by API Gateway. For the other Swagger Operation
properties, see the Swagger specification.
Properties
Property Name
Type
Description
x-amazon-apigatewayintegration
x-amazon-apigateway-any-method Example
The following example integrates the ANY method on a proxy resource, {proxy+}, with a Lambda
function, TestSimpleProxy.
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"produces": [
"application/json"
],
130
"parameters": [
{
"name": "proxy",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {},
"x-amazon-apigateway-integration": {
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/
functions/arn:aws:lambda:us-east-1:123456789012:function:TestSimpleProxy/
invocations",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"type": "aws_proxy"
}
x-amazon-apigateway-authorizer Object
Defines a custom authorizer to be applied for authorization of method invocations in API Gateway. This
object is an extended property of the Swagger Security Definitions Operation object.
Properties
Property Name
Type
Description
type
string
authorizerUri
string
authorizerCredentials
string
identityValidationExpression
string
authorizerResultTtlInSeconds
string
131
x-amazon-apigateway-authorizer Example
The following Swagger security definitions example specifies a custom authorizer named testauthorizer.
"securityDefinitions" : {
"test-authorizer" : {
"type" : "apiKey",
// Required and the value
must be "apiKey" for an API Gateway API.
"name" : "Authorization",
// The source header name
identifying this authorizer.
"in" : "header",
// Required and the value
must be "header" for an AAPI Gateway API.
"x-amazon-apigateway-authtype" : "oauth2", // Specifies the
authorization mechanism for the client.
"x-amazon-apigateway-authorizer" : {
// An API Gateway custom
authorizer definition
"type" : "token",
// Required property and the
value must "token"
"authorizerUri" : "arn:aws:apigateway:useast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:accountid:function:function-name/invocations",
"authorizerCredentials" : "arn:aws:iam::account-id:role",
"identityValidationExpression" : "^x-[a-z]+",
"authorizerResultTtlInSeconds" : 60
}
}
}
The following Swagger operation object snippet sets the GET /http to use the custom authorizer
specified above.
"/http" : {
"get" : {
"responses" : { },
"security" : [ {
"test-authorizer" : [ ]
} ],
"x-amazon-apigateway-integration" : {
"type" : "http",
"responses" : {
"default" : {
"statusCode" : "200"
}
},
"httpMethod" : "GET",
"uri" : "http://api.example.com"
}
}
}
132
x-amazon-apigateway-authtype Property
Specify the type of a custom authorizer. It is parsed by the API Gateway API import and export
features.
This property is an extended property of the Swagger Security Definitions Operation object.
x-amazon-apigateway-authtype Example
The following example sets the type of a custom authorizer using OAuth 2.
"cust-authorizer" : {
"type" : "...", // required
"name" : "...", // name of the identity source header
"in" : "header", // must be header
"x-amazon-apigateway-authtype" : "oauth2", // Specifies the
authorization mechanism for the client.
"x-amazon-apigateway-authorizer" : {
...
}
}
The following security definition example specifies authorization using AWS Signature Version 4:
"sigv4" : {
"type" : "apiKey",
"name" : "Authorization",
"in" : "header",
"x-amazon-apigateway-authtype" : "awsSigv4"
}
x-amazon-apigateway-integration Object
Specifies details of the back-end integration used for this method. This extension is an extended
property of the Swagger Operation object. The result is an API Gateway integration object.
Properties
Property Name
Type
Description
type
string
uri
string
133
Property Name
Type
Description
httpMethod
string
credentials
string
requestTemplates
requestParameters
cacheNamespace
string
cacheKeyParameters
An array of string
responses
x-amazon-apigateway-integration Example
The following example integrates an API's POST method with a Lambda function in the back end.
For demonstration purposes, the sample mapping templates shown in requestTemplates and
responseTemplates of the examples below are assumed to apply to the following JSON-formatted
payload: { "name":"value_1", "key":"value_2", "redirect": {"url" :"..."} } to
generate a JSON output of { "stage":"value_1", "user-id":"value_2" } or an XML output
of <stage>value_1</stage>.
"x-amazon-apigateway-integration" : {
134
"type" : "aws",
"uri" : "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:012345678901:function:HelloWorld/invocations",
"httpMethod" : "POST",
"credentials" : "arn:aws:iam::012345678901:role/apigateway-invoke-lambdaexec-role",
"requestTemplates" : {
"application/json" : "#set ($root=$input.path('$')) { \"stage
\": \"$root.name\", \"user-id\": \"$root.key\" }",
"application/xml" : "#set ($root=$input.path('$')) <stage>
$root.name</stage> "
},
"requestParameters" : {
"integration.request.path.stage" :
"method.request.querystring.version",
"integration.request.querystring.provider" :
"method.request.querystring.vendor"
},
"cacheNamespace" : "cache namespace",
"cacheKeyParameters" : [],
"responses" : {
"2\\d{2}" : {
"statusCode" : "200",
"responseParameters" : {
"method.response.header.requestId" :
"integration.response.header.cid"
},
"responseTemplates" : {
"application/json" : "#set ($root=$input.path('$')) { \"stage
\": \"$root.name\", \"user-id\": \"$root.key\" }",
"application/xml" : "#set ($root=$input.path('$')) <stage>
$root.name</stage> "
}
},
"302" : {
"statusCode" : "302",
"responseParameters" : {
"method.response.header.Location" :
"integration.response.body.redirect.url"
}
},
"default" : {
"statusCode" : "400",
"responseParameters" : {
"method.response.header.test-method-response-header" :
"'static value'"
}
}
}
}
Note that double quotes (") of the JSON string in the mapping templates must be string-escaped (\").
x-amazon-apigateway-integration.requestTemplates Object
Specifies mapping templates for a request payload of the specified MIME types.
135
Properties
Property Name
Type
Description
MIME type
string
x-amazon-apigateway-integration.requestTemplates Example
The following example sets mapping templates for a request payload of the application/json and
application/xml MIME types.
"requestTemplates" : {
"application/json" : "#set ($root=$input.path('$')) { \"stage\":
\"$root.name\", \"user-id\": \"$root.key\" }",
"application/xml" : "#set ($root=$input.path('$')) <stage>$root.name</
stage> "
}
x-amazon-apigateway-integration.requestParameters Object
Specifies mappings from named method request parameters to integration request parameters. The
method request parameters must be defined before being referenced.
Properties
Property Name
Type
Description
The value must be a predefined
method request parameter of the
method.request.<paramtype>.<param-name> format,
where <param-type> can
be querystring, path,
header, or body. For the body
parameter, the <param-name>
is a JSON path expression
without the $. prefix.
integration.request.<paramstring
type>.<param-name>
x-amazon-apigateway-integration.requestParameters
Example
The following request parameter mappings example translates a method request's query (version),
header (x-user-id) and path (service) parameters to the integration request's query (stage),
header (x-userid), and path parameters (op), respectively.
"requestParameters" : {
"integration.request.querystring.stage" :
"method.request.querystring.version",
136
"integration.request.header.x-userid" : "method.request.header.x-userid",
"integration.request.path.op" : "method.request.path.service"
},
x-amazon-apigateway-integration.responses Object
Defines the method's responses and specifies parameter mappings or payload mappings from
integration responses to method responses.
Properties
Property Name
Type
Description
Note
The Response
status pattern
property name refers to
a response status code
or regular expression
describing a group of
response status codes.
It does not correspond
to any identifier of an
IntegrationResponse
resource in the API
Gateway REST API.
x-amazon-apigateway-integration.responses
Example
The following example shows a list of responses from 2xx and 302 responses. For the 2xx response,
the method response is mapped from the integration response's payload of the application/json
or application/xml MIME type. This response uses the supplied mapping templates. For the
302 response, the method response returns a Location header whose value is derived from the
redirect.url property on the integration response's payload.
"responses" : {
137
"2\\d{2}" : {
"statusCode" : "200",
"responseTemplates" : {
"application/json" : "#set ($root=$input.path('$')) { \"stage\":
\"$root.name\", \"user-id\": \"$root.key\" }",
"application/xml" : "#set ($root=$input.path('$')) <stage>
$root.name</stage> "
}
},
"302" : {
"statusCode" : "302",
"responseParameters" : {
"method.response.header.Location":
"integration.response.body.redirect.url"
}
}
}
x-amazon-apigateway-integration.response Object
Defines a response and specifies parameter mappings or payload mappings from the integration
response to the method response.
Properties
Property Name
Type
Description
statusCode
string
responseTemplates
responseParameters
x-amazon-apigateway-integration.response
Example
The following example defines a 302 response for the method that derives a payload of the
application/json or application/xml MIME type from the back end. The response uses the
supplied mapping templates and returns the redirect URL from the integration response in the method's
Location header.
138
"statusCode" : "302",
"responseTemplates" : {
"application/json" : "#set ($root=$input.path('$')) { \"stage\":
\"$root.name\", \"user-id\": \"$root.key\" }",
"application/xml" : "#set ($root=$input.path('$')) <stage>
$root.name</stage> "
},
"responseParameters" : {
"method.response.header.Location":
"integration.response.body.redirect.url"
}
}
x-amazon-apigateway-integration.responseTemplates Object
Specifies mapping templates for a response payload of the specified MIME types.
Properties
Property Name
Type
Description
MIME type
string
x-amazon-apigateway-integration.responseTemplate Example
The following example sets mapping templates for a request payload of the application/json and
application/xml MIME types.
"responseTemplates" : {
"application/json" : "#set ($root=$input.path('$')) { \"stage\":
\"$root.name\", \"user-id\": \"$root.key\" }",
"application/xml" : "#set ($root=$input.path('$')) <stage>$root.name</
stage> "
}
x-amazon-apigateway-integration.responseParameters Object
Specifies mappings from integration method response parameters to method response parameters.
Only the header and body types of the integration response parameters can be mapped to the
header type of the method response.
139
Properties
Property Name
Type
Description
The named parameter value can
be derived from the header and
body types of the integration
response parameters only.
method.response.header.<paramstring
name>
x-amazon-apigateway-integration.responseParameters
Example
The following example maps body and header parameters of the integration response to two header
parameters of the method response.
"responseParameters" : {
"method.response.header.Location" :
"integration.response.body.redirect.url",
"method.response.header.x-user-id" : "integration.response.header.xuserid"
}
140
API Gateway supports multiple mechanisms of access control, including metering or tracking API
uses by clients using API keys. The standard AWS IAM roles and policies offer flexible and robust
access controls that can be applied to an entire API set or individual methods. Custom authorizers and
Amazon Cognito user pools provide customizable authorization and authentication solutions.
Topics
Set IAM Permissions to Access API Gateway (p. 141)
Enable CORS for an API Gateway Resource (p. 151)
Use an API Key in API Gateway (p. 155)
Use Amazon API Gateway Custom Authorizers (p. 156)
Use Amazon Cognito Your User Pool (p. 164)
Use Client-Side SSL Certificates for Authentication by the Back End (p. 167)
141
apigateway and the API executing service as execute-api. The apigateway service supports the
actions of GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD and the execute-api service supports
the Invoke and InvalidateCache actions. To create an IAM policy using the Policy Generator in the
IAM console, select Manage Amazon API Gateway as AWS Service to set permissions statements
for apigateway and select Amazon API Gateway as AWS Service to set permission statements for
execute-api.
You can use IAM to allow IAM users and roles in your AWS account to manage only certain API
Gateway entities (for example, APIs, resources, methods, models, and stages) and perform only
certain actions against those entities. You may want to do this, for example, if you have IAM users you
want to allow to list, but not create, resources and methods for selected APIs. You may have other IAM
users you want to allow to list and create new resources and methods for any API they have access to
in API Gateway.
In the Get Ready to Use API Gateway (p. 4) instructions, you attached an access policy to an IAM user
in your AWS account that contains a policy statement similar to this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"apigateway:*"
],
"Resource": [
"*"
]
}
]
}
This statement allows the IAM user in your AWS account to perform all available actions and access all
available resources in API Gateway to which your AWS account has access. In practice, you may not
want to give the IAM users in your AWS account this much access.
You can also use IAM to enable users inside your organization to interact with only certain API
methods in API Gateway.
In the Configure How a User Calls an API Method (p. 73) instructions, the API Gateway console may
have displayed a resource ARN you used to create a policy statement similar to this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:my-aws-account-id:my-api-id/my-stage/
GET/my-resource-path"
]
}
]
}
142
This statement allows the IAM user to call the GET method for the resource path associated with the
specified resource ARN in API Gateway. In practice, you may want to give IAM users access to more
methods.
Note
IAM policies are effective only if IAM authentication is enabled. If you, as the API owner, has
enabled AWS identity and access management on a specific resource, users from other AWS
accounts cannot access your API. If you do not enable IAM authentication on the resource,
that resource is effectively public accessible.
2.
Choose Policies, and then choose Create Policy. (If a Get Started button appears, choose it,
and then choose Create Policy.)
3.
4.
For Policy Name, type any value that will be easy for you to refer to later, if needed.
5.
For Policy Document, type a policy statement with the following format, and then choose Create
Policy:
{
"Version": "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"action-statement"
],
"Resource" : [
"resource-statement"
]
},
{
"Effect" : "Allow",
"Action" : [
"action-statement"
],
"Resource" : [
"resource-statement"
]
}
]
}
Choose Users.
7.
Choose the IAM user to whom you want to attach the policy.
8.
143
9.
Select the policy you just created, and then choose Attach Policy.
where region is a target AWS region (such as us-east-1 or * for all supported AWS regions), and
resource-path-specifier is the path to the target resources.
Some example resource expressions include:
arn:aws:apigateway:region::/restapis/* for all resources, methods, models, and stages in
the AWS region of region.
144
where:
145
region is the AWS region (such as us-east-1 or * for all AWS regions) that corresponds to the
deployed API for the method.
account-id is the 12-digit AWS account Id of the REST API owner.
api-id is the identifier API Gateway has assigned to the API for the method. (* can be used for all
APIs, regardless of the API's identifier.)
stage-name is the name of the stage associated with the method (* can be used for all stages,
regardless of the stage's name.)
HTTP-VERB is the HTTP verb for the method. It can be one of the following: GET, POST, PUT,
DELETE, PATCH, HEAD, OPTIONS.
resource-path-specifier is the path to the desired method. (* can be used for all paths).
Some example resource expressions include:
arn:aws:execute-api:*:*:* for any resource path in any stage, for any API in any AWS region.
(This is equivalent to *).
arn:aws:execute-api:us-east-1:*:* for any resource path in any stage, for any API in the
AWS region of us-east-1.
arn:aws:execute-api:us-east-1:*:api-id/* for any resource path in any stage, for the API
with the identifier of api-id in the AWS region of us-east-1.
arn:aws:execute-api:us-east-1:*:api-id/test/* for resource path in the stage of test,
for the API with the identifier of api-id in the AWS region of us-east-1.
arn:aws:execute-api:us-east-1:*:api-id/test/*/mydemoresource/* for any resource
path along the path of mydemoresource, for any HTTP method in the stage of test, for the API
with the identifier of api-id in the AWS region of us-east-1.
arn:aws:execute-api:us-east-1:*:api-id/test/GET/mydemoresource/* for GET
methods under any resource path along the path of mydemoresource, in the stage of test, for the
API with the identifier of api-id in the AWS region of us-east-1.
146
"Effect": "Allow",
"Action": [
"apigateway:GET"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/a123456789/*"
]
}
]
}
The following example policy statement gives the IAM user permission to list information for all
resources, methods, models, and stages in any region. The user also has permission to perform all
available API Gateway actions for the API with the identifier of a123456789 in the AWS region of useast-1:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"apigateway:GET"
],
"Resource": [
"arn:aws:apigateway:*::/restapis/*"
]
},
{
"Effect": "Allow",
"Action": [
"apigateway:*"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/a123456789/*"
]
}
]
}
147
],
"Resource": [
"arn:aws:apigateway:us-east-1::/*"
]
},
{
"Sid": "Stmt1467321341000",
"Effect": "Deny",
"Action": [
"apigateway:GET",
"apigateway:HEAD",
"apigateway:OPTIONS"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/",
"arn:aws:apigateway:us-east-1::/account",
"arn:aws:apigateway:us-east-1::/clientcertificates",
"arn:aws:apigateway:us-east-1::/domainnames",
"arn:aws:apigateway:us-east-1::/apikeys"
]
},
{
"Sid": "Stmt1467321344000",
"Effect": "Allow",
"Action": [
"apigateway:GET",
"apigateway:HEAD",
"apigateway:OPTIONS"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/*"
]
}
]
}
The first Deny statement explicitly prohibits any calls of POST, PUT, PATCH, DELETE on any resources
in API Gateway. This ensures that such permissions will not be overridden by other policy documents
also attached to the caller. The second Deny statement blocks the caller to query the root (/) resource,
account information (/account), client certificates (/clientcertificates), custom domain names
(/domainnames) and API keys (/apikeys. Together, the three statements ensure that the caller can
only query API-related resources. This can be useful in API testing when you do not want the tester to
modify any of the code.
To restrict the above read-only access to specified APIs, replace the Resource property of Allow
statement by the following:
"Resource": ["arn:aws:apigateway:us-east-1::/restapis/restapi_id1/*",
"arn:aws:apigateway:us-east-1::/restapis/restapi_id2/*"]
148
"Statement": [
{
"Sid": "Stmt1467321765000",
"Effect": "Allow",
"Action": [
"apigateway:*"
],
"Resource": [
"*"
]
}
]
}
In general, you should refrain from using such a broad and open access policy. It may be necessary to
do so for your API development core team so that they can create, deploy, update, and delete any API
Gateway resources.
The above policy document grants full access permissions only to the stages collection and any of
the contained stage resources, provided that no other policies granting more accesses have been
attached to the caller. Otherwise, you must explicitly deny all the other accesses.
Using the above policy, caller must find out the REST API's identifier beforehand because the
user cannot call GET /respais to query the available APIs. Also, if arn:aws:apigateway:useast-1::/restapis/*/stages is not specified in the Resource list, the Stages resource becomes
inaccessible. In this case, the caller will not be able to create a stage nor get the existing stages,
although he or she can still view, update or delete a stage, provided that he stage's name is known.
To grant permissions for a specific API's stages, simply replace the restapis/* portion of the
Resource specifications by restapis/restapi_id, where restapi_id is the identifier of the API
of interest.
149
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1467331998000",
"Effect": "Allow",
"Action": [
"apigateway:GET",
"apigateway:HEAD",
"apigateway:OPTIONS",
"apigateway:PATCH",
"apigateway:POST",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/*"
]
},
{
"Sid": "Stmt1467332141000",
"Effect": "Allow",
"Action": [
"apigateway:DELETE"
],
"Condition": {
"StringNotLike": {
"aws:username": "johndoe"
}
},
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/*"
]
}
]
}
This IAM policy grants full access permission to create, deploy, update and delete API for attached
users, groups or roles, except for the specified user (johndoe), who cannot delete any API resources.
It assumes that no other policy document granting Allow permissions on the root, API keys, client
certificates or custom domain names has been attached to the caller.
To block the specified user from deleting specific API Gateway resources, e.g., a specific API or an
API's resources, replace the Resource specification above by this:
"Resource": ["arn:aws:apigateway:us-east-1::/restapis/restapi_id_1",
"arn:aws:apigateway:us-east-1::/restapis/restapi_id_2/resources"]
150
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:*:a123456789/test/POST/mydemoresource/
*"
]
}
]
}
The following example policy statement gives the user permission to call any method on the resource
path of petstorewalkthrough/pets, in any stage, for the API with the identifier of a123456789, in
any AWS region where the corresponding API has been deployed:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:*:*:a123456789/test/*/petstorewalkthrough/pets"
]
}
]
}
Tip
You must set up an OPTIONS method to handle preflight requests to support CORS.
However, OPTIONS methods are optional if 1) an API resource exposes only the GET, HEAD
or POST methods and 2) the request payload content type is application/x-www-formurlencoded, multipart/form-data or text/plain and 3) the request does not contain
151
any custom headers. When possible, we recommend to use OPTIONS method to enable
CORS in your API.
This section describes how to enable CORS for a method in API Gateway using the API Gateway
console or the API Gateway Import API.
Topics
Prerequisites (p. 152)
Enable CORS on a Resource Using the API Gateway Console (p. 152)
Enable CORS for a Resource Using the API Gateway Import API (p. 153)
Prerequisites
You must have the method available in API Gateway. For instructions on how to create and
configure a method, see Build an API Gateway API as an HTTP Proxy (p. 6).
4.
Alternatively, you could choose a method under the resource to enable CORS for just this method.
Choose Enable CORS from the Actions drop-down menu.
5.
b.
152
c.
6.
In Confirm method changes, choose Yes, overwrite existing values to confirm the new CORS
settings.
After CORS is enabled on the GET method, an OPTIONS method is added to the resource, if it is not
already there. The 200 response of the OPTIONS method is automatically configured to return the
three Access-Control-Allow-* headers to fulfill preflight handshakes. In addition, the actual (GET)
method is also configured by default to return the Access-Control-Allow-Origin header in its
200 response as well. For other types of responses, you will need to manually configure them to return
Access-Control-Allow-Origin' header with '*' or specific origin domain names, if you do not
want to return the Cross-origin access error.
Note
Web browsers expect Access-Control-Allow-Headers, and Access-Control-Allow-Origin
headers to be set up in each API method that accepts CORS requests. In addition, some
browsers first make an HTTP request to an OPTIONS method in the same resource, and then
expect to receive the same headers.
153
The following example creates an OPTIONS method and specifies mock integration. For more
information, see Configure Mock Integration for a Method (p. 78).
/users
options:
summary: CORS support
description: |
Enable CORS by returning correct headers
consumes:
- application/json
produces:
- application/json
tags:
- CORS
x-amazon-apigateway-integration:
type: mock
requestTemplates:
application/json: |
{
"statusCode" : 200
}
responses:
"default":
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Headers :
"'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
method.response.header.Access-Control-Allow-Methods : "'*'"
method.response.header.Access-Control-Allow-Origin : "'*'"
responseTemplates:
application/json: |
{}
responses:
200:
description: Default response for CORS method
headers:
Access-Control-Allow-Headers:
type: "string"
Access-Control-Allow-Methods:
type: "string"
Access-Control-Allow-Origin:
type: "string"
Once you have configured the OPTIONS method for your resource, you can add the required headers
to the other methods in the same resource that need to accept CORS requests.
1.
154
type: "string"
2.
In the x-amazon-apigateway-integration tag, set up the mapping for those headers to your
static values:
responses:
"default":
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Headers :
"'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
method.response.header.Access-Control-Allow-Methods : "'*'"
method.response.header.Access-Control-Allow-Origin : "'*'"
Prerequisites
1.
You must have an API available in API Gateway. Follow the instructions in Creating an API (p. 70).
2.
You must have deployed the API in API Gateway at least once. Follow the instructions in
Deploying an API (p. 173).
2.
3.
4.
If API Key Required is set to false, choose the pencil icon next to it. From the drop-down menu
list, choose true. Finally, choose the check-mark icon to save the setting.
Note
The steps above configures the API Gateway to enforce using API key. Otherwise, the
API key created following the instructions below will not be used.
5.
In the secondary navigation bar, in the first list next to the console home button, choose API Keys.
6.
7.
155
8.
(Optional) For Description, type a description for the API key entry.
9.
10. Choose Save. Make a note of the key displayed in API key.
11. For API Stage Association, for Select API, choose the name of the API.
12. For Select stage, choose the name of the stage.
13. Choose Add, and then choose Save.
14. Deploy or redeploy the API for the effect to take place.
15. Callers must now add to each call a custom header named x-api-key, along with the value of
the API key. For example, if the API key value is bkayZOMvuy8aZOhIgxq94K9Oe7Y70Hw55, the
custom header would be as follows:
x-api-key: bkayZOMvuy8aZOhIgxq94K9Oe7Y70Hw55
Note
In addition to, or instead of, enabling an API key, you can restrict access to certain IAM users
only. For instructions, see Configure How a User Calls an API Method (p. 73).
156
Note
The custom authorizer Lambda function presented here is for illustration purposes. In
production code, you should follow the API Gateway Custom Authorizer blueprint to
implement your authorizer Lambda function.
When creating the Lambda function for your API Gateway custom authorizer, you will be asked to
assign an execution role for the Lambda function if it calls other AWS services. For the following
example, the basic AWSLambdaRole will suffice. For more involved use cases, follow the instructions to
grant permissions in an execution role for the Lambda function.
In the code editor of the Lambda console, enter the following Node.js code.
console.log('Loading function');
exports.handler = function(event, context) {
var token = event.authorizationToken;
// Call oauth provider, crack jwt token, etc.
// In this example, the token is treated as the status for simplicity.
switch (token) {
case 'allow':
context.succeed(generatePolicy('user', 'Allow',
event.methodArn));
break;
case 'deny':
context.succeed(generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
context.fail("Unauthorized");
break;
157
default:
context.fail("error");
}
};
var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17'; // default version
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke'; // default action
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
return authResponse;
}
The preceding Lambda function returns an Allow IAM policy on a specified method if the request's
authorization token contains an 'allow' value, thereby permitting a caller to invoke the specified
method. The caller receives an 200 OK response. The function returns a Deny policy against the
specified method if the authorization token has a 'deny' value, thus blocking the caller from calling
the method. The client will receive a 403 Forbidden response. If the token is 'unauthorized', the
client will receive a 401 Unauthorized response. If the token is 'fail' or anything else, the client will
receive a 500 Internal Server Error response. In both of the last two cases, the calls will not succeed.
Note
In production code, you may need to authenticate the user before granting authorizations.
If so, you can add authentication logic in the Lambda function as well. Consult the providerspecific documentation for instructions on how to call such an authentication provider.
Before going further, you may want to test the Lambda function from within the Lambda Console. To
do this, configure the sample event to provide the input and verify the result by examining the output.
The next two sections explain the Input to a Custom Authorizer (p. 158) and Output from a Custom
Authorizer (p. 159).
{
"type":"TOKEN",
"authorizationToken":"<caller-supplied-token>",
"methodArn":"arn:aws:executeapi:<regionId>:<accountId>:<apiId>/<stage>/<method>/<resourcePath>"
158
In this example, the type property specifies the payload type. Currently, the only valid value is the
TOKEN literal. The <caller-supplied-token> originates from the custom authorization header in
a client request. The methodArn is the ARN of the incoming method request and is populated by API
Gateway in accordance with the custom authorizer configuration.
For the custom authorizer shown in the preceeding section, the <caller-supplied-token> string
is allow, deny, unauthorized, or any other string value. An empty string value is the same as
unauthorized. The following shows an example of such an input to obtain an Allow policy on the
GET method of an API (ymy8tbxw7b) of the AWS account (123456789012) in any stage (*).
{
"type":"TOKEN",
"authorizationToken":"allow",
"methodArn":"arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/
GET/"
}
{
"principalId": "xxxxxxxx", // The principal user identification associated
with the token send by the client.
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow|Deny",
"Resource": "arn:aws:executeapi:<regionId>:<accountId>:<appId>/<stage>/<httpVerb>/[<resource>/<httpVerb>/
[...]]"
}
]
}
}
Here, a policy statement stipulates whether to allow or deny (Effect) the API Gateway execution
service to invoke (Action) the specified API method (Resource). You can use a wild card (*) to
specify a resource type (method).
You can access the principalId value in a mapping template using the
$context.authorizer.principalId variable. This is useful if you want to pass the value to the
back end. For more information, see Accessing the $context Variable (p. 117).
159
For information about valid policies for calling an API, see Statement Reference of IAM Policies for
Executing API in API Gateway (p. 145).
The following shows example output from the example custom authorizer. The example output
contains a policy statement to block (Deny) calls to the GET method in an API (ymy8tbxw7b) of an
AWS account (123456789012) in any stage (*).
{
"principalId": "user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/*/
GET/"
}
]
}
}
2.
3.
Note
You must first create a custom authorizer Lambda function in the region for it to be
available in the drop-down list.
In Authorizer Name, enter a name for your new custom authorizer.
Leave Execution role blank to let the API Gateway console to set a resource-based policy
to grant API Gateway permissions to invoke the authorizer Lambda function or type the
name of an IAM role to allow API Gateway to invoke the authorizer Lambda function. For an
example of such a role, see Set Up an IAM Role and Policy for an API to Invoke Lambda
Functions (p. 231).
In Identity token source, type the mapping expression for your authorizer's custom header.
Note
The custom header mapping expression is of the method.request.header.<name>
format, where <name> is the name of a custom authorization header submitted as part
of the client request. In the following example, this custom header name is Auth.
160
In Token validation expression, you can optionally provide a RegEx statement for API
Gateway to validate the input token before calling the custom authorizer Lambda function. This
helps you avoid or reduce the chances of being charged for processing invalid tokens.
In Result TTL in seconds, you can change or use the default (300) value to enable caching
(>0) or disable caching (=0) of the policy returned from the Lambda function.
Note
The policy caching uses a cache key generated from the supplied token for the
targeted API and custom authorizer in a specified stage. To enable caching, your
authorizer must return a policy that is applicable to all methods across an API. To
enforce method-specific policy, you can set the TTL value to zero to disable policy
caching for the API.
4.
If you choose to let the API Gateway console to set the resource-based policy, the Add
Permission to Lambda Function dialog will be displayed. Choose OK. After the custom
authorization is created, you can test it with appropriate authorization token values to verify that it
works as expected.
This completes the procedure to create a custom authorization. The next procedure shows how to
configure an API method to use the custom authorizer.
Go back to the API. Create a new method or choose an existing method. If necessary, create a
new resource.
2.
3.
Under Authorization Settings, expand the Authorization drop-down list to select the custom
authorizer you just created (myTestApiAuthorizer), and then choose the checkmark icon to save
the choice.
161
4.
Optionally, while still on the Method Request page, choose Add header if you also want to pass
the custom authorization header to the back end. In Name, type a custom header name that
matches the header mapping expression you used when you created the custom authorization,
and then choose the checkmark icon to save the settings.
5.
Choose Deploy API to deploy the API to a stage. Make a note of the Invoke URL value. You will
need it when calling the API.
Note
When calling an authorizer-enabled method, API Gateway will not log the call to CloudWatch
if the required token is not set, null or invalidated by the specified Token validation
expression.
Open the Postman Chrome App, choose the GET method and paste the API's Invoke URL into
the adjacent URL field.
Add the custom authorization token header and set the value to allow. Choose Send.
162
The response shows that the API Gateway custom authorizer returns a 200 OK response and
successfully authorizes the call to access the HTTP endpoint (http://httpbin.org/get) integrated with
the method.
2.
Still in Postman, change the custom authorization token header value to deny. Choose Send.
The response shows that the API Gateway custom authorizer returns a 403 Forbidden response
without authorizing the call to access the HTTP endpoint.
3.
In Postman, change the custom authorization token header value to unauthorized and choose
Send.
163
4.
The response shows that API Gateway returns a 401 Unauthorized response without authorizing
the call to access the HTTP endpoint.
Now, change the custom authorization token header value to fail. Choose Send.
The response shows that API Gateway returns a 500 Internal Server Error response without
authorizing the call to access the HTTP endpoint.
164
the authorizer on selected API methods. You must also distribute to your API client developers the
user pool ID, a client ID, and possibly the associated client secret that are provisioned from the user
pool. The client will need this information to register users with the user pool, to provide the sign-in
functionality, and to have the user's identity token provisioned from the user pool.
In this section, you will learn how to create a user pool, how to integrate an API Gateway API with the
user pool, and how to invoke an API integrated with the user pool.
Topics
Create a User Pool (p. 165)
Integrate an API with a User Pool (p. 165)
Call an API Integrated with a User Pool (p. 166)
Note
Make note of the user pool ID, client ID and the client secret, if selected. The client will need
to provide them to Amazon Cognito for the user to register with the user pool, to sign in to
the user pool, and to get an identity token to be included in requests to call API methods
configured with the user pool. Also, you will need to specify the user pool name when you
configure the user pool as an authorizer in API Gateway, as described next.
2.
From the main navigation pane, choose Authorizers under the specified API.
3.
Under Authorizers, choose Create and then choose Cognito User Pool Authorizer.
4.
5.
a.
b.
c.
The Authorizer name field will be automatically populated with the chosen user pool name.
However, you can customize it if you want to.
d.
e.
Optionally, type a regular expression in the App client ID regex field to validate client IDs
associated with the user pool.
f.
Choose Create to finish integrating the user pool with the API.
Having created the authorizer, you can, optionally, test it by supplying an identity token
provisioned from the user pool.
165
2.
3.
Under Authorization Settings, choose the edit icon by the Authorization field.
4.
Choose one of the available Amazon Cognito User Pool authorizers from the drop-down list.
5.
6.
7.
If you have declared a custom claim field when configuring your user pool, you can follow the
same pattern to access the custom fields. The following example gets a custom role field of a
claim:
{
"context" : {
"role" : "$context.authorizer.claims.role"
}
}
If the custom claim field is declared as custom:role, use the following example to get the claim's
property:
{
"context" : {
"role" : "$context.authorizer.claims['custom:role']"
}
}
You can use one of the AWS SDKs to perform these tasks. For example:
To use the Android SDK, see Setting up the AWS Mobile SDK for Android to Work with User Pools.
To use the iOS SDK, see Setting Up the AWS Mobile SDK for iOS to Work with User Pools.
To use JavaScript, see Setting up the AWS SDK for JavaScript in the Browser to Work with User
Pools.
The following procedure outlines the steps to perform these tasks. For more information, see the blog
posts on Using Android SDK with Amazon Cognito Your User Pools and Using Your Amazon Cognito
User Pool for iOS.
2.
3.
4.
Call API methods configured with a user pool authorizer, supplying the unexpired token in the
Authorization header or another header of your choosing.
5.
When the token expires, repeat Step 2-4. Identity tokens provisioned by Amazon Cognito expire
within an hour.
For code examples, see an Android Java sample and an iOS Objective-C sample.
2.
3.
Optionally, For Description, enter a short descriptive title for the generated certificate. API
Gateway generates a new certificate and returns the new certificate GUID, along with the PEMencoded public key.
167
4.
In the API Gateway console, create or open an API for which you want to use the client certificate.
Make sure the API has been deployed to a stage.
2.
Choose Stages under the selected API and then choose a stage.
3.
In the Stage Editor panel, select a certificate under the Client Certificate section.
4.
168
After a certificate is selected for the API and saved, API Gateway will use the certificate for all calls to
HTTP integrations in your API.
Test Invoke
1.
2.
API Gateway will present the chosen SSL certificate for the HTTP back end to authenticate the API.
169
Prerequisites
You must have an API available in API Gateway. Follow the instructions in Creating an API (p. 70).
2.
170
Warning
Deleting an API means that you can no longer call it. This action cannot be undone.
Topics
Prerequisites (p. 171)
Delete an API with the API Gateway Console (p. 171)
Prerequisites
You must have deployed the API at least once. Follow the instructions in Deploying an
API (p. 173).
2.
In the box that contains the name of the API you want to delete, choose Resources.
3.
4.
Warning
When you delete a resource, you also delete its child resources and methods. Deleting a
resource may cause part of the corresponding API to be unusable. Deleting a resource cannot
be undone.
2.
In the box that contains the name of the API for the resource you want to delete, choose
Resources.
In the Resources pane, choose the resource, and then choose Delete Resource.
When prompted, choose Delete.
3.
4.
Prerequisites
You must have methods available in API Gateway. Follow the instructions in Build an API
Gateway API as an HTTP Proxy (p. 6).
171
2.
3.
In the box that contains the name of the API, choose Resources.
The list of methods is displayed in the Resources pane.
Tip
You may need to choose the arrow next to one or more resources to display all of the
available methods.
Warning
Deleting a method may cause part of the corresponding API to become unusable. Deleting a
method cannot be undone.
2.
3.
In the box that contains the name of the API for the method, choose Resources.
In the Resources pane, choose the arrow next to the resource for the method.
4.
5.
172
You must specify settings for all of the methods in the API you want to deploy. Follow the
instructions in Set up Method and Integration (p. 71).
173
1.
2.
In the box that contains the name of the API you want to deploy, choose Resources.
3.
4.
Tip
The stage name should be meaningful, but short enough to be easy and fast to type.
Your users will specify this name as part of the URL they will use to invoke the API.
5.
6.
7.
Choose Deploy.
If needed, choose the Settings tab in the Stage Editor pane of the API Gateway Console.
You can then choose to use or not use API cache, to enable or disable CloudWatch logs, to
change throttling settings, or to select or deselect a client certificate.
2.
If needed, choose the Stage Variables tab in the Stage Editor pane of the API Gateway Console.
You can then choose to update the values of selected stage variables.
3.
If you made any change, choose the Save Changes button; go back to the Resources window;
and then choose Deploy API again.
Note
If the updated settings, such as enabling logging, requires a new IAM role, you can add the
required IAM role without redeploying the API. However, it can take a few minutes before the
new IAM role takes effect. Before that happens, traces of your API calls will not be logged
even if you have enabled the logging option.
You must have deployed to the stage at least twice. Follow the instructions in Deploy an API with
the API Gateway Console (p. 173).
2.
3.
In the box that contains the name of the API with the stage you want to change, choose Stages.
4.
5.
On the Deployment History tab, choose the option button next to the deployment you want the
stage to use.
6.
Prerequisites
1.
You must have an API available in API Gateway. Follow the instructions in Creating an API (p. 70).
2.
You must have deployed the API at least once. Follow the instructions in Deploying an
API (p. 173).
2.
In the box that contains the name of the API, choose Stages.
3.
4.
5.
6.
For Deployment, choose the date and time of the existing API deployment you want to associate
with this stage.
7.
Choose Create.
175
Prerequisites
1.
You must have an API available in API Gateway. Follow the instructions in Creating an API (p. 70).
2.
You must have deployed the API in API Gateway at least once. Follow the instructions in
Deploying an API (p. 173).
2.
In the box that contains the name of the API, choose Stages.
Set Up a Stage
This section walks you through the options to set up an API deployment stage in the API Gateway
console.
Topics
Prerequisites (p. 176)
Set Up an API Deployment Stage with the API Gateway Console (p. 176)
Prerequisites
You must have a stage available in API Gateway. Follow the instructions in Create a
Stage (p. 175).
2.
In the box that contains the name of the API for the stage where you want to specify settings,
choose Stages.
3.
4.
To enable a cache for the API, on the Settings tab, in the Cache Settings area, select Enable
API cache. Then, for Cache capacity, choose a cache size. You can use the default for other
cache settings. For information on how to set up these, . Finally, choose Save Changes.
Important
By selecting this box, your AWS account may be charged for API caching.
Tip
To override enabled stage-level cache settings, expand the stage under the Stages
secondary navigation pane, choose a method. Then back in the stage editor, choose
Override for this method for Settings. In the ensuing Cache Settings area, clear
Enable Method Cache or customize any other desired options, before choosing Save
Changes. For more information about the method-level and other stage-level cache
settings, see Enable API Caching (p. 179).
5.
To generate code to call the API from Android, iOS, or JavaScript, you use the SDK Generation
tab. For more information, see Generate an SDK for an API (p. 197).
6.
To enable Amazon CloudWatch Logs for all of the methods associated with this stage of this API
Gateway API, do the following:
176
1.
On the Settings tab, in the CloudWatch Settings area, select Enable CloudWatch Logs.
Tip
To enable method-level CloudWatch settings, expand the stage under the Stages
secondary navigation pane, choose each method of interest, and, back in the stage
editor, choose Override for this method for Settings. In the ensuing CloudWatch
Settings area, make sure to select Log to CloudWatch Logs and any other desired
options, before choosing Save Changes.
Important
Your account will be charged for accessing method-level CloudWatch metrics, but
not the API- or stage- level metrics.
2.
For Log level, choose ERROR to write only error-level entries to CloudWatch Logs, or
choose INFO to include all ERROR events as well as extra informational events. No sensitive
data will be logged unless the Log full requests/responses data option is selected.
3.
To write entries to CloudWatch Logs that contain full API call request and response
information, select Log full requests/responses data.
4.
Choose Save Changes. The new settings will take effect after a new deployment.
Important
Whether you enable CloudWatch Logs for all or only some of the methods, you must
also specify the ARN of an IAM role that enables API Gateway to write information
to CloudWatch Logs on behalf of your IAM user. To do this, in the secondary
navigation bar, in the first list next to the console home button, choose Settings.
Then type the ARN of the IAM role in the CloudWatch Logging role ARN box. For
common application scenarios, the IAM role could attach the managed policy of
AmazonAPIGatewayPushToCloudWatchLogs, which contains the following access
policy statement:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
"logs:GetLogEvents",
"logs:FilterLogEvents"
],
"Resource": "*"
}
]
}
The IAM role must also contain the following trust relationship statement:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
177
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
To create the IAM role, you can adapt the instructions in "To create the Lambda
invocation role and its policy" and "To create the Lambda execution role and its
policy" in the Create Lambda Functions (p. 44) section of the Build an API as a
Lambda Proxy (p. 43).
For more information about CloudWatch, see the Amazon CloudWatch Developer
Guide.
7.
To enable Amazon CloudWatch metrics for all of the methods associated with this API in API
Gateway, in the Stage Editor pane, on the Settings tab, in the CloudWatch Settings area, select
Enable CloudWatch metrics, and then choose Save Changes. The new settings will take effect
after a new deployment.
Important
By selecting this box, your AWS account may be charged for using CloudWatch.
Tip
To enable CloudWatch metrics for only some methods, clear Enable CloudWatch
metrics. In the Stages pane, choose each of the methods for which you want to enable
CloudWatch metrics. For each method you choose, on the Settings tab for the method,
choose Override for this method, and in the CloudWatch Settings area, select Enable
CloudWatch metrics. Finally, choose Save Changes.
For more information about CloudWatch, see the Amazon CloudWatch Developer Guide.
8.
To set a default throttle limit for all of the methods associated with this API in API Gateway, in the
Stage Editor pane, on the Settings tab, in the Throttle Settings area, do the following, and then
choose Save Changes:
For Burst Limit, type the absolute maximum number of times API Gateway will allow this
method to be called per second. (The value of Burst Limit must be equal to or greater than the
value of Rate.) The default setting is 1000 request per second.
For Rate, type the number of times API Gateway will allow this method to be called per second
on average. (The value of Rate must be equal to or less than the value of Burst Limit.) The
default setting is 500 request per second.
Note
When creating a stage, if not supplied, API Gateway will enforce the default values of
1000 for Burst Limit and 500 for Rate in the stage settings.
In addition, API Gateway enforces overall account level throttling at the default values
of 1000 for Burst Limitand 500 for Rate. If your require a higher level of throttling on
your account, contact the AWS Support Center to request an increase.
API Gateway uses the token bucket algorithm, including average rate and burst size,
for both account and method throttling.
9.
To change the stage to use a different deployment, in the Stage Editor pane, on the Change
Deployment tab, choose the option button next to the deployment you want the stage to use, and
then choose Change Deployment.
178
Warning
Deleting a stage may cause part or all of the corresponding API to be unusable by API callers.
Deleting a stage cannot be undone.
2.
In the box that contains the name of the API for the stage, choose Stages.
3.
In the Stages pane, choose the stage you want to delete, and then choose Delete Stage.
4.
Account-Level Throttling
By default, API Gateway limits the steady-state request rates to 1000 requests per second (rps)
and allows bursts of up to 2000 rps across all APIs, stages, and methods within an AWS account. If
necessary, you can request an increase to your account-level limits. For more information, see API
Gateway Limits (p. 293).
You can view account-level throttling limits in the API Gateway console. The console displays the
default account-level settings before these settings are overridden by any customization. You can also
read the account-level throttling limits by using the API Gateway REST API (p. 292).
Topics
Amazon API Gateway Caching Overview (p. 180)
Enable Amazon API Gateway Caching (p. 180)
Override API Gateway Stage-Level Caching for Method Caching (p. 181)
Use Method or Integration Parameters as Cache Keys to Index Cached Responses (p. 182)
Flush the API Stage Cache in API Gateway (p. 183)
Invalidate an API Gateway Cache Entry (p. 183)
Note
Caching is charged by the hour and is not eligible for the AWS free tier.
2.
Navigate to the Stage Editor for the stage for which you want to enable caching.
3.
Choose Settings.
4.
5.
Note
Creating or deleting a cache takes about 4 minutes for API Gateway to complete. When
cache is created, the Cache status value changes from CREATE_IN_PROGRESS to
AVAILABLE. When cache deletion is completed, the Cache status value changes from
DELETE_IN_PROGRESS to an empty string.
When you enable caching within a stage's Cache Settings, you enable caching for all methods in that
stage.
180
If you would like to verify if caching is functioning as expected, you have two general options:
Inspect the CloudWatch metrics of CacheHitCount and CacheMissCount for your API and stage.
Put a timestamp in the response.
Note
You should not use the X-Cache header from the CloudFront response to determine if your
API is being served from your API Gateway cache instance.
181
In this request, type can take a value of admin or regular. If you include the type parameter as part
of the cache key, the responses from GET /users?type=admin will be cached separately from those
from GET /users?type=regular.
When a method or integration request takes more than one parameter, you can choose to include
some or all of the parameters to create the cache key. For example, you can include only the type
parameter in the cache key for the following request, made in the listed order within a TTL period:
182
host: example.com
...
The response from this request will be cached and will be used to serve the following request:
To include a method or integration request parameter as part of a cache key in the API Gateway
console, select Caching after you add the parameter.
183
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:InvalidateCache"
],
"Resource": [
"arn:aws:execute-api:region:account-id:api-id/stage-name/HTTPVERB/resource-path-specifier"
]
}
]
}
This policy allows the API Gateway execution service to invalidate cache for requests on the specified
resource (or resources). To specify a group of targeted resources, use a wildcard (*) character for
account-id, api-id, and other entries in the ARN value of Resource. For more information on how
to set permissions for the API Gateway execution service, see Set IAM Permissions (p. 141)
If you do not impose an InvalidateCache policy, any client can invalidate the API cache. If all or
most of the clients invalidate the API cache, there could be significant latency impact on your API.
When the policy is in place, caching is enabled, and authorization is required, you can control how
unauthorized requests are handled by choosing an option from Handle unauthorized requests in the
API Gateway console.
184
Fail the request with 403 status code: returns a 403 Unauthorized response.
To set this option using the API, use FAIL_WITH_403.
Ignore cache control header; Add a warning in response header: process the request and add a
warning header in the response.
To set this option using the API, use SUCCEED_WITH_RESPONSE_HEADER.
Ignore cache control header: process the request and do not add a warning header in the
response.
To set this option using the API, use SUCCEED_WITHOUT_RESPONSE_HEADER.
Use Cases
With deployment stages in API Gateway, you can manage multiple release stages for each API,
such as alpha, beta, and production. Using stage variables you can configure an API deployment
stage to interact with different back-end endpoints. For example, your API can pass a GET request
as an HTTP proxy to the back-end web host (for example, http://example.com). In this case, the
back-end web host is configured in a stage variable so that when developers call your production
endpoint, API Gateway calls example.com. When you call your beta endpoint, API Gateway uses the
value configured in the stage variable for the beta stage, and calls a different web host (for example,
beta.example.com). Similarly, stage variables can be used to specify a different AWS Lambda
function name for each stage in your API.
You can also use stage variables to pass configuration parameters to a Lambda function through
your mapping templates. For example, you may want to re-use the same Lambda function for multiple
stages in your API, but the function should read data from a different Amazon DynamoDB table
depending on which stage is being called. In the mapping templates that generate the request for the
Lambda function, you can use stage variables to pass the table name to Lambda.
Examples
To use a stage variable to customize the HTTP integration endpoint, you must first configure a stage
variable of a specified name, e.g., url, and then assign it a value, e.g., example.com. Next, from your
method configuration, set up an HTTP proxy integration, and instead of entering the endpoint's URL,
185
you can tell API Gateway to use the stage variable value, http://${stageVariables.url}. This
value tells API Gateway to substitute your stage variable ${} at runtime, depending on which stage
your API is running. You can reference stage variables in a similar way to specify a Lambda function
name, an AWS Service Proxy path, or an AWS role ARN in the credentials field.
When specifying a Lambda function name as a stage variable value, you must configure the
permissions on the Lambda function manually. You can use the AWS Command Line Interface to do
this.
aws lambda add-permission --function-name arn:aws:lambda:XXXXXX:yourlambda-function-name --source-arn arn:aws:execute-api:useast-1:YOUR_ACCOUNT_ID:api_id/*/HTTP_METHOD/resource --principal
apigateway.amazonaws.com --statement-id apigateway-access --action
lambda:InvokeFunction
The following example assigns API Gateway permission to invoke a Lambda function named
helloWorld hosted in the US West (Oregon) region of an AWS account on behalf of the API method.
arn arn:aws:execute-api:us-west-2:123123123123:bmmuvptwze/*/GET/hello
Prerequisites
1.
You must have an API available in API Gateway. Follow the instructions in Creating an API (p. 70).
2.
You must have deployed the API at least once. Follow the instructions in Deploying an
API (p. 173).
3.
You must have created the first stage for a deployed API. Follow the instructions in Create a
Stage (p. 175).
2.
Create an API, create a GET method on the API's root resource, if you have not already done so.
Set the HTTP Endpoint URL value as "http://${stageVariables.url}", and then choose
Save.
186
3.
Choose Deploy API. Choose New Stage and enter "beta" for Stage name. Choose Deploy.
4.
In the beta Stage Editor panel; choose the Stage Variables tab; and then choose Add Stage
Variable.
5.
Enter the "url" string in the Name field and the "httpbin.org/get" in the Value field. Choose
the checkmark icon to save the setting for the stage variable.
187
6.
Repeat the above step to add two more stage variables: version and function. Set their values
as "v-beta" and "HelloWorld", respectively.
Note
When setting a Lambda function as the value of a stage variable, use the function's
local name, possibly including its alias or version specification, as in HelloWorld,
HelloWorld:1 or HelloWorld:alpha. Do not use the function's ARN (for example,
arn:aws:lambda:us-east-1:123456789012:function:HelloWorld). The
API Gateway console assumes the stage variable value for a Lambda function as the
unqualified function name and will expand the given stage variable into an ARN.
7.
From the Stages navigation pane, choose Create. For Stage name, type prod. Select a recent
deployment from Deployment and then choose Create.
188
8.
As with the beta stage, set the same three stage variables (url, version, and function) to different
values ("petstore-demo-endpoint.execute-api.com/petstore/pets", "v-prod", and
"HelloEveryone"), respectively.
Prerequisites
You must create two stages with a url variable set to two different HTTP endpoints: a function
stage variable assigned to two different Lambda functions, and a version stage variable containing
stage-specific metadata. Follow the instructions in Set Stage Variables Using the Amazon API
Gateway Console (p. 186).
In the Stages navigation pane, choose beta. In beta Stage Editor, choose the Invoke URL link.
This starts the beta stage GET request on the root resource of the API.
189
Note
The Invoke URL link points to the root resource of the API in its beta stage. Navigating
to the URL by choosing the link calls the beta stage GET method on the root resource.
If methods are defined on child resources and not on the root resource itself, choosing
the Invoke URL link will return a {"message":"Missing Authentication Token"}
error response. In this case, you must append the name of a specific child resource to the
Invoke URL link.
2.
The response you get from the beta stage GET request is shown next. You can also verify the
result by using a browser to navigate to http://httpbin.org/get. This value was assigned to the
url variable in the beta stage. The two responses are identical.
3.
In the Stages navigation pane, choose the prod stage. From prod Stage Editor , choose the
Invoke URL link. This starts the prod stage GET request on the root resource of the API.
190
4.
The response you get from the prod stage GET request is shown next. You can verify the result by
using a browser to navigate to http://petstore-demo-endpoint-execute-api.com/petstore/pets.
This value was assigned to the url variable in the prod stage. The two responses are identical.
In the Resource navigation pane, choose the GET method. To add a query string parameter
to the method's URL, in Method Execution, choose Method Request . Type version for the
parameter name.
191
2.
In Method Execution choose Integration Request. Edit the Endpoint URL value to append ?
version=${stageVariables.version} to the previously defined URL value, which, in this
case, is also expressed with the url stage variable. Choose Deploy API to deploy these changes.
3.
In the Stages navigation pane, choose the beta stage. From beta Stage Editor, verify that the
current stage is in the most recent deployment, and then choose the Invoke URL link.
Note
We use the beta stage here because the HTTP endpoint, as specified by the url
variable, "http://httpbin.org/get", accepts query parameter expressions and returns them
as the args object in its response.
192
4.
The response is shown next. Notice that v-beta, assigned to the version stage variable, is
passed in the back end as the version argument.
In the Resources pane, create a /lambdasv1 child resource under the root directory, and then
create a GET method on the child resource. Set the Integration type to Lambda Function, and in
Lambda Function, type ${stageVariables.function} . Choose Save.
Tip
When prompted with Add Permision to Lambda Function, make a note of the AWS CLI
command before choosing OK. You must run the command on each Lambda function
193
that is or will be assigned to the function stage variable for each of the newly created
API methods. For example, if the $stageVariables.function value is HelloWorld
and you have not added permission to this function yet, you must run the following AWS
CLI command:
aws lambda add-permission --function-name arn:aws:lambda:useast-1:account-id:function:HelloWorld --source-arn arn:aws:executeapi:us-east-1:account-id:api-id/*/GET/lambdasv1 --principal
apigateway.amazonaws.com --statement-id statement-id-guid --action
lambda:InvokeFunction
2.
3.
In the Stages navigation pane, choose the beta stage. Verify that your most recent deployment
is in beta Stage Editor. Copy the Invoke URL link, paste it into the address bar of your browser,
and append /lambdasv1 to that URL. This calls the underlying Lambda function through the GET
method on the LambdaSv1 child resource of the API.
Note
Your HelloWorld Lambda function implements the following code.
1.
In the Resources pane, choose the /lambdasv1 child resource. Create a POST
method on the child resource, set the Integration type to Lambda Function, and type
${stageVariables.function} in Lambda Function. Choose Save.
Tip
This step is similar to the step we used to create the GET method. For more information,
see Call Lambda function through API with a stage variable (p. 193).
2.
From the /Method Execution pane, choose Integration Request. In the Integration Request
pane, expand Mapping Templates, and then choose Add mapping template to add a template
for the application/json content-type, as shown in the following.
Note
In a mapping template, a stage variable must be referenced within quotes (as
in "$stageVariables.version" or "${stageVariables.version}"),
whereas elsewhere it must be referenced without quotes (as in
${stageVariables.function}).
3.
4.
In the Stages navigation pane, choose beta. In beta Stage Editor , verify that the current stage
has the most recent deployment. Copy the Invoke URL link, paste it into the URL input field of
a REST API client, append /lambdasv1 to that URL, and then submit a POST request to the
underlying Lambda function.
Note
You will get the following response.
"Hello, world! (v-beta)"
To summarize, we have demonstrated how to use API Gateway stage variables to target different
HTTP and Lambda back ends for different stages of API deployment. In addition, we also showed
how to use the stage variables to pass stage-specific configuration data into HTTP and Lambda back
ends. Together, these procedures demonstrate the versatility of the API Gateway stage variables in
managing API development.
195
Mapping Templates
A stage variable can be used anywhere in a mapping template, as shown in the following examples.
{ "name" : "$stageVariables.<variable_name>"}
{ "name" : "${stageVariables.<variable_name>}"}
196
Prerequisites
You must have deployed the API at least once in API Gateway. Follow the instructions in
Deploying an API (p. 173).
2.
In the box that contains the name of the API for the stage, choose Stages.
3.
4.
5.
6.
If you chose iOS, in the Prefix box, type the unique prefix for the generated classes.
(For example, typing CLI will result in classes named CLIRequestModel.h and
CLIRequestModel.m.)
7.
Choose Generate SDK, and then follow the on-screen directions to download the API Gatewaygenerated SDK.
197
8.
Extract the contents of the API Gateway-generated .zip file you downloaded earlier.
2.
3.
4.
5.
Run the command mvn install to install the compiled artifact files to your local Maven repository.
This will create a target folder containing compiled SDK library.
6.
Copy the SDK file (the name of which is derived from the Artifact Id and Artifact Version you
specified when generating the SDK, e.g., aws-apigateway-api-sdk-1.0.0.jar) from the
target folder, along with all of the other libraries from the target/lib folder, into your project's
lib folder.
If you use Andriod Studio, create a libs folder under your client app module and copy the required
JAR file into this folder. Verify that the dependencies section in the module's gradle file contains
the following
compile fileTree(include: ['*.jar'], dir: 'libs')
compile fileTree(include: ['*.jar'], dir: 'app/libs')
Use the ApiClientFactory class to initialize the API Gateway-generated SDK. For example:
ApiClientFactory factory = new ApiClientFactory();
// Create an instance of your SDK.
final MyApiClient client = factory.build(MyApiClient.class);
// Invoke a method (e.g., 'parentPath1Get(param1,body)') exposed by your
SDK.
// Here the method's return type is OriginalModel.
OriginalModel output = client.parentPath1Get(param1,body);
// You also have access to your API's models.
OriginalModel myModel = new OriginalModel();
myModel.setStreetAddress(streetAddress);
myModel.setCity(city);
myModel.setState(state);
myModel.setStreetNumber(streetNumber);
198
8.
To use a Amazon Cognito credentials provider to authorize calls to your API, use the
ApiClientFactory class to pass a set of AWS credentials by using the API Gateway-generated
SDK. For example:
9.
To set an API key by using the API Gateway-generated SDK, use code similar to the following:
Extract the contents of the API Gateway-generated .zip file you downloaded earlier.
2.
Import the AWS Mobile SDK for iOS into your project by using CocoaPods or Frameworks.
To import the AWS Mobile SDK for iOS into your project by using CocoaPods, do the following:
1.
2.
Copy the Podfile file from the extracted .zip file into the same directory as your Xcode
project file. If your Xcode project file already contains a file named Podfile, you can simply
add the following line of code to it:
pod 'AWSAPIGateway', '~> 2.2.1'
3.
4.
5.
Copy all of the .h and .m files from the extracted .zip file's generated-src directory into
your Xcode project.
199
To import the AWS Mobile SDK for iOS into your project by using Frameworks, do the following:
3.
1.
Download the AWS Mobile SDK for iOS, version 2.2.1 or later.
2.
With your project already open in Xcode, press and hold the Ctrl key while choosing
Frameworks, and then choose Add files to "<project name>"....
3.
4.
Open a target for your project, choose Build Phases, expand Link Binary With Libraries,
choose the + button, and then add the following: libsqlite3.dylib, libz.dylib, and
SystemConfiguration.framework.
Import the .h file from the API Gateway-generated SDK. For example:
#import "<generated header file name>"
4.
5.
Use the API Gateway-generated SDK to call your API's method. For example:
[[client parentPath1ChildPath1Get:@"test" body:APIGOriginalModel]
continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(@"Error: %@", task.error);
return nil;
}
if (task.result) {
APIGOriginalModel * output = task.result;
//Do something with the output.
}
return nil;
}
];
6.
To use a Amazon Cognito credentials provider to authorize calls to your API, create an
AWSCognitoCredentialsProvider object as the default provider for the API Gatewaygenerated SDK. For example:
7.
To send an API key in your requests, set the apiKey property of the API Gateway-generated
SDK. For example:
200
Extract the contents of the API Gateway-generated .zip file you downloaded earlier.
2.
Enable cross-origin resource sharing (CORS) for all of the methods the API Gateway-generated
SDK will call. For instructions, see Enable CORS for a Resource (p. 151).
3.
4.
src="lib/axios/dist/axios.standalone.js"></
src="lib/CryptoJS/rollups/hmacsrc="lib/CryptoJS/rollups/sha256.js"></
src="lib/CryptoJS/components/hmac.js"></
src="lib/CryptoJS/components/encsrc="lib/url-template/url-template.js"></
src="lib/apiGatewayCore/sigV4Client.js"></
src="lib/apiGatewayCore/
src="lib/apiGatewayCore/
src="lib/apiGatewayCore/utils.js"></script>
src="apigClient.js"></script>
In your code, initialize the API Gateway-generated SDK by using code similar to the following:
var apigClient = apigClientFactory.newClient();
5.
Call the API in API Gateway by using code similar to the following. Each call returns a promise
with a success and failure callbacks:
var params = {
// This is where any modeled request parameters should be added.
// The key is the parameter name, as it is defined in the API in API
Gateway.
param0: '',
param1: ''
};
var body = {
// This is where you define the body of the request,
};
201
var additionalParams = {
// If there are any unmodeled query parameters or headers that must be
//
sent with the request, add them here.
headers: {
param0: '',
param1: ''
},
queryParams: {
param0: '',
param1: ''
}
};
apigClient.methodName(params, body, additionalParams)
.then(function(result){
// Add success callback code here.
}).catch( function(result){
// Add error callback code here.
});
6.
To initialize the API Gateway-generated SDK with AWS credentials, use code similar to the
following. If you use AWS credentials, all requests to the API will be signed. This means you must
set the appropriate CORS Accept headers for each request:
var apigClient = apigClientFactory.newClient({
accessKey: 'ACCESS_KEY',
secretKey: 'SECRET_KEY',
});
7.
To use an API key with the API Gateway-generated SDK, you can pass the API key as a
parameter to the Factory object by using code similar to the following. If you use an API key, it is
specified as part of the x-api-key header and all requests to the API will be signed. This means
you must set the appropriate CORS Accept headers for each request:
var apigClient = apigClientFactory.newClient({
apiKey: 'API_KEY'
});
202
size of a certificate key length, see Using Alternate Domain Names and HTTPS in the Amazon
CloudFront Developer Guide.
To enable a custom domain name, you, as the API owner, must provide a server-side SSL certificate to
verify the custom domain name targeted by the client requests. You do this when setting up the domain
name initially and then when renewing an expiring certificate subsequently. In addition, you must have
registered the custom domain name with a domain name registrar. After setting up a custom domain
name in API Gateway, you must create or update your domain name service (DNS) provider's resource
record to map the custom domain name to its CloudFront distribution domain name. For the SSL
certificate, you must also have obtained from a certificate authority the PEM-formatted SSL certificate
body, its private key, and the certificate chain for the custom domain name. This section describes how
to configure a domain name for an API, to set up the certificate for a custom domain name, to map a
base path to an API, and to upload a new certificate to replace an expiring one. We will also provide
general guidance, by way of examples, on how to obtain the server-side certificate and create a DNS
alias record.
Topics
Prerequisites (p. 203)
Set Up a Custom Domain Name for an API Gateway API (p. 204)
Specify API Mappings for a Custom Domain Name (p. 206)
Base Path Examples of API Mappings for a Custom Domain Name (p. 207)
Upload and Renew an Expiring Certificate (p. 207)
Call Your API with Custom Domain Names (p. 208)
Prerequisites
The following steps describe how to prepare to use custom domain names in API Gateway.
Register your custom domain name. See the Accredited Registrar Directory at the ICANN website.
2.
Get a PEM-encoded SSL certificate for your custom domain name from a certificate authority. For
a partial list, see Third-Party Certificate Authorities at the DMOZ website.
Here are the general steps to obtain an SSL certificate from your chosen certificate authority:
a.
Generate a private key for the certificate and save output to a file, using the OpenSSL toolkit
at the OpenSSL website:
openssl genrsa -out private-key-file 2048
Note
Amazon API Gateway leverages Amazon CloudFront to support certificates for
custom domain names. As such, the requirements and constraints of a custom
domain name SSL certificate are dictated by CloudFront. For example, the maximum
size of the public key is 2048 and the private key size can be 1024, 2048 and 4096.
For more information, see Secure access to your objects and Create signed URLs
and signed cookies.
b.
Generate a certificate signing request (CSR) with the previously generated private key, using
OpenSSL:
openssl req -new -sha256 -key private-key-file -out CSR-file
c.
Submit the CSR to the certificate authority and save the resulting certificate.
203
d.
Note
If you obtain the private key in another way and the key is encrypted, you can use the
following command to decrypt the key before submitting it to API Gateway for setting up a
custom domain name.
openssl pkcs8 -topk8 -inform pem -in MyEncryptedKey.pem -outform
pem -nocrypt -out MyDecryptedKey.pem
2.
3.
4.
For Domain name, type your domain name (for example, api.example.com).
b.
For Certificate name, type a name for future reference (for example, my-examplecertificate).
c.
For Certificate body, type or paste the body of the PEM-formatted server certificate from
your certificate authority. The following shows an abbreviated example of such a certificate.
-----BEGIN CERTIFICATE----EXAMPLECA+KgAwIBAgIQJ1XxJ8Pl++gOfQtj0IBoqDANBgkqhkiG9w0BAQUFADBB
...
az8Cg1aicxLBQ7EaWIhhgEXAMPLE
-----END CERTIFICATE-----
d.
For Certificate private key, type or paste your PEM-formatted certificate's private key. The
following shows an abbreviated example of such a key.
-----BEGIN RSA PRIVATE KEY----EXAMPLEBAAKCAQEA2Qb3LDHD7StY7Wj6U2/opV6Xu37qUCCkeDWhwpZMYJ9/nETO
...
1qGvJ3u04vdnzaYN5WoyN5LFckrlA71+CszD1CGSqbVDWEXAMPLE
-----END RSA PRIVATE KEY-----
e.
For Certificate chain, type or paste the PEM-formatted intermediate certificates and,
optionally, the root certificate, one after the other without any blank lines. If you include the
root certificate, your certificate chain must start with intermediate certificates and end with
the root certificate. Use the intermediate certificates provided by your certificate authority. Do
not include any intermediaries that are not in the chain of trust path. The following shows an
abbreviated example.
-----BEGIN CERTIFICATE----EXAMPLECA4ugAwIBAgIQWrYdrB5NogYUx1U9Pamy3DANBgkqhkiG9w0BAQUFADCB
204
...
8/ifBlIK3se2e4/hEfcEejX/arxbx1BJCHBvlEPNnsdw8EXAMPLE
-----END CERTIFICATE-----
5.
Choose Save.
6.
While the new custom domain name is being created, the console displays the following
information to have an alias resource record created in your DNS provider to map your
custom domain name (api.example.com) to the API's CloudFront distribution domain name
(distribution-id.cloudfront.net).
Make note of the CloudFront distribution's domain name shown in the output. You will need it to
set the custom domain's CNAME or alias record in your DNS.
7.
In this step, we will use Amazon Route 53 as an example DNS provider to show how to set up
the alias record to map the custom domain to its CloudFront distribution. The instructions can be
adapted to other DNS providers.
a.
b.
c.
d.
e.
Choose Yes for Alias, type the CloudFront domain name (e.g.,
d3boq9ikothtgw.cloudfront.net) in Alias Target, and then choose Create.
205
For most DNS providers, including Amazon Route 53, your custom domain name is added to
the hosted zone as a CNAME resource record set. The CNAME record name specifies the
custom domain name you typed earlier for Domain Name (for example, api.example.com).
The CNAME record value specifies the domain name for the CloudFront distribution. However,
use of a CNAME record will not work if your custom domain is a zone apex (i.e., example.com
instead of api.example.com). A zone apex is also commonly known as the root domain of your
organization.
With Amazon Route 53 you can also create an alias resource record set for your custom domain
name and specify the CloudFront distribution as the alias target. This means that Amazon
Route 53 can route your custom domain name even if it is a zone apex. For more information, see
Choosing Between Alias and Non-Alias Resource Record Sets in the Amazon Route 53 Developer
Guide.
For each URL variation you want to enable, choose Create API mapping.
206
2.
(Optional) For Base path, type the base path name that API callers must provide as part of the
URL. This value must be unique for all of the mappings across a single API. Leave this blank if you
do not want callers to specify a base path name after the domain name.
3.
For API, choose the name of an available API from the selected region in your AWS account.
4.
(Optional) For Stage, choose the name of the API's stage you want to use for this mapping. Leave
this blank if you want callers to explicitly specify the stage name after any base path name.
5.
Choose Save.
Note
To delete a mapping after you create it, next to the mapping that you want to delete, choose
Remove.
Choose Custom Domain Names from the API Gateway console main navigation pane.
2.
3.
Choose Upload
Note
The upload feature will not be available when the certificate is being initialized or rotated
for the selected custom domain name. However, upload for a different domain name is
still available because the upload feature is independent for each custom domain name.
4.
207
Type a name for the new certificate in Certificate name. The name should be different from the
name of the expiring certificate.
Type or paste the PEM-formatted new certificate body in Certificate body.
Type or paste the PEM-formatted new certificate key in Certificate private key
Type or paste the PEM-formatted new certificate chain in Certificate chain.
Then, choose Save.
5.
Choose Rotate to start replacing the old certificate by the new certificate.
Note
The certificate rotation takes up to 40 minutes to finish. The custom domain name is
available during the rotation.
208
Calling a deployed API involves submitting requests to the execute-api component of API Gateway.
The request URL is the Invoke URL generated by API Gateway when the API is successfully
deployed. You can obtain this invocation URL from the API Gateway console or you can construct it
yourself according to the following format:
https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/
If your API permits anonymous access, you can use any web browser to invoke any GET-method calls
by pasting the Invoke URL to the browser's address bar. For other methods or any authenticationrequired calls, the invocation will be more involved because you must specify a payload or sign the
requests. You can handle these in a script behind an HTML page or in a client app using one of the
AWS SDKs.
For testing, you can use the API Gateway console to call an API using the API Gateway's TestInvoke
feature, which bypasses the Invoke URL and allows API testing before the API is deployed.
Alternatively, you can use the Postman Chrome extension to test a successfully deployed API, without
writing a script or a client.
Topics
Prerequisites (p. 209)
Obtain an API's Invoke URL in the API Gateway Console (p. 210)
Test a Method Using the API Gateway Console (p. 210)
Use Postman to Test an API (p. 211)
Prerequisites
You must have already deployed the API in API Gateway. Follow the instructions in Deploying an
API (p. 173).
209
2.
In the box that contains the name of the API you want to call, choose Stages.
3.
4.
The URL displayed next to Invoke URL should look something like this, where my-api-id is the
identifier API Gateway assigns to your API, region-id is the AWS region identifier (for example,
us-east-1 ) where you deployed your API, and stage-name is the name of the stage for the API
you want to call:
https://my-api-id.execute-api.region-id.amazonaws.com/stage-name/
{resourcePath}
Depending on the method type you want to call and the tool you want to use, copy this URL to your
clipboard, and then paste and modify it to call the API from a web browser, a web debugging proxy tool
or the cURL command-line tool, or from your own API.
If you are not familiar with which method to call or the format you must use to call it, browse the list of
available methods by following the instructions in View a Methods List (p. 171).
To call the method directly from the API Gateway console, see Test a Method Using the
Console (p. 210).
For more options, contact the API owner.
Prerequisites
You must specify the settings for the methods you want to test. Follow the instructions in Set up
Method and Integration (p. 71).
210
2.
In the box that contains the name of the API for the method, choose Resources.
3.
4.
In the Method Execution pane, in the Client box, choose TEST. Type values in any of the
displayed boxes (such as Query Strings, Headers, and Request Body).
For additional options you may need to specify, contact the API owner.
5.
Tip
Depending on the mapping, the HTTP status code, response body, and response
headers may be different from those sent from the Lambda function, HTTP proxy, or
AWS service proxy.
Logs are the simulated Amazon CloudWatch Logs entries that would have been written if this
method were called outside of the API Gateway console.
Note
Although the CloudWatch Logs entries are simulated, the results of the method call are
real.
Launch Postman.
Enter the endpoint URL of a request in the address bar and choose the appropriate HTTP method
from the drop-down list to the left of the address bar.
If required, choose the Authorization tab. Choose AWS Signature for the authorization Type.
Enter your AWS IAM user's access key ID in the AccessKey input field. Enter your IAM user
secret key in SecretKey. Specify an appropriate AWS region that matches the region specified in
the invocation URL. Enter execute-api in Service Name.
4.
Choose the Headers tab. Optionally, delete any existing headers. This can clear any stale settings
that may cause errors. Add any required custom headers. For example, if API keys are enabled,
you can set the x-api-key:{api_key} name/value pair here.
5.
For an example of using Postman, see Call an API with Custom authorization (p. 162).
211
Note
CloudTrail logs API Gateway REST API calls an API developer or owner made against the
apigateway component, whereas CloudWatch logs API calls an API customer or client made
against the execute-api component of API Gateway.
212
213
sourceIPAddress: "203.0.113.11",
userAgent: "example-user-agent-string",
requestParameters: {
restApiId: "3rbEXAMPLE",
resourceId: "5tfEXAMPLE",
template: false
},
responseElements: null,
requestID: "6d9c4bfc-148a-11e5-81b6-7577cEXAMPLE",
eventID: "4d293154-a15b-4c33-9e0a-ff5eeEXAMPLE",
readOnly: true,
eventType: "AwsApiCall",
recipientAccountId: "123456789012"
},
... additional entries ...
]
}
214
Description
4XXError
5XXError
CacheHitCount
CacheMissCount
Count
IntegrationLatency
Latency
Description
ApiName
215
Dimension
Description
ApiName, Stage
Prerequisites
1.
You must have an API created in API Gateway. Follow the instructions in Creating an API (p. 70).
2.
You must have the API deployed at least once. Follow the instructions in Deploying an
API (p. 173).
3.
To get CloudWatch metrics for individual methods, you must have CloudWatch Logs enabled
for those methods in a given stage. The process is prescribed in Set Up a Stage (p. 176). Your
account will be charged for accessing method-level logs, but not for accessing API- or stage-level
logs.
4.
5.
To display a summary of API activity over time, for Stage, choose the desired stage.
Use From and To to enter the date range.
6.
Refresh, if needed, and view individual metrics displayed in separate graphs titled API
Calls, Integration Latency, Latency, 4xx Error and 5xx Error. The CacheHitCount and
CacheMissCount graphs will be displayed only if API caching has been enabled.
Tip
To examine method-level CloudWatch metrics, make sure that you have enabled
CloudWatch Logs on a method level. For more information about how to set up
method-level logging, see Set Up an API Deployment Stage with the API Gateway
Console (p. 176).
216
1.
2.
If necessary, change the region. From the navigation bar, select the region where your AWS
resources reside. For more information, see Regions and Endpoints.
3.
4.
In the CloudWatch Metrics by Category pane, under the metrics category for API Gateway,
select a metrics category, and then in the upper pane, scroll down to view the full list of metrics.
217
218
After you create, test, and deploy your APIs, you can extend them as product offerings for your
customers. You can provide usage plans to allow specified customers to access selected APIs at
agreed-upon request rates and quotas that can meet their business requirements and budgetary
constraints.
Note
Throttling and quota limits apply to requests for individual API keys that are aggregated across
all API stages within a usage plan.
Create one or more APIs, configure the methods to require an API key, and deploy the APIs in
stages.
2.
Generate API keys and distribute the keys to app developers (your customers) using your APIs.
219
3.
Create the usage plan with the desired throttle and quota limits.
4.
Associate selected API stages and API keys to the usage plan.
Callers of the API must supply an assigned API key in the x-api-key header in requests to the API.
Note
To enforce authorization of the API key in requests to the API, individual API methods must be
configured to require an API key (p. 155). Setting this configuration ensures the incoming API
key will be authorized according to the usage plan configuration.
Topics
Configure Usage Plans Using the API Gateway Console (p. 220)
Configure Usage Plans Using the API Gateway REST API (p. 225)
API Gateway API Key File Format (p. 228)
Sign in to the AWS Management Console and open the API Gateway console at https://
console.aws.amazon.com/apigateway/.
2.
3.
4.
5.
Under the Authorization Settings section, choose true for API Key Required.
220
6.
Sign in to the AWS Management Console and open the API Gateway console at https://
console.aws.amazon.com/apigateway/.
2.
3.
4.
5.
a.
Type an API key name (e.g., MyFirstKey) in the Name input field.
b.
Choose Auto Generate to have API Gateway to generate the key value or choose Custom to
enter the key manually.
c.
Choose Save.
221
2.
3.
To load a comma-separated key file, choose Select CSV File. You can also type the keys
manually. For information about the file format, see API Gateway API Key File Format (p. 228).
4.
Choose Fail on warnings to stop import when there is an error, or choose Ignore warnings to
continue to import valid key entries when there is an error.
5.
In the Amazon API Gateway main navigation pane, choose Usage Plans, and then choose
Create.
2.
b.
c.
Select Enable throttling and set Rate (e.g., 100) and Burst (e.g., 200).
d.
Choose Enable quota and set its limit (e.g., 5000) for a selected time interval (e.g., Month).
e.
Choose Save.
222
3.
4.
To add a stage to the plan, do the following in the Associated API Stages pane:
a.
b.
c.
d.
e.
Choose Next.
To add a key to the plan, do the following in the Usage Plan API Keys pane:
a.
b.
For Name, type a name for the key you want to add (e.g., MyFirstKey).
c.
d.
If desired, repeat the preceding steps to add other existing API keys to this usage plan.
223
Note
To add a new API key to the usage plan, choose Create API Key and add to Usage
Plan and follow the instructions.
5.
6.
If you want to add more API stages to the usage plan, choose Add API Stage to repeat the
preceding steps.
2.
Choose a usage plan from the list of the usage plans in the secondary navigation pane in the
middle.
3.
4.
Choose an API key. Then choose Usage to view Subscriber's Traffic from the plan you are
monitoring.
5.
Optionally, choose Export, choose a From date and a To date, choose JSON or CSV for the
exported data format, and then choose Export.
The following example shows an exported file.
{
"thisPeriod": {
"px1KW6...qBazOJH": [
[
224
0,
5000
],
[
0,
5000
],
[
0,
10
]
]
},
"startDate": "2016-08-01",
"endDate": "2016-08-03"
}
The usage data in the example shows the daily usage data for an API client, as identified by the
API key (px1KW6...qBazOJH), between August 1, 2016, and August 3, 2016. Each daily usage
data shows used and remaining quotas. In this example, the subscriber has not yet used any
allotted quotas and the API owner or administrator has reduced the remaining quota from 5000 to
10 on the third day.
2.
On the usage plan page, choose Extension from the usage plan window.
3.
4.
Choose Save.
225
For more information about migrating API stages associated with API keys see Migrate to Default
Usage Plans in the API Gateway Console (p. 222).
2.
Call usageplan:create to create a usage plan, specifying in the payload the name and description
of the plan, associated API stages, rate limits, and quotas.
Make note of the resultant usage plan identifier. You will need it in the next step.
Do one of the following:
a.
b.
Call usageplankey:create to add an API key to the usage plan, specifying keyId and
keyType in the payload.
To add more API keys to the usage plan, repeat the above call, one API key at a time.
Call apikey:import to add one or more API keys directly to the specified usage plan. The
request payload should contain API key values, the associated usage plan identifier, the
Boolean flags to indicate the keys are enabled for the usage plan, and, possibly, the API key
names and descriptions.
The following example of the apikey:import request will add three API keys (as identified
by key, name, and description) to one usage plan (as identified by usageplanIds):
POST /apikeys?mode=import&format=csv&failonwarnings=fase HTTP/1.1
Host: apigateway.us-east-1.amazonaws.com
Content-Type: text/csv
Authorization: ...
226
usageplanIds
importedKey_1, firstone,
tRuE,
As a result, three UsagePlanKey resources will be created and added to the UsagePlan.
You can also add API keys to more than one usage plan this way. To do this, change each
usageplanIds column value to a comma-separated string that contains the selected
usage plan identifiers and is enclosed within a pair of quotes ("n371pt,m282qs" or
'n371pt,m282qs').
Call usageplan:by-id to get a usage plan of a given plan Id. To see the available usage plans, call
apigateway:usage-plans.
2.
Call usageplan:update to add a new API stage to the plan, to replace an existing API stage in the
plan, to remove an API stage from the plan, or to modify the rate limits or quotas.
3.
4.
Make a GET request on the Pets resource (/pets), with the ?type=...&page=... query
parameters, of the API (e.g., xbvxlpijch) in a usage plan:
GET /testStage/pets?type=dog&page=1 HTTP/1.1
x-api-key: Hiorr45VR...c4GJc
Content-Type: application/x-www-form-urlencoded
Host: xbvxlpijch.execute-api.ap-southeast-1.amazonaws.com
X-Amz-Date: 20160803T001845Z
Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160803/apsoutheast-1/execute-api/aws4_request, SignedHeaders=content-type;host;xamz-date;x-api-key, Signature={sigv4_hash}
Note
You must submit this request to the execute-api component of API Gateway and
provide the required API key (e.g., Hiorr45VR...c4GJc) in the required x-api-key
header.
The successful response returns a 200 OK status code and a payload containing the requested
results from the back end. If you forget to set the x-api-key header or set it with an incorrect key,
227
you will get a 403 Forbidden response. On the other hand, if you did not configure the method
to require an API key, you will likely to get a 200 OK response whether you set the x-api-key
header correctly or not and the throttle and quota limits of the usage plan are bypassed.
When a key is associated with more than one usage plan, the UsagePlanIds value is a commaseparated string of the usage plan Ids enclosed with a pair of double or single quotes, as shown in the
following example:
Enabled,Name,key,UsageplanIds
true,MyFirstApiKey,apikey1234abcdefghij0123456789,"c7y23b,glvrsr"
Unrecognized columns are permitted, but will be ignored. The default value is an empty string or a
true Boolean value.
The same API key can be imported multiple times with the most recent version overwriting the previous
one. Two API keys are identical if they have the same key value.
228
The following tutorials provide hands-on exercises to help you learn about API Gateway.
Topics
Create an API Gateway API as an AWS Lambda Proxy (p. 229)
Create an API as an Amazon S3 Proxy (p. 245)
Create an API Gateway API as an Amazon Kinesis Proxy (p. 263)
229
POST /2015-03-31/functions/FunctionArn/invocations?Qualifier=Qualifier
HTTP/1.1
X-Amz-Invocation-Type: Event
...
Authorization: ...
Content-Type: application/json
Content-Length: PayloadSize
Payload
In this example, FunctionArn is the ARN of the Lambda function to be invoked. The
Authorization header is required by secure invocation of Lambda functions over HTTPS. For more
information, see the Invoke action in the AWS Lambda Developer Guide.
To illustrate how to create and configure an API as an AWS service proxy for Lambda, we will create
a Lambda function (Calc) that performs addition (+), subtraction (-), multiplication (*), and division (/).
When a client submits a method request to perform any of these operations, API Gateway will post the
corresponding integration request to call the specified Lambda function, passing the required input (two
operands and one operator) as a JSON payload. A synchronous call will return the result, if any, as the
JSON payload. An asynchronous call will return no data.
The API can expose a GET or POST method on the /calc resource to invoke the Lambda function.
With the GET method, a client supplies the input to the back-end Lambda function through three
query string parameters (operand1, operand2, and operator). These are mapped to the JSON
payload of the integration request. With the POST method, a client provides the input to the Lambda
function as a JSON payload of the method request, which is then passed through to the integration
request. Alternatively, the API can expose a GET method on the /calc/{operand1}/{operand2}/
{operator} resource. With this method, the client specifies the Lambda function input as the values
of the path parameters. Parameter mappings and mapping templates are used to translate the method
request data into the Lambda function input and to translate the output from the integration responses
to the method response.
This section provides more detailed discussions for the following tasks:
Create the Calc Lambda function to implement the arithmetic operations, accepting and returning
JSON-formatted input and output.
Expose GET on the /calc resource to invoke the Lambda function, supplying the input as query
strings.
Expose POST on the /calc resource to invoke the Lambda function, supplying the input in the
payload.
Expose GET on the /calc/{operand1}/{operand2}/{operator} resource to invoke the
Lambda function, specifying the input in the path parameters.
You can import the sample API as a Lambda proxy from the Swagger Definitions of a Sample API as
Lambda Proxy (p. 242). To do so, copy the Swagger definition, paste it into a file, and use the API
Gateway Swagger Importer. For more information, see Getting Started with the API Gateway Swagger
Importer.
To use the API Gateway console to create the API, you must first sign up for an AWS account.
If you do not have an AWS account, use the following procedure to create one.
230
2.
To allow the API to invoke Lambda functions, you must have an IAM role that has appropriate IAM
policies attached to it. The next section describes how to verify and to create, if necessary, the required
IAM role and policies.
Topics
Set Up an IAM Role and Policy for an API to Invoke Lambda Functions (p. 231)
Create a Lambda Function in the Back End (p. 232)
Create API Resources for the Lambda Function (p. 233)
Create a GET Method with Query Strings to Call the Lambda Function (p. 233)
Create a POST Method with a JSON Payload to Call the Lambda Function (p. 236)
Create a GET Method with Path Parameters to Call the Lambda Function (p. 238)
A Sample API as a Lambda Proxy in Swagger with API Gateway Extensions (p. 242)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "*"
}
]
}
If you do not enact this policy, the API caller will receive a 500 Internal Server Error response. The
response contains the "Invalid permissions on Lambda function" error message. For a complete list of
error messages returned by Lambda, see the Invoke topic.
An API Gateway assumable role is an IAM role with the following trusted relationship:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
231
}
]
}
This function requires two operands (a and b) and an operator (op) from the event input parameter.
The input is a JSON object of the following format:
{
"a": "Number" | "String",
"b": "Number" | "String",
"op": "String"
}
This function returns the calculated result (c) and the input. For an invalid input, the function returns
either the null value or the "Invalid op" string as the result. The output is of the following JSON format:
232
"a": "Number",
"b": "Number",
"op": "String",
"c": "Number" | "String"
}
You should test the function in the Lambda console before integrating it with the API, which is created
next.
In the API Gateway console, create an API named LambdaGate. You can create child resources
to represent different Lambda functions; in the following, you will create a single child resource of
the API root.
2.
For the simple calculator function you created, create the /calc resource off the API's root. You
will expose the GET and POST methods on this resource for the client to invoke the back-end
Lambda function, supplying the required input as query string parameters (to be declared as ?
operand1=...&operand2=...&operator=...) in the GET request and as a JSON payload in
the POST request, respectively.
You will also create the /calc/{operand1}/{operand2}/{operator} to expose the GET method
to invoke the Lambda function and to supply the required input as the three path parameters
(operand1, operand2, and operator).
We will show how to apply API Gateway request and response data mapping to normalize the
input to the back end Lambda function.
To set up the GET method with query strings to invoke the Lambda function
1.
Choose Create Method in the API Gateway console to create a GET method for the API's /calc
resource.
In the method's Set up pane, configure the method with the following settings.
233
You must use the POST method for the integration request when calling a Lambda function,
although you can use any other HTTP verbs for the method request.
The Path override value must the URL path of the Lambda Invoke action. The path is of the
following format:
/2015-03-31/functions/FunctionName/invocations?Qualifier=version
where FunctionName is the ARN of the Lambda function to be invoked. The optional Qualifier
query string can be used to select a version of the function. If it not specified, the $LATEST version
will be used.
You can also add the X-Amz-Invocation-Type: Event | RequestReponse | DryRun
header to have the action invoked asynchronously, as request and response, or as a test run,
respectively. If the header is not specified, the action will be invoked as request and response. For
the example shown here, this header has the default value.
We will come back to setting up Mapping Templates after setting up the query string parameters
to hold the input data for the Lambda function.
2.
In Method Request for the GET method on /calc, expand the URL Query String Parameters
section. Choose Add query string to add the operand1, operand2, and operator query string
parameters.
234
3.
{
"a": "$input.params('operand1')",
"b": "$input.params('operand2')",
"op": "$input.params('operator')"
}
235
This template maps the three query string parameters declared in Method Request into
designated property values of the JSON object as the input to the back-end Lambda function. The
transformed JSON object will be included as the integration request payload.
4.
You can now choose Test to verify that the GET method on the /calc resource has been properly
set up to invoke the Lambda function.
To set up the POST method with a JSON payload to invoke a Lambda function
1.
Choose Create Method in the API Gateway console to create a POST method for the
LambdaGate API's /calc resource.
In the method's Set Up panel, configure the POST method with the following settings.
236
Using a POST request with a JSON payload is the simplest way to invoke a Lambda function,
because no mappings are needed.
2.
You can now choose Test to verify the POST method works as expected. The following input:
{
"a": 1,
"b": 2,
"op": "+"
}
{
"a": 1,
"b": 2,
"op": "+",
"c": 3
}
If you would like to implement POST as an asynchronous call, you can add an
InvocationType:Event header in the method request and map it to the X-AmzInvocation-Type header in the integration request, using the header mapping expression
of method.request.header.InvocationType. You must inform the clients to include the
InvocationType:Event header in the method request. Alternatively, you can set the X-Amz-
237
To set up the GET method with URL path parameters to invoke the Lambda function
1.
Choose Create Method in the API Gateway console to create a GET method for the API's /calc/
{operand1}/{operand2}/{operator} resource.
In the method's Set up pane, configure this GET method with the following settings.
Next, we will set up Mapping Templates to translate the URL path parameters into the integration
request JSON payload as the input to the Lambda function.
2.
238
3.
{
"a": "$input.params('operand1')",
239
This template maps the three URL path parameters, declared when the /calc/{operand1}/
{operand2}/{operator} resource was created, into designated property values of the JSON
object. Because URL paths must be URL-encoded, the division operator must be specified as %2F
instead of /. This template maps these translations as well. The transformed JSON object will be
included as the integration request payload.
4.
As another exercise, we demonstrate how to translate the JSON returned from the Lambda
function to show the output as a plain text string to the caller. This involves resetting the method
request's Content-Type header to "text/plain" and providing a mapping template to translate the
JSON output into a plain string.
First, make sure that Content-Type header is included in the Response Headers for 200 section
in Method Response.
5.
In Integration Response, expand the 200 method response entry. Expand the Header Mappings
section. In Mapping value for Content-Type, type 'text/plain'. This header mapping
expression overrides the Content-Type header with a literal string, which must be enclosed within
a pair of single quotes.
240
Next, expand the Mapping Templates section, highlight the application/json entry under the
Content-Type header (of integration response), open the Mapping template editor, enter and
save the following mapping script:
$input.path('$.a') $input.path('$.op') $input.path('$.b') =
$input.path('$.c')
6.
Note
As part of a URL, the division operator (/) is URL-encoded (%2F).
7.
After testing the API using the Test Invoke in the API Gateway console, you must deploy the API
to make it public available. If you update the API, such as adding, modifying or deleting a resource
or method, updating any data mapping, you must redeploy the API to make the new features or
updates available.
241
242
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.operator":
"integration.response.body.op",
"method.response.header.operand_2":
"integration.response.body.b",
"method.response.header.operand_1":
"integration.response.body.a"
},
"responseTemplates": {
"application/json": "#set($res= $input.path('$'))\n{\n
\"result\": \"$res.a, $res.b, $res.op => $res.c\"\n}"
}
}
},
"requestTemplates": {
"application/json": "{\n
\"a\":
\"$input.params('operand1')\",\n
\"b\": \"$input.params('operand2')\",
\n
\"op\": \"$input.params('operator')\"
\n}"
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path//2015-03-31/
functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"httpMethod": "POST",
"type": "aws"
}
},
"post": {
"produces": [
"application/json"
],
"parameters": [],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200",
"responseTemplates": {
"application/json": "__passthrough__"
}
}
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path//2015-03-31/
functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
243
"httpMethod": "POST",
"type": "aws"
}
}
},
"/calc/{operand1}/{operand2}/{operator}": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "operand2",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "operator",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "operand1",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Type": {
"type": "string"
}
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type": "'text/plain'"
},
"responseTemplates": {
"application/json": "\"$input.path('$.a') $input.path('$.op')
$input.path('$.b') = $input.path('$.c')\""
}
}
},
"requestTemplates": {
244
"application/json": "\n{\n
\"a\":
\"$input.params('operand1')\",\n
\"b\": \"$input.params('operand2')\",
\n
\"op\": #if($input.params('operator')=='%2F')\"/
\"#{else}\"$input.params('operator')\"#end\n
\n}"
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path//2015-03-31/
functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"httpMethod": "POST",
"type": "aws"
}
}
}
},
"definitions": {
"Empty": {
"type": "object"
}
}
}
Note
To integrate your API Gateway API with Amazon S3, you must choose a region where both
the API Gateway and Amazon S3 services are available. For region availability, see Regions
and Endpoints.
You may want to import the sample API as an Amazon S3 proxy, as shown in A Sample Amazon S3
Proxy API in Swagger with API Gateway Extensions (p. 254). To do so, copy the Swagger definition
and paste it into a file. Use the API Gateway Swagger Importer. For more information, see Getting
Started with the API Gateway Swagger Importer.
To use the API Gateway console to create the API, you must first sign up for an AWS account.
If you do not have an AWS account, use the following procedure to create one.
2.
245
To allow the API to invoke the Amazon S3 actions, you must have appropriate IAM policies attached to
an IAM role. The next section describes how to verify and to create, if necessary, the required IAM role
and policies.
This policy document states that any of the Amazon S3 Get* and List* actions can be invoked on
any of the Amazon S3 resources.
To allow Amazon S3 buckets and objects to be updated, you can use a custom policy for any of the
Amazon S3 Put* actions.
You can attach a read-only and a put-only policy to an IAM role if your API works with Amazon S3
Get*, List* and Put* actions only.
To invoke the Amazon S3 Post actions, you must include s3:Post* action in an Allow policy
document. For a complete list of Amazon S3 actions, see Specifying Amazon S3 Permissions in a
Policy.
246
For an API to create, view, update, and delete buckets and objects in Amazon S3, you can attach a
single full-access policy. For this, you can use the AmazonS3FullAccess policy, which is provided by
the IAM console and whose ARN is arn:aws:iam::aws:policy/AmazonS3FullAccess.
This policy covers all actions on any resources in Amazon S3. Using the IAM role and policies ensures
that API Gateway can call the specifically allowed Amazon S3 actions on the specified Amazon S3
resources.
After you have decided which IAM policy documents to use, create an IAM role. Attach the policies to
the role. The resulting IAM role must contain the following trust policy for the attached policies to be
applied on API Gateway.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
When using the IAM console to create the role, choose the Amazon API Gateway role type to ensure
that this trust policy is automatically included.
In the API Gateway console, create an API named MyS3. This API's root resource (/) represents
the Amazon S3 service. Later, we will expose the GET method to list the Amazon S3 buckets of
the caller.
247
2.
For the API's root resource, create a child resource named Folder, setting the required Resource
Path as /{folder}. The folder path parameter enables the client to specify a bucket name in the
URL when the client calls the API to work with the bucket. Later, we will expose the DELETE,
GET, and PUT methods on this Folder resource to work with an Amazon S3 bucket in the back
end. We will also declare a bucket path parameter for the back-end URL and specify a mapping
expression to translate folder to bucket.
3.
For the API's Folder resource, identified by the /{folder} resource path, create an Item child
resource. Set the required Resource Path as /{item}. The folder and item path parameters
enable the client to specify, in the request's URL, an object name in a given folder when the
client calls the API to work with the object. Later, we will expose the DELETE, HEAD, GET and
PUT methods on this Item resource. We will also declare bucket and object path parameters for
the back-end URL and specify mapping expressions to translate folder and item to bucket and
object, respectively.
2.
3.
4.
5.
6.
7.
Copy the previously created IAM role's ARN (from the IAM console) and paste it into Execution
role.
8.
248
Note
After the method is set up, you can modify these settings in the method's Integration
Request page.
By default, API Gateway assumes the request and response payload to be of the "application/json"
type. However, Amazon S3 returns results in an XML-formatted response payload. This means that
you must override the default Content-Type header value of the method response with the ContentType header value from the integration response. Otherwise, the client will see "application/json" in the
response Content-Type header when the response body is an XML string.
To translate the integration response header to the method response header, use response header
mappings. The process involves declaring the Content-Type header explicitly for the method response
and specifying a header mapping expression for the integration response to pass the back-end
Content-Type header value to the front-end Content-Type header value.
In the API Gateway console, choose Method Response. Add the Content-Type header.
249
2.
In Integration Response, for Content-Type, type integration.response.header.ContentType for the method response.
In Method Execution, choose Test. An example result is shown in the following figure.
250
Note
To use the API Gateway console to test the API as an Amazon S3 proxy, make sure that the
targeted S3 bucket is from a different region from the API's region. Otherwise, you may get a
500 Internal Server Error response. This limitation does not apply to any deployed API.
On the /{folder} resource under the root, choose Create Method to create a PUT method.
2.
Follow the setup steps for the GET method on the root resource explained in the previous
procedure, except that you will specify PUT for HTTP method and /{bucket} for Path override.
3.
Set up the mappings for the Content-Type and possibly other headers from method request to
integration request and from integration response to method response. The instructions are the
same or similar to the header mapping from the integration response to the method response
for the GET method on the API's root resource. You must add the mapping for the Content-Type
header from the method request to integration because you must supply an XML payload in the
PUT request; this mapping overrides the default Content-Type header value (i.e., application/json)
to reflect the actual payload content type.
251
4.
In Integration Request, expand the URL Path Parameters section. Add the path parameter
name, for example, bucket, as specified in Path override. Type a path-mapping expression,
namely method.request.path.folder, to map the front-end path parameter (folder) for the method
request to the back-end path parameter (bucket) for the integration request.
5.
Choose Test from the Method Execution pane to test this PUT method. In folder, type a bucket
name, and then in Content-Type, type application/xml. In Request Body, provide the bucket
region as the location constraint; it is declared in an XML fragment as the payload of the request.
<CreateBucketConfiguration>
<LocationConstraint>us-west-2</LocationConstraint>
</CreateBucketConfiguration>
252
6.
Repeat the preceding steps to create and configure the GET and DELETE method on the API's /
{folder} resource.
Repeat the preceding steps to create and configure the DELETE, HEAD, GET and PUT methods
on the /{folder}/{item} resource. The following image shows integration settings for the PUT
method. The settings for the other methods are similar.
253
2.
To test the GET method on a Folder/Item resource using the API Gateway console, choose
Test in the Method Execution page. The following image shows the result of an example test,
where the README.txt file in the apig-demo bucket in Amazon S3 contains a string of plain text
("Welcome to README.txt").
254
255
256
257
258
259
260
261
262
Note
To integrate your API Gateway API with Amazon Kinesis, you must choose a region where
both the API Gateway and Amazon Kinesis services are available. For region availability, see
Regions and Endpoints.
For the purpose of illustration, we will create an example API to enable a client to do the following:
1. List the user's available streams in Amazon Kinesis
2. Create, describe, or delete a specified stream
3. Read data records from or write data records into the specified stream
To accomplish the preceding tasks, the API exposes methods on various resources to invoke the
following, respectively:
1. The ListStreams action in Amazon Kinesis
2. The CreateStream, DescribeStream, or DeleteStream action
3. The GetRecords or PutRecords (including PutRecord) action in Amazon Kinesis
Specifically, we will build the API as follows:
Expose an HTTP GET method on the API's /streams resource and integrate the method with the
ListStreams action in Amazon Kinesis to list the streams in the caller's account.
Expose an HTTP POST method on the API's /streams/{stream-name} resource and integrate
the method with the CreateStream action in Amazon Kinesis to create a named stream in the caller's
account.
Expose an HTTP GET method on the API's /streams/{stream-name} resource and integrate
the method with the DescribeStream action in Amazon Kinesis to describe a named stream in the
caller's account.
Expose an HTTP DELETE method on the API's /streams/{stream-name} resource and integrate
the method with the DeleteStream action in Amazon Kinesis to delete a stream in the caller's
account.
Expose an HTTP PUT method on the API's /streams/{stream-name}/record resource and
integrate the method with the PutRecord action in Amazon Kinesis. This enables the client to add a
single data record to the named stream.
Expose an HTTP PUT method on the API's /streams/{stream-name}/records resource and
integrate the method with the PutRecords action in Amazon Kinesis. This enables the client to add a
list of data records to the named stream.
Expose an HTTP GET method on the API's /streams/{stream-name}/records resource and
integrate the method with the GetRecords action in Amazon Kinesis. This enables the client to list
data records in the named stream, with a specified shard iterator. A shard iterator specifies the shard
position from which to start reading data records sequentially.
Expose an HTTP GET method on the API's /streams/{stream-name}/sharditerator
resource and integrate the method with the GetShardIterator action in Amazon Kinesis. This helper
method must be supplied to the ListStreams action in Amazon Kinesis.
263
You can apply the instructions presented here to other Amazon Kinesis actions. For the complete list of
the Amazon Kinesis actions, see Amazon Kinesis API Reference.
Instead of using the API Gateway console to create the sample API, you can import the sample API
into API Gateway, using either the API Gateway Import API or the API Gateway Swagger Importer. For
information on how to use the Import API, see Import an API (p. 124). For information on how to use
the API Gateway Swagger Importer, see Getting Started with the API Gateway Swagger Importer.
If you do not have an AWS account, use the following procedure to create one.
2.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:Get*",
"kinesis:List*",
"kinesis:Describe*"
],
"Resource": "*"
}
]
}
This policy is available from the IAM console and its ARN is arn:aws:iam::aws:policy/
AmazonKinesisReadOnlyAccess.
To enable read-write actions in Amazon Kinesis, you can use the AmazonKinesisFullAccess policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "kinesis:*",
"Resource": "*"
}
264
]
}
This policy is also available from the IAM console. Its ARN is arn:aws:iam::aws:policy/
AmazonKinesisFullAccess.
After you decide which IAM policy to use, attach it to a new or existing IAM role. Make sure that the API
Gateway control service (apigateway.amazonaws.com) is a trusted entity of the role and is allowed
to assume the execution role (sts:AssumeRole).
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
If you create the execution role in the IAM console and choose the Amazon API Gateway role type,
this trust policy is automatically attached.
Note the ARN of the execution role. You will need it when creating an API method and setting up its
integration request.
3.
4.
5.
For Clone from API, choose Do not clone from existing API.
Type a description in Description.
Choose Create API.
After the API is created, the API Gateway console displays the Resources page, which contains only
the API's root (/) resource.
265
2.
Select the /Streams resource. From Actions, choose Create Method, choose GET from the list,
and then choose the checkmark icon to finish creating the method.
Note
You can choose any of the available HTTP verbs for a method request. We use GET here,
because listing streams is a READ operation.
3.
In the method's Setup pane, choose Show Advanced and then choose AWS Service Proxy.
a.
b.
c.
Note
For the integration request with Amazon Kinesis, you must choose the POST HTTP
verb to invoke the action, although you can use any of the available HTTP verbs for
the API's method request.
d.
e.
f.
For Execution role, type the ARN for your execution role.
g.
The initial setup of the integration request will suffice if there is no need to map data between
the method and integration requests and/or between the method and integration responses.
Examples discussed in this topic require data mapping, which is covered in the second half of the
Integration Request pane.
4.
b.
c.
d.
5.
b.
c.
d.
e.
Choose Mapping template from the drop-down list to open the Template editor.
f.
g.
{
"ExclusiveStartStreamName": "string",
"Limit": number
}
However, the properties are optional. To use the default values, we opted for an empty JSON
payload here.
6.
Test the GET method on the Streams resource to invoke the ListStreams action in Amazon
Kinesis:
From the API Gateway console, select the /streams/GET entry from the Resources pane, choose
the Test invocation option, and then choose Test.
If you have already created two streams named "myStream" and "yourStream" in Amazon Kinesis,
the successful test will return a 200 OK response containing the following payload:
{
"HasMoreStreams": false,
267
"StreamNames": [
"myStream",
"yourStream"
]
}
268
We can build our API to accept the required input as a JSON payload of the method request and pass
the payload through to the integration request. However, to provide more examples of data mapping
between method and integration requests, and method and integration responses, we will create our
API slightly differently.
We will expose the GET, POST, and Delete HTTP methods on a to-be-named Stream resource. We
will use the {stream-name} path variable to hold the to-be-named stream resource and integrate
these API methods with the Amazon Kinesis' DescribeStream, CreateStream, and DeleteStream
actions, respectively. We require that the client pass other input data as headers, query parameters,
or the payload of a method request, and we provide mapping templates to transform the data to the
required integration request payload.
After the methods are created on a to-be-named stream resource, the structure of the API looks like
the following:
Set up the GET method to describe a named stream in Amazon Kinesis, as shown in the following.
2.
Map data from the GET method request to the integration request, as shown in the following:
269
3.
Test the GET method to invoke the DescribeStream action in Amazon Kinesis:
From the API Gateway console, select /streams/{stream-name}/GET in the Resources pane,
choose Test to start testing, type the name of an existing Amazon Kinesis stream in the Path field
for stream-name, and choose Test. If the test is successful, a 200 OK response is returned with a
payload similar to the following:
{
"StreamDescription": {
"HasMoreShards": false,
"RetentionPeriodHours": 24,
"Shards": [
{
"HashKeyRange": {
"EndingHashKey": "68056473384187692692674921486353642290",
"StartingHashKey": "0"
},
"SequenceNumberRange": {
"StartingSequenceNumber":
"49559266461454070523309915164834022007924120923395850242"
},
"ShardId": "shardId-000000000000"
},
...
{
"HashKeyRange": {
"EndingHashKey": "340282366920938463463374607431768211455",
"StartingHashKey": "272225893536750770770699685945414569164"
},
"SequenceNumberRange": {
"StartingSequenceNumber":
"49559266461543273504104037657400164881014714369419771970"
},
270
"ShardId": "shardId-000000000004"
}
],
"StreamARN": "arn:aws:kinesis:us-east-1:12345678901:stream/myStream",
"StreamName": "myStream",
"StreamStatus": "ACTIVE"
}
}
After you deploy the API, you can make a REST request against this API method:
GET https://your-api-id.execute-api.region.amazonaws.com/stage/
streams/myStream HTTP/1.1
Host: your-api-id.execute-api.region.amazonaws.com
Content-Type: application/json
Authorization: ...
X-Amz-Date: 20160323T194451Z
Set up the POST method on a stream resource to create the stream in Amazon Kinesis, as shown
in the following:
2.
Map data from the POST method request to the integration request, as shown in the following:
271
In this example, we use the following mapping template to set ShardCount to a fixed value of 5 if
the client does not specify a value in the method request payload. Otherwise, we pass the clientsupplied value to the back end.
{
"ShardCount": #if($input.path('$.ShardCount') == '') 5 #else
$input.path('$.ShardCount')",
"StreamName": "$input.params('stream-name')"
}
POST https://your-api-id.execute-api.region.amazonaws.com/stage/
streams/yourStream HTTP/1.1
Host: your-api-id.execute-api.region.amazonaws.com
Content-Type: application/json
Authorization: ...
X-Amz-Date: 20160323T194451Z
{
"ShardCount": 5
272
Set up the DELETE method to invoke the DeleteStream action in Amazon Kinesis, as shown in
the following.
2.
Map data from the DELETE method request to the integration request, as shown in the following:
273
3.
DELETE https://your-api-id.execute-api.region.amazonaws.com/stage/
streams/yourStream HTTP/1.1
Host: your-api-id.execute-api.region.amazonaws.com
Content-Type: application/json
Authorization: ...
X-Amz-Date: 20160323T194451Z
{}
274
Amazon Kinesis. The former adds multiple records whereas the latter adds a single record to the
stream.
or
Here, StreamName identifies the target stream to add records. StreamName, Data, and
PartitionKey are required input data. In our example, we use the default values for all of the
optional input data and will not explicitly specify values for them in the input to the method request.
Reading data in Amazon Kinesis amounts to calling the GetRecords action:
POST /?Action=GetRecords HTTP/1.1
Host: kinesis.region.domain
Authorization: AWS4-HMAC-SHA256 Credential=..., ...
...
Content-Type: application/x-amz-json-1.1
Content-Length: PayloadSizeBytes
{
"ShardIterator": "string",
275
Here, the source stream from which we are getting records is specified in the required
ShardIterator value, as is shown in the following Amazon Kinesis action to obtain a shard iterator:
For the GetRecords and PutRecords actions, we expose the GET and PUT methods, respectively, on
a /records resource that is appended to a named stream resource (/{stream-name}). Similarly, we
expose the PutRecord action as a PUT method on a /record resource.
Because the GetRecords action takes as input a ShardIterator value, which is obtained by calling
the GetShardIterator helper action, we expose a GET helper method on a ShardIterator
resource (/sharditerator).
The following figure shows the API structure of resources after the methods are created:
The following four procedures describe how to set up each of the methods, how to map data from the
method requests to the integration requests, and how to test the methods.
To configure and test the PUT method on the record resource in the API to invoke the
PutRecord action in Amazon Kinesis:
1.
276
2.
Configure data mapping for the PUT-on-Record method, as shown in the following:
The preceding mapping template assumes that the method request payload is of the following
format:
{
"Data": "some data",
"PartitionKey": "some key"
}
277
You can create a model to include this schema and use the model to facilitate generating the
mapping template. However, you can generate a mapping template without using any model.
3.
To test the PUT method, set the stream-name path variable to an existing stream, supply a
payload of the preceding format, and then submit the method request. The successful result is a
200 OK response with a payload of the following format:
{
"SequenceNumber":
"49559409944537880850133345460169886593573102115167928386",
"ShardId": "shardId-000000000004"
}
To configure and test the PUT method on the records resource in the API to invoke the
PutRecords action in Amazon Kinesis
1.
2.
Configure data mapping for the PUT method, as shown in the following:
278
The preceding mapping template assumes the method request payload can be modeled by
following JSON schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PutRecords proxy payload data",
"type": "object",
"properties": {
"records": {
"type": "array",
"items": {
"type": "object",
"properties": {
"data": { "type": "string" },
"partition-key": { "type": "string" }
}
}
}
}
}
3.
To test the PUT method, set the stream-name path variable to an existing stream, supply a
payload as previously shown, and submit the method request. The successful result is a 200 OK
response with a payload of the following format:
{
"records": [
{
"data": "some data",
"partition-key": "some key"
279
{
"FailedRecordCount": 0,
"Records": [
{
"SequenceNumber":
"49559409944537880850133345460167468741933742152373764162",
"ShardId": "shardId-000000000004"
},
{
"SequenceNumber":
"49559409944537880850133345460168677667753356781548470338",
"ShardId": "shardId-000000000004"
}
]
}
To configure and test the GET method on the ShardIterator resource in the API to
invoke the GetShardIterator action in Amazon Kinesis
The GET-on-ShardIterator method is a helper method to acquire a required shard iterator before calling
the GET-on-Records method.
1.
2.
280
In the following mapping template, we add the translation of the shard-id query parameter
value to the ShardId property value of the JSON payload for the GetShardIterator action in
Amazon Kinesis.
3.
4.
281
Using the Test option in the API Gateway console, enter an existing stream name as the streamname Path variable value, set the shard-id Query string to an existing ShardId value (e.g.,
shard-000000000004), and choose Test.
The successful response payload will be similar to the following output:
{
"ShardIterator": "AAAAAAAAAAFYVN3VlFy..."
}
Make note of the ShardIterator value. You will need it to get records from a stream.
To configure and test the GET Method on the records resource in the API to invoke the
GetRecords action in Amazon Kinesis
1.
2.
The GetRecords action requires an input of a ShardIterator value. To pass a client-supplied
ShardIterator value, we add a Shard-Iterator header parameter to the method request, as
shown in the following:
282
In the following mapping template, we add the mapping from the Shard-Iterator header
value to the ShardIterator property value of the JSON payload for the GetRecords action in
Amazon Kinesis.
3.
4.
Using the Test option in the API Gateway console, type an existing stream name as the streamname Path variable value, set the Shard-Iterator Header to the ShardIterator value
obtained from the test run of the GET-on-ShardIterator method (above), and choose Test.
The successful response payload will be similar to the following output:
{
"MillisBehindLatest": 0,
283
"NextShardIterator": "AAAAAAAAAAF...",
"Records": [ ... ]
}
284
"/streams/{stream-name}": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n
\"StreamName\":
\"$input.params('stream-name')\"\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/
DescribeStream",
"httpMethod": "POST",
"type": "aws"
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
285
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n
\"ShardCount\": 5,\n
\"StreamName
\": \"$input.params('stream-name')\"\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/CreateStream",
"httpMethod": "POST",
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amzjson-1.1'"
},
"type": "aws"
}
},
"delete": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response",
"headers": {
"Content-Type": {
"type": "string"
}
}
286
},
"500": {
"description": "500 response",
"headers": {
"Content-Type": {
"type": "string"
}
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type"
}
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type"
}
},
"5\\d{2}": {
"statusCode": "500",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type"
}
}
},
"requestTemplates": {
"application/json": "{\n
\"StreamName\":
\"$input.params('stream-name')\"\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/DeleteStream",
"httpMethod": "POST",
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amzjson-1.1'"
},
"type": "aws"
}
}
},
"/streams/{stream-name}/record": {
"put": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
287
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n
\"StreamName
\": \"$input.params('stream-name')\",\n
\"Data\":
\"$util.base64Encode($input.path('$.Data'))\",\n
\"PartitionKey\":
\"$input.path('$.PartitionKey')\"\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecord",
"httpMethod": "POST",
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amzjson-1.1'"
},
"type": "aws"
}
}
},
"/streams/{stream-name}/records": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "Shard-Iterator",
"in": "header",
"required": false,
"type": "string"
}
],
288
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n
\"ShardIterator\":
\"$input.params('Shard-Iterator')\"\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetRecords",
"httpMethod": "POST",
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amzjson-1.1'"
},
"type": "aws"
}
},
"put": {
"consumes": [
"application/json",
"application/x-amz-json-1.1"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": false,
"type": "string"
},
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "PutRecordsMethodRequestPayload",
"required": true,
"schema": {
"$ref": "#/definitions/PutRecordsMethodRequestPayload"
}
}
],
"responses": {
289
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n
\"StreamName\":
\"$input.params('stream-name')\",\n
\"Records\": [\n
#foreach($elem
in $input.path('$.records'))\n
{\n
\"Data\":
\"$util.base64Encode($elem.data)\",\n
\"PartitionKey\":
\"$elem.partition-key\"\n
}#if($foreach.hasNext),#end\n
#end
\n
]\n}",
"application/x-amz-json-1.1": "#set($inputRoot =
$input.path('$'))\n{\n \"StreamName\": \"$input.params('stream-name')\",\n
\"records\" : [\n
#foreach($elem in $inputRoot.records)\n
{\n
\"Data\" : \"$elem.data\",\n
\"partition-key\" : \"$elem.partitionkey\"\n
}#if($foreach.hasNext),#end\n
#end\n ]\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecords",
"httpMethod": "POST",
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amzjson-1.1'"
},
"type": "aws"
}
}
},
"/streams/{stream-name}/sharditerator": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "shard-id",
"in": "query",
"required": false,
"type": "string"
}
],
290
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n
\"ShardId\": \"$input.params('shardid')\",\n
\"ShardIteratorType\": \"TRIM_HORIZON\",\n
\"StreamName\":
\"$input.params('stream-name')\"\n}"
},
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/
GetShardIterator",
"httpMethod": "POST",
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amzjson-1.1'"
},
"type": "aws"
}
}
}
},
"definitions": {
"PutRecordsMethodRequestPayload": {
"type": "object",
"properties": {
"records": {
"type": "array",
"items": {
"type": "object",
"properties": {
"data": {
"type": "string"
},
"partition-key": {
"type": "string"
}
}
}
}
}
},
"Empty": {
"type": "object"
}
}
}
291
292
Default Limit
Can Be
Increased
1000 request per second (rps) with a burst limit of 2000 rps.
Yes
60
Yes
500
Yes
300
Yes
Custom authorizers
per API
10
Yes
Client certificates
per account
60
Yes
300
Yes
293
Resource or
Operation
Default Limit
Can Be
Increased
10
Yes
Not for
the upper
bound
(3600)
Integration timeout
No
Payload size
10 MB
No
Number of iterations
in a #foreach ...
#end loop in
mapping templates
1000
No
ARN length of
a method with
authorization
1600 bytes
No
When authorization is enabled on a method, the maximum length of the method's ARN (e.g.,
arn:aws:execute-api:{region-id}:{account-id}:{api-id}/{stage-id}/{method}/
{resource}/{path}) is 1600 bytes. The path parameter values, the size of which are determined at
run time, can cause the ARN length to exceed the limit. When this happens, the API client will receive
a 414 Request URI too long response.
Default Limit
Can Be Increased
CreateRestApi
No
ImportRestApi
No
PutRestApi
No
DeleteRestApi
No
CreateDeployment
No
UpdateAccount
No
GetResources
No
294
Action
Default Limit
Can Be Increased
CreateResource
No
DeleteResource
No
CreateDomainName
No
Note
API caching in Amazon API Gateway is not eligible for the AWS Free Tier.
Known Issues
Cross-account authentication is not currently supported in API Gateway. An API caller must be an
IAM user of the same AWS account of the API owner.
When using the API Gateway console to test an API, you may get an "unknown endpoint errors"
response if a self-signed certificate is presented to the back end, the intermediate certificate is
missing from the certificate chain, or any other unrecognizable certificate-related exceptions thrown
by the back end.
295
Document History
The following table describes the important changes to the documentation since the last release of the
API Gateway Developer Guide.
Latest documentation update: September 20, 2016
Change
Description
Date
Changed
Enabling a proxy
integration with an
HTTP or Lambda
back end through a
proxy resource of an
API.
September
20, 2016
Extending selected
APIs in API Gateway
as product offerings
for your customers
by providing one or
more usage plans.
August 11,
2016
Enabling Amazon
CloudWatch metrics
and dimensions
under the AWS/
ApiGateway
namespace.
Enabling certificate
rotation for a custom
domain name
296
Change
Description
Date
Changed
Documenting
changes for the
updated Amazon API
Gateway console.
April 5, 2016
With the Import API features, you can create a new API
or update an existing one by uploading an external API
definition expressed in Swagger 2.0 with the API Gateway
extensions. For more information about the Import API, see
Import an API (p. 124).
April 5, 2016
Exposing the
For more information about $input.body and
$input.body
$util.parseJson(), see Request and Response
variable to access
Payload-Mapping Reference (p. 117).
the raw payload
as string and the
$util.parseJson()
function to turn a
JSON string into a
JSON object in a
mapping template.
April 5, 2016
Enabling client
requests with
method-level
cache invalidation,
and improving
request throttling
management.
March 25,
2016
February 11,
2016
Importing and
exporting API
Gateway API using
a Swagger definition
file and extensions
December 18,
2015
Mapping request or
response body or
body's JSON fields to
request or response
parameters.
December 18,
2015
November 5,
2015
297
Change
Description
Date
Changed
November 3,
2015
September
22, 2015
Mock integration of
methods
September 1,
2015
Amazon Cognito
Identity support
August 28,
2015
Swagger integration
Mapping Template
Reference
July 9, 2015
298
AWS Glossary
For the latest AWS terminology, see the AWS Glossary in the AWS General Reference.
299