Apigateway DG
Apigateway DG
Developer Guide
Amazon API Gateway Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
Amazon API Gateway Developer Guide
Table of Contents
What is Amazon API Gateway? ............................................................................................................ 1
Architecture of API Gateway ........................................................................................................ 1
Features of API Gateway ............................................................................................................. 2
API Gateway use cases ................................................................................................................ 3
Use API Gateway to create HTTP APIs .................................................................................. 3
Use API Gateway to create REST APIs ................................................................................... 3
Use API Gateway to create WebSocket APIs ........................................................................... 4
Who uses API Gateway? ...................................................................................................... 4
Accessing API Gateway ............................................................................................................... 5
Part of AWS serverless infrastructure ............................................................................................ 5
How to get started with Amazon API Gateway ............................................................................... 5
API Gateway concepts ................................................................................................................. 5
Choosing HTTP API or REST API .................................................................................................. 9
........................................................................................................................................ 9
Prerequisites .................................................................................................................................... 12
Getting started ................................................................................................................................ 13
Step 1: Create a Lambda function .............................................................................................. 13
Step 2: Create an HTTP API ....................................................................................................... 14
Step 3: Test your API ................................................................................................................ 14
(Optional) Step 4: Clean up ....................................................................................................... 15
Next steps ............................................................................................................................... 16
Tutorials and workshops ................................................................................................................... 17
HTTP API tutorials .................................................................................................................... 17
CRUD API with Lambda and DynamoDB .............................................................................. 18
Private integration to Amazon ECS ..................................................................................... 25
REST API tutorials .................................................................................................................... 30
Build an API with Lambda integration ................................................................................. 30
Tutorial: Create a REST API by importing an example ............................................................ 46
Build an API with HTTP integration .................................................................................... 54
Tutorial: Build an API with private integration ...................................................................... 87
Tutorial: Build an API with AWS integration ......................................................................... 89
Tutorial: Calc API with three integrations ........................................................................... 94
Tutorial: Create a REST API as an Amazon S3 proxy in API Gateway ....................................... 113
Tutorial: Create a REST API as an Amazon Kinesis proxy ....................................................... 139
Build a private REST API ................................................................................................. 177
WebSocket API tutorials .......................................................................................................... 181
WebSocket chat app ....................................................................................................... 181
Working with HTTP APIs ................................................................................................................. 186
Develop ................................................................................................................................. 186
Creating an HTTP API ..................................................................................................... 186
Routes ........................................................................................................................... 187
Access control ................................................................................................................ 189
Integrations ................................................................................................................... 197
CORS ............................................................................................................................ 209
Parameter mapping ........................................................................................................ 210
OpenAPI ........................................................................................................................ 215
Publish .................................................................................................................................. 221
Stages ........................................................................................................................... 221
Custom domain names .................................................................................................... 222
Protect .................................................................................................................................. 226
Throttling ...................................................................................................................... 227
Mutual TLS .................................................................................................................... 227
Monitor ................................................................................................................................. 231
Metrics .......................................................................................................................... 232
iii
Amazon API Gateway Developer Guide
iv
Amazon API Gateway Developer Guide
v
Amazon API Gateway Developer Guide
vi
Amazon API Gateway Developer Guide
vii
Amazon API Gateway Developer Guide
Architecture of API Gateway
• Are HTTP-based.
• Enable stateless client-server communication.
• Implement standard HTTP methods such as GET, POST, PUT, PATCH, and DELETE.
For more information about API Gateway REST APIs and HTTP APIs, see the section called “Choosing
HTTP API or REST API ” (p. 9), Working with HTTP APIs (p. 186), the section called “Use API
Gateway to create REST APIs” (p. 3), and the section called “Create and configure” (p. 242).
• Adhere to the WebSocket protocol, which enables stateful, full-duplex communication between client
and server.
• Route incoming messages based on message content.
For more information about API Gateway WebSocket APIs, see the section called “Use API Gateway to
create WebSocket APIs” (p. 4) and the section called “About WebSocket APIs” (p. 693).
Topics
• Architecture of API Gateway (p. 1)
• Features of API Gateway (p. 2)
• API Gateway use cases (p. 3)
• Accessing API Gateway (p. 5)
• Part of AWS serverless infrastructure (p. 5)
• How to get started with Amazon API Gateway (p. 5)
• Amazon API Gateway concepts (p. 5)
• Choosing between HTTP APIs and REST APIs (p. 9)
1
Amazon API Gateway Developer Guide
Features of API Gateway
This diagram illustrates how the APIs you build in Amazon API Gateway provide you or your developer
customers with an integrated and consistent developer experience for building AWS serverless
applications. API Gateway handles all the tasks involved in accepting and processing up to hundreds of
thousands of concurrent API calls. These tasks include traffic management, authorization and access
control, monitoring, and API version management.
API Gateway acts as a "front door" for applications to access data, business logic, or functionality from
your backend services, such as workloads running on Amazon Elastic Compute Cloud (Amazon EC2), code
running on AWS Lambda, any web application, or real-time communication applications.
• Support for stateful (WebSocket (p. 693)) and stateless (HTTP (p. 186) and REST (p. 242)) APIs.
• Powerful, flexible authentication (p. 273) mechanisms, such as AWS Identity and Access Management
policies, Lambda authorizer functions, and Amazon Cognito user pools.
• Developer portal (p. 620) for publishing your APIs.
• Canary release deployments (p. 507) for safely rolling out changes.
• CloudTrail (p. 799) logging and monitoring of API usage and API changes.
• CloudWatch access logging and execution logging, including the ability to set alarms. For more
information, see the section called “CloudWatch metrics” (p. 672) and the section called
“Metrics” (p. 734).
• Ability to use AWS CloudFormation templates to enable API creation. For more information, see
Amazon API Gateway Resource Types Reference and Amazon API Gateway V2 Resource Types
Reference.
• Support for custom domain names (p. 518).
• Integration with AWS WAF (p. 662) for protecting your APIs against common web exploits.
• Integration with AWS X-Ray (p. 682) for understanding and triaging performance latencies.
For a complete list of API Gateway feature releases, see Document history (p. 824).
2
Amazon API Gateway Developer Guide
API Gateway use cases
You can use HTTP APIs to send requests to AWS Lambda functions or to any publicly routable HTTP
endpoint.
For example, you can create an HTTP API that integrates with a Lambda function on the backend. When
a client calls your API, API Gateway sends the request to the Lambda function and returns the function's
response to the client.
HTTP APIs support OpenID Connect and OAuth 2.0 authorization. They come with built-in support for
cross-origin resource sharing (CORS) and automatic deployments.
To learn more, see the section called “Choosing HTTP API or REST API ” (p. 9).
For example, /incomes could be the path of a resource representing the income of the app user. A
resource can have one or more operations that are defined by appropriate HTTP verbs such as GET, POST,
PUT, PATCH, and DELETE. A combination of a resource path and an operation identifies a method of the
API. For example, a POST /incomes method could add an income earned by the caller, and a GET /
expenses method could query the reported expenses incurred by the caller.
The app doesn't need to know where the requested data is stored and fetched from on the backend. In
API Gateway REST APIs, the frontend is encapsulated by method requests and method responses. The API
interfaces with the backend by means of integration requests and integration responses.
For example, with DynamoDB as the backend, the API developer sets up the integration request to
forward the incoming method request to the chosen backend. The setup includes specifications of an
appropriate DynamoDB action, required IAM role and policies, and required input data transformation.
The backend returns the result to API Gateway as an integration response.
To route the integration response to an appropriate method response (of a given HTTP status code)
to the client, you can configure the integration response to map required response parameters from
integration to method. You then translate the output data format of the backend to that of the
frontend, if necessary. API Gateway enables you to define a schema or model for the payload to
facilitate setting up the body mapping template.
API Gateway provides REST API management functionality such as the following:
• Support for generating SDKs and creating API documentation using API Gateway extensions to
OpenAPI
3
Amazon API Gateway Developer Guide
Use API Gateway to create WebSocket APIs
For example, you could build a serverless application using an API Gateway WebSocket API and AWS
Lambda to send and receive messages to and from individual users or groups of users in a chat room. Or
you could invoke backend services such as AWS Lambda, Amazon Kinesis, or an HTTP endpoint based on
message content.
You can use API Gateway WebSocket APIs to build secure, real-time communication applications without
having to provision or manage any servers to manage connections or large-scale data exchanges.
Targeted use cases include real-time applications such as the following:
• Chat applications
• Real-time dashboards such as stock tickers
• Real-time alerts and notifications
API Gateway provides WebSocket API management functionality such as the following:
An API developer creates and deploys an API to enable the required functionality in API Gateway. The API
developer must be an IAM user in the AWS account that owns the API.
An app developer builds a functioning application to call AWS services by invoking a WebSocket or REST
API created by an API developer in API Gateway.
The app developer is the customer of the API developer. The app developer doesn't need to have an
AWS account, provided that the API either doesn't require IAM permissions or supports authorization of
users through third-party federated identity providers supported by Amazon Cognito user pool identity
federation. Such identity providers include Amazon, Amazon Cognito user pools, Facebook, and Google.
As an API developer, you can create and manage an API by using the API Gateway console, described in
Getting started with API Gateway (p. 13), or by calling the API references (p. 812). There are several
ways to call this API. They include using the AWS Command Line Interface (AWS CLI), or by using an AWS
SDK. In addition, you can enable API creation with AWS CloudFormation templates or (in the case of
REST APIs and HTTP APIs) Working with API Gateway extensions to OpenAPI (p. 744).
For a list of Regions where API Gateway is available, as well as the associated control service endpoints,
see Amazon API Gateway Endpoints and Quotas.
4
Amazon API Gateway Developer Guide
Accessing API Gateway
• AWS Management Console – The AWS Management Console provides a web interface for creating
and managing APIs. After you complete the steps in Prerequisites (p. 12), you can access the API
Gateway console at https://console.aws.amazon.com/apigateway.
• AWS SDKs – If you're using a programming language that AWS provides an SDK for, you can use an
SDK to access API Gateway. SDKs simplify authentication, integrate easily with your development
environment, and provide access to API Gateway commands. For more information, see Tools for
Amazon Web Services.
• API Gateway V1 and V2 APIs – If you're using a programming language that an SDK isn't available
for, see the Amazon API Gateway Version 1 API Reference and Amazon API Gateway Version 2 API
Reference.
• AWS Command Line Interface – For more information, see Getting Set Up with the AWS Command
Line Interface in the AWS Command Line Interface User Guide.
• AWS Tools for Windows PowerShell – For more information, see Setting Up the AWS Tools for
Windows PowerShell in the AWS Tools for Windows PowerShell User Guide.
For an app to call publicly available AWS services, you can use Lambda to interact with required services
and expose Lambda functions through API methods in API Gateway. AWS Lambda runs your code on
a highly available computing infrastructure. It performs the necessary execution and administration
of computing resources. To enable serverless applications, API Gateway supports streamlined proxy
integrations (p. 327) with AWS Lambda and HTTP endpoints.
• Getting started (p. 13), which provides a walkthrough for creating an HTTP API.
• Serverless land, which provides instructional videos.
5
Amazon API Gateway Developer Guide
API Gateway concepts
• Creating, deploying, and managing a RESTful application programming interface (API) to expose
backend HTTP endpoints, AWS Lambda functions, or other AWS services.
• Creating, deploying, and managing a WebSocket API to expose AWS Lambda functions or other
AWS services.
• Invoking exposed API methods through the frontend HTTP and WebSocket endpoints.
API Gateway REST API
A collection of HTTP resources and methods that are integrated with backend HTTP endpoints,
Lambda functions, or other AWS services. You can deploy this collection in one or more stages.
Typically, API resources are organized in a resource tree according to the application logic. Each
API resource can expose one or more API methods that have unique HTTP verbs supported by API
Gateway. For more information, see the section called “Choosing HTTP API or REST API ” (p. 9).
API Gateway HTTP API
A collection of routes and methods that are integrated with backend HTTP endpoints or Lambda
functions. You can deploy this collection in one or more stages. Each route can expose one or more
API methods that have unique HTTP verbs supported by API Gateway. For more information, see the
section called “Choosing HTTP API or REST API ” (p. 9).
API Gateway WebSocket API
A collection of WebSocket routes and route keys that are integrated with backend HTTP endpoints,
Lambda functions, or other AWS services. You can deploy this collection in one or more stages.
API methods are invoked through frontend WebSocket connections that you can associate with a
registered custom domain name.
API deployment
A point-in-time snapshot of your API Gateway API. To be available for clients to use, the deployment
must be associated with one or more API stages.
API developer
Your AWS account that owns an API Gateway deployment (for example, a service provider that also
supports programmatic access).
API endpoint
A hostname for an API in API Gateway that is deployed to a specific Region. The hostname is of the
form {api-id}.execute-api.{region}.amazonaws.com. The following types of API endpoints
are supported:
• Edge-optimized API endpoint (p. 7)
• Private API endpoint (p. 8)
• Regional API endpoint (p. 8)
API key
An alphanumeric string that API Gateway uses to identify an app developer who uses your REST or
WebSocket API. API Gateway can generate API keys on your behalf, or you can import them from a
CSV file. You can use API keys together with Lambda authorizers (p. 299) or usage plans (p. 549)
to control access to your APIs.
A logical reference to a lifecycle state of your API (for example, 'dev', 'prod', 'beta', 'v2'). API stages
are identified by API ID and stage name.
6
Amazon API Gateway Developer Guide
API Gateway concepts
App developer
An app creator who may or may not have an AWS account and interacts with the API that you, the
API developer, have deployed. App developers are your customers. An app developer is typically
identified by an API key (p. 6).
Callback URL
When a new client is connected to through a WebSocket connection, you can call an integration in
API Gateway to store the client's callback URL. You can then use that callback URL to send messages
to the client from the backend system.
Developer portal
An application that allows your customers to register, discover, and subscribe to your API products
(API Gateway usage plans), manage their API keys, and view their usage metrics for your APIs.
Edge-optimized API endpoint
The default hostname of an API Gateway API that is deployed to the specified Region while using a
CloudFront distribution to facilitate client access typically from across AWS Regions. API requests are
routed to the nearest CloudFront Point of Presence (POP), which typically improves connection time
for geographically diverse clients.
The internal interface of a WebSocket API route or REST API method in API Gateway, in which you
map the body of a route request or the parameters and body of a method request to the formats
required by the backend.
Integration response
The internal interface of a WebSocket API route or REST API method in API Gateway, in which you
map the status codes, headers, and payload that are received from the backend to the response
format that is returned to a client app.
Mapping template
A script in Velocity Template Language (VTL) that transforms a request body from the frontend
data format to the backend data format, or that transforms a response body from the backend data
format to the frontend data format. Mapping templates can be specified in the integration request
or in the integration response. They can reference data made available at runtime as context and
stage variables.
The mapping can be as simple as an identity transform that passes the headers or body through
the integration as-is from the client to the backend for a request. The same is true for a response, in
which the payload is passed from the backend to the client.
Method request
The public interface of an API method in API Gateway that defines the parameters and body that an
app developer must send in requests to access the backend through the API.
Method response
The public interface of a REST API that defines the status codes, headers, and body models that an
app developer should expect in responses from the API.
Mock integration
In a mock integration, API responses are generated from API Gateway directly, without the need
for an integration backend. As an API developer, you decide how API Gateway responds to a mock
integration request. For this, you configure the method's integration request and integration
response to associate a response with a given status code.
7
Amazon API Gateway Developer Guide
API Gateway concepts
Model
A data schema specifying the data structure of a request or response payload. A model is required
for generating a strongly typed SDK of an API. It is also used to validate payloads. A model is
convenient for generating a sample mapping template to initiate creation of a production mapping
template. Although useful, a model is not required for creating a mapping template.
Private API
An API endpoint that is exposed through interface VPC endpoints and allows a client to securely
access private API resources inside a VPC. Private APIs are isolated from the public internet, and they
can only be accessed using VPC endpoints for API Gateway that have been granted access.
Private integration
An API Gateway integration type for a client to access resources inside a customer's VPC through a
private REST API endpoint without exposing the resources to the public internet.
Proxy integration
A simplified API Gateway integration configuration. You can set up a proxy integration as an HTTP
proxy integration or a Lambda proxy integration.
For HTTP proxy integration, API Gateway passes the entire request and response between the
frontend and an HTTP backend. For Lambda proxy integration, API Gateway sends the entire request
as input to a backend Lambda function. API Gateway then transforms the Lambda function output
to a frontend HTTP response.
In REST APIs, proxy integration is most commonly used with a proxy resource, which is represented
by a greedy path variable (for example, {proxy+}) combined with a catch-all ANY method.
Quick create
You can use quick create to simplify creating an HTTP API. Quick create creates an API with a
Lambda or HTTP integration, a default catch-all route, and a default stage that is configured to
automatically deploy changes. For more information, see the section called “Create an HTTP API by
using the AWS CLI” (p. 187).
Regional API endpoint
The host name of an API that is deployed to the specified Region and intended to serve clients,
such as EC2 instances, in the same AWS Region. API requests are targeted directly to the Region-
specific API Gateway API without going through any CloudFront distribution. For in-Region requests,
a Regional endpoint bypasses the unnecessary round trip to a CloudFront distribution.
In addition, you can apply latency-based routing on Regional endpoints to deploy an API to multiple
Regions using the same Regional API endpoint configuration, set the same custom domain name for
each deployed API, and configure latency-based DNS records in Route 53 to route client requests to
the Region that has the lowest latency.
A WebSocket route in API Gateway is used to direct incoming messages to a specific integration,
such as an AWS Lambda function, based on the content of the message. When you define your
WebSocket API, you specify a route key and an integration backend. The route key is an attribute in
the message body. When the route key is matched in an incoming message, the integration backend
is invoked.
8
Amazon API Gateway Developer Guide
Choosing HTTP API or REST API
A default route can also be set for non-matching route keys or to specify a proxy model that passes
the message through as-is to backend components that perform the routing and process the
request.
Route request
The public interface of a WebSocket API method in API Gateway that defines the body that an app
developer must send in the requests to access the backend through the API.
Route response
The public interface of a WebSocket API that defines the status codes, headers, and body models
that an app developer should expect from API Gateway.
Usage plan
A usage plan (p. 549) provides selected API clients with access to one or more deployed REST
or WebSocket APIs. You can use a usage plan to configure throttling and quota limits, which are
enforced on individual client API keys.
WebSocket connection
API Gateway maintains a persistent connection between clients and API Gateway itself. There is no
persistent connection between API Gateway and backend integrations such as Lambda functions.
Backend services are invoked as needed, based on the content of messages received from clients.
The following tables summarize core features that are available in HTTP APIs and REST APIs.
AWS Lambda ✓ ✓
IAM ✓ ✓
Amazon Cognito ✓* ✓
Lambda ✓ ✓
AWS services ✓ ✓
9
Amazon API Gateway Developer Guide
Choosing HTTP API or REST API
Mock ✓
Usage plans ✓
API keys ✓
API caching ✓
Request parameter ✓ ✓
transformation
Test invocation ✓
CORS configuration ✓ ✓*
Automatic deployments ✓
Default stage ✓
Default route ✓
Custom gateway ✓
responses (p. 422)
Canary release ✓
deployment (p. 507)
* You can combine different features of REST APIs to support CORS. To learn more, see the section called
“CORS” (p. 429).
10
Amazon API Gateway Developer Guide
Choosing HTTP API or REST API
AWS WAF ✓
Resource policies ✓
Regional ✓ ✓
Edge-optimized ✓
Private ✓
Execution logs ✓
AWS X-Ray ✓
11
Amazon API Gateway Developer Guide
As a best practice, you should also create an AWS Identity and Access Management (IAM) user with
administrator permissions and use that for all work that does not require root credentials. Create a
password for console access, and access keys to use command line tools. See Creating your first IAM
admin user and group in the IAM User Guide for instructions.
12
Amazon API Gateway Developer Guide
Step 1: Create a Lambda function
First, you create a Lambda function using the AWS Lambda console. Next, you create an HTTP API using
the API Gateway console. Then, you invoke your API.
When you invoke your HTTP API, API Gateway routes the request to your Lambda function. Lambda runs
the Lambda function and returns a response to API Gateway. API Gateway then returns a response to
you.
To complete this exercise, you need an AWS account and an AWS Identity and Access Management user
with console access. For more information, see Prerequisites (p. 12).
Topics
• Step 1: Create a Lambda function (p. 13)
• Step 2: Create an HTTP API (p. 14)
• Step 3: Test your API (p. 14)
• (Optional) Step 4: Clean up (p. 15)
• Next steps (p. 16)
For this example, you use the default Node.js function from the Lambda console.
13
Amazon API Gateway Developer Guide
Step 2: Create an HTTP API
The example function returns a 200 response to clients, and the text Hello from Lambda!.
You can modify your Lambda function, as long as the function's response aligns with the format that API
Gateway requires (p. 200).
The default Lambda function code should look similar to the following:
The HTTP API provides an HTTP endpoint for your Lambda function. API Gateway routes requests to
your Lambda function, and then returns the function's response to clients.
Now you've created an HTTP API with a Lambda integration that's ready to receive requests from clients.
14
Amazon API Gateway Developer Guide
(Optional) Step 4: Clean up
4. Copy your API's invoke URL, and enter it in a web browser. Append the name of your Lambda
function to your invoke URL to call your Lambda function. By default, the API Gateway console
creates a route with the same name as your Lambda function, my-function.
15
Amazon API Gateway Developer Guide
Next steps
1. In the AWS Identity and Access Management console, open the Roles page.
2. Select the function's role, for example, my-function-31exxmpl.
3. Choose Delete role.
4. Choose Yes, delete.
You can automate the creation and cleanup of AWS resources by using AWS CloudFormation or AWS
SAM. For example AWS CloudFormation templates, see example AWS CloudFormation templates.
Next steps
For this example, you used the AWS Management Console to create a simple HTTP API. The HTTP API
invokes a Lambda function and returns a response to clients.
The following are next steps as you continue to work with API Gateway.
To get help with Amazon API Gateway from the community, see the API Gateway Discussion Forum.
When you enter this forum, AWS might require you to sign in.
To get help with API Gateway directly from AWS, see the support options on the AWS Support page.
16
Amazon API Gateway Developer Guide
HTTP API tutorials
• Tutorial: Build a CRUD API with Lambda and DynamoDB (p. 18)
• Tutorial: Building an HTTP API with a private integration to an Amazon ECS service (p. 25)
• Build an API Gateway REST API with Lambda integration (p. 30)
• Tutorial: Create a REST API by importing an example (p. 46)
• Build an API Gateway REST API with HTTP integration (p. 54)
• Tutorial: Build a REST API with API Gateway private integration (p. 87)
• Tutorial: Build an API Gateway REST API with AWS integration (p. 89)
• Tutorial: Create a Calc REST API with two AWS service integrations and one Lambda non-proxy
integration (p. 94)
• Tutorial: Create a REST API as an Amazon S3 proxy in API Gateway (p. 113)
• Tutorial: Create a REST API as an Amazon Kinesis proxy in API Gateway (p. 139)
• Tutorial: Building a private REST API (p. 177)
• Tutorial: Building a serverless chat app with a WebSocket API, Lambda and DynamoDB (p. 181)
Workshops
Topics
• Tutorial: Build a CRUD API with Lambda and DynamoDB (p. 18)
• Tutorial: Building an HTTP API with a private integration to an Amazon ECS service (p. 25)
17
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
First, you create a DynamoDB table using the DynamoDB console. Then you create a Lambda function
using the AWS Lambda console. Next, you create an HTTP API using the API Gateway console. Lastly, you
test your API.
When you invoke your HTTP API, API Gateway routes the request to your Lambda function. The Lambda
function interacts with DynamoDB, and returns a response to API Gateway. API Gateway then returns a
response to you.
To complete this exercise, you need an AWS account and an AWS Identity and Access Management user
with console access. For more information, see Prerequisites (p. 12).
In this tutorial, you use the AWS Management Console. For an AWS SAM template that creates this API
and all related resources, see template.yaml.
Topics
• Step 1: Create a DynamoDB table (p. 18)
• Step 2: Create a Lambda function (p. 19)
• Step 3: Create an HTTP API (p. 20)
• Step 4: Create routes (p. 20)
• Step 5: Create an integration (p. 21)
• Step 6: Attach your integration to routes (p. 22)
• Step 7: Test your API (p. 22)
• Step 8: Clean up (p. 24)
• Next steps: Automate with AWS SAM or AWS CloudFormation (p. 24)
Each item has a unique ID, which we use as the partition key for the table.
18
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
try {
switch (event.routeKey) {
case "DELETE /items/{id}":
await dynamo
.delete({
TableName: "http-crud-tutorial-items",
Key: {
id: event.pathParameters.id
}
})
.promise();
body = `Deleted item ${event.pathParameters.id}`;
break;
case "GET /items/{id}":
body = await dynamo
.get({
TableName: "http-crud-tutorial-items",
Key: {
id: event.pathParameters.id
}
})
.promise();
break;
19
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
return {
statusCode,
body,
headers
};
};
• GET /items/{id}
• GET /items
20
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
• PUT /items
• DELETE /items/{id}
To create routes
To create an integration
21
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
8. Choose Create.
Now that you have an HTTP API with routes and integrations, you can test your API.
22
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
3. Note your API's invoke URL. It appears under Invoke URL on the Details page.
• Use the following command to create or update an item. The command includes a request body with
the item's ID, price, and name.
curl -v https://abcdef123.execute-api.us-west-2.amazonaws.com/items
To get an item
curl -v https://abcdef123.execute-api.us-west-2.amazonaws.com/items/abcdef234
To delete an item
23
Amazon API Gateway Developer Guide
CRUD API with Lambda and DynamoDB
curl -v https://abcdef123.execute-api.us-west-2.amazonaws.com/items
Step 8: Clean up
To prevent unnecessary costs, delete the resources that you created as part of this getting started
exercise. The following steps delete your HTTP API, your Lambda function, and associated resources.
1. In the AWS Identity and Access Management console, open the Roles page.
2. Select the function's role, for example, http-crud-tutorial-role.
3. Choose Delete role.
4. Choose Yes, delete.
For example AWS CloudFormation templates, see example AWS CloudFormation templates.
24
Amazon API Gateway Developer Guide
Private integration to Amazon ECS
This tutorial takes approximately an hour to complete. First, you use an AWS CloudFormation template
to create a Amazon VPC and Amazon ECS service. Then you use the API Gateway console to create a VPC
link. The VPC link allows API Gateway to access the Amazon ECS service that runs in your Amazon VPC.
Next, you create an HTTP API that uses the VPC link to connect to your Amazon ECS service. Lastly, you
test your API.
When you invoke your HTTP API, API Gateway routes the request to your Amazon ECS service through
your VPC link, and then returns the response from the service.
To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user
with console access. For more information, see Prerequisites (p. 12).
In this tutorial, you use the AWS Management Console. For an AWS CloudFormation template that
creates this API and all related resources, see template.yaml.
Topics
• Step 1: Create an Amazon ECS service (p. 25)
• Step 2: Create a VPC link (p. 26)
• Step 3: Create an HTTP API (p. 26)
• Step 4: Create a route (p. 27)
• Step 5: Create an integration (p. 27)
• Step 6: Test your API (p. 28)
• Step 7: Clean up (p. 29)
• Next steps: Automate with AWS CloudFormation (p. 30)
Download and unzip this AWS CloudFormation template, which creates all of the dependencies for the
service, including an Amazon VPC. You use the template to create an Amazon ECS service that uses an
Application Load Balancer.
25
Amazon API Gateway Developer Guide
Private integration to Amazon ECS
AWS CloudFormation provisions the ECS service, which can take a few minutes. When the status of your
AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step.
After you create your VPC link, API Gateway provisions Elastic Network Interfaces to access your VPC. The
process can take a few minutes. In the meantime, you can create your API.
26
Amazon API Gateway Developer Guide
Private integration to Amazon ECS
To create a route
To create an integration
To verify that your route and integration are set up correctly, select Attach integrations to routes. The
console shows that you have an ANY /{proxy+} route with an integration to a VPC Load Balancer.
27
Amazon API Gateway Developer Guide
Private integration to Amazon ECS
28
Amazon API Gateway Developer Guide
Private integration to Amazon ECS
If you see the welcome message, you successfully created an Amazon ECS service that runs in an
Amazon VPC, and you used an API Gateway HTTP API with a VPC link to access the Amazon ECS
service.
Step 7: Clean up
To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following
steps delete your VPC link, AWS CloudFormation stack, and HTTP API.
29
Amazon API Gateway Developer Guide
REST API tutorials
Topics
• Build an API Gateway REST API with Lambda integration (p. 30)
• Tutorial: Create a REST API by importing an example (p. 46)
• Build an API Gateway REST API with HTTP integration (p. 54)
• Tutorial: Build a REST API with API Gateway private integration (p. 87)
• Tutorial: Build an API Gateway REST API with AWS integration (p. 89)
• Tutorial: Create a Calc REST API with two AWS service integrations and one Lambda non-proxy
integration (p. 94)
• Tutorial: Create a REST API as an Amazon S3 proxy in API Gateway (p. 113)
• Tutorial: Create a REST API as an Amazon Kinesis proxy in API Gateway (p. 139)
• Tutorial: Building a private REST API (p. 177)
In Lambda proxy integration, the input to the integrated Lambda function can be expressed as any
combination of request headers, path variables, query string parameters, and body. In addition,
the Lambda function can use API configuration settings to influence its execution logic. For an API
developer, setting up a Lambda proxy integration is simple. Other than choosing a particular Lambda
function in a given region, you have little else to do. API Gateway configures the integration request
and integration response for you. Once set up, the integrated API method can evolve with the backend
without modifying the existing settings. This is possible because the backend Lambda function developer
parses the incoming request data and responds with desired results to the client when nothing goes
wrong or responds with error messages when anything goes wrong.
In Lambda non-proxy integration, you must ensure that input to the Lambda function is supplied as the
integration request payload. This implies that you, as an API developer, must map any input data the
client supplied as request parameters into the proper integration request body. You may also need to
translate the client-supplied request body into a format recognized by the Lambda function.
Topics
• Tutorial: Build a Hello World REST API with Lambda proxy integration (p. 31)
30
Amazon API Gateway Developer Guide
Build an API with Lambda integration
• Tutorial: Build an API Gateway REST API with cross-account Lambda proxy integration (p. 36)
• Tutorial: Build an API Gateway REST API with Lambda non-proxy integration (p. 37)
• Create a "Hello, World!" Lambda function to be the backend for the API.
• Create and test a "Hello, World!" API with Lambda proxy integration.
Topics
• Create a "Hello, World!" Lambda function (p. 31)
• Create a "Hello, World!" API (p. 32)
• Deploy and test the API (p. 33)
{
"greeting": "Good {time}, {name} of {city}.[ Happy {day}!]"
}
31
Amazon API Gateway Developer Guide
Build an API with Lambda integration
'use strict';
console.log('Loading hello world function');
if (event.body) {
let body = JSON.parse(event.body)
if (body.time)
time = body.time;
}
let responseBody = {
message: greeting,
input: event
};
8. Choose Deploy.
32
Amazon API Gateway Developer Guide
Build an API with Lambda integration
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
3. Create an empty API as follows:
Use browser and cURL to test an API with Lambda proxy integration
To test GET requests using only query string parameters, you can type the URL for the API's
helloworld resource into a browser address bar. For example: https://r275xc9bmd.execute-api.us-
east-1.amazonaws.com/test/helloworld?name=John&city=Seattle
For other methods, you must use more advanced REST API testing utilities, such as POSTMAN or cURL.
This tutorial uses cURL. The cURL command examples below assume that cURL is installed on your
computer.
curl -v -X POST \
'https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?
name=John&city=Seattle' \
-H 'content-type: application/json' \
-H 'day: Thursday' \
-d '{ "time": "evening" }'
Note
If you're running the command on Windows, use this syntax instead:
You should get a successful response with a payload similar to the following:
{
"message":"Good evening, John of Seattle. Happy Thursday!",
"input":{
"resource":"/helloworld",
"path":"/helloworld",
"httpMethod":"POST",
"headers":{"Accept":"*/*",
"content-type":"application/json",
"day":"Thursday",
"Host":"r275xc9bmd.execute-api.us-east-1.amazonaws.com",
"User-Agent":"curl/7.64.0",
"X-Amzn-Trace-Id":"Root=1-1a2b3c4d-a1b2c3d4e5f6a1b2c3d4e5f6",
"X-Forwarded-For":"72.21.198.64",
"X-Forwarded-Port":"443",
"X-Forwarded-Proto":"https"},
"multiValueHeaders":{"Accept":["*/*"],
34
Amazon API Gateway Developer Guide
Build an API with Lambda integration
"content-type":["application/json"],
"day":["Thursday"],
"Host":["r275xc9bmd.execute-api.us-east-1.amazonaws.com"],
"User-Agent":["curl/0.0.0"],
"X-Amzn-Trace-Id":["Root=1-1a2b3c4d-a1b2c3d4e5f6a1b2c3d4e5f6"],
"X-Forwarded-For":["11.22.333.44"],
"X-Forwarded-Port":["443"],
"X-Forwarded-Proto":["https"]},
"queryStringParameters":{"city":"Seattle",
"name":"John"
},
"multiValueQueryStringParameters":{
"city":["Seattle"],
"name":["John"]
},
"pathParameters":null,
"stageVariables":null,
"requestContext":{
"resourceId":"3htbry",
"resourcePath":"/helloworld",
"httpMethod":"POST",
"extendedRequestId":"a1b2c3d4e5f6g7h=",
"requestTime":"20/Mar/2019:20:38:30 +0000",
"path":"/test/helloworld",
"accountId":"123456789012",
"protocol":"HTTP/1.1",
"stage":"test",
"domainPrefix":"r275xc9bmd",
"requestTimeEpoch":1553114310423,
"requestId":"test-invoke-request",
"identity":{"cognitoIdentityPoolId":null,
"accountId":null,
"cognitoIdentityId":null,
"caller":null,
"sourceIp":"test-invoke-source-ip",
"accessKey":null,
"cognitoAuthenticationType":null,
"cognitoAuthenticationProvider":null,
"userArn":null,
"userAgent":"curl/0.0.0","user":null
},
"domainName":"r275xc9bmd.execute-api.us-east-1.amazonaws.com",
"apiId":"r275xc9bmd"
},
"body":"{ \"time\": \"evening\" }",
"isBase64Encoded":false
}
}
If you change POST to PUT in the preceding method request, you should get the same response.
To test the GET method, copy the following cURL command and paste it into the terminal window,
replacing r275xc9bmd with your API's API ID and us-east-1 with the region where your API is
deployed.
curl -X GET \
'https://r275xc9bmd.execute-api.us-east-1.amazonaws.com/test/helloworld?
name=John&city=Seattle' \
-H 'content-type: application/json' \
-H 'day: Thursday'
You should get a response similar to the result from the preceding POST request, except that the GET
request does not have any payload. So the body parameter will be null.
35
Amazon API Gateway Developer Guide
Build an API with Lambda integration
In this section, we show how to configure cross-account Lambda proxy integration using the Amazon API
Gateway console.
First, we create the example API from the section called “Tutorial: Create a REST API by importing an
example” (p. 46) in one account. We then create a Lambda function in another account. Finally, we use
cross-account Lambda integration to allow the example API to use the Lambda function we created in
the second account.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
3. Under Create new API, choose Example API.
4. Choose Import to create the example API.
1. Log in to the Lambda console in a different account from the one where you created your API
Gateway API.
2. Choose Create function.
3. Choose Author from scratch.
4. Under Author from scratch, do the following:
36
Amazon API Gateway Developer Guide
Build an API with Lambda integration
8. Note the full ARN for your function (in the upper right corner of the Lambda function pane). You'll
need it when you create your cross-account Lambda integration.
You should see an Allow policy with a Condition clause in which the in the AWS:SourceArn is the
ARN for your API's GET method.
To facilitate learning, we chose a simple Lambda function with minimal API setup to walk you through
the steps of building an API Gateway API with the Lambda custom integration. When necessary,
we describe some of the logic. For a more detailed example of the Lambda custom integration, see
Tutorial: Create a Calc REST API with two AWS service integrations and one Lambda non-proxy
integration (p. 94).
37
Amazon API Gateway Developer Guide
Build an API with Lambda integration
Before creating the API, set up the Lambda backend by creating a Lambda function in AWS Lambda,
described next.
Topics
• Create a Lambda function for Lambda non-proxy integration (p. 38)
• Create an API with Lambda non-proxy integration (p. 41)
• Test invoking the API method (p. 43)
• Deploy the API (p. 44)
• Test the API in a deployment stage (p. 45)
• Clean up (p. 45)
In this step, you create a "Hello, World!"-like Lambda function for the Lambda custom integration.
Throughout this walkthrough, the function is called GetStartedLambdaIntegration.
'use strict';
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
console.log('Loading function');
// Generate a greeting
let greeting = 'Good ' + time + ', ' + name + ' of ' + city + '. ';
if (day) greeting += 'Happy ' + day + '!';
For the Lambda custom integration, API Gateway passes the input to the Lambda function from the
client as the integration request body. The event object of the Lambda function handler is the input.
Our Lambda function is simple. It parses the input event object for the name, city, time, and day
properties. It then returns a greeting, as a JSON object of {"message":greeting}, to the caller. The
message is in the "Good [morning|afternoon|day], [name|you] in [city|World]. Happy
day!" pattern. It is assumed that the input to the Lambda function is of the following JSON object:
{
"city": "...",
38
Amazon API Gateway Developer Guide
Build an API with Lambda integration
"time": "...",
"day": "...",
"name" : "..."
}
If you set up the API without using the API Gateway console, such as when importing an API from an
OpenAPI file, you must explicitly create, if necessary, and set up an invocation role and policy for API
Gateway to invoke the Lambda functions. For more information on how to set up Lambda invocation and
execution roles for an API Gateway API, see Control access to an API with IAM permissions (p. 290).
• If the welcome page appears, choose Get Started Now and then choose Create function.
• If the Lambda > Functions list page appears, choose Create function.
3. Choose Author from scratch.
4. In the Author from scratch pane, do the following:
a. Copy the Lambda function code listed in the beginning of this section and paste it in the inline
code editor.
b. Leave the default choices for all other fields in this section.
c. Choose Deploy.
39
Amazon API Gateway Developer Guide
Build an API with Lambda integration
6. To test the newly created function, choose Configure test events from Select a test event....
a. For Create new event, replace any default code statements with the following, enter
HelloWorldTest for the event name, and choose Create.
{
"name": "Jonny",
"city": "Seattle",
"time": "morning",
"day": "Wednesday"
}
b. Choose Test to invoke the function. The Execution result: succeeded section is shown. Expand
Detail and you see the following output.
{
"greeting": "Good morning, Jonny of Seattle. Happy Wednesday!"
}
As a side exercise, you can use the IAM console to view the IAM role
(GetStartedLambdaIntegrationRole) that was created as part of the Lambda function creation.
Attached to this IAM role are two inline policies. One stipulates the most basic permissions for Lambda
execution. It permits calling the CloudWatch CreateLogGroup for any CloudWatch resources of
your account in the region where the Lambda function is created. This policy also allows creating
the CloudWatch streams and logging events for the HelloWorldForLambdaIntegration Lambda
function.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:region:account-id:*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:region:account-id:log-group:/aws/lambda/
GetStartedLambdaIntegration:*"
]
}
]
}
The other policy document applies to invoking another AWS service that is not used in this example. You
can skip it for now.
Associated with the IAM role is a trusted entity, which is lambda.amazonaws.com. Here is the trust
relationship:
40
Amazon API Gateway Developer Guide
Build an API with Lambda integration
"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 Lambda function
to invoke a console.log() function to log events to CloudWatch Logs.
If you did not use the AWS Management Console to create the Lambda function, you need to follow
these examples to create the required IAM role and policies and then manually attach the role to your
function.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
a. Choose ANY from the HTTP method drop-down menu. The ANY HTTP verb is a placeholder for a
valid HTTP method that a client submits at run time. This example shows that ANY method can
be used for Lambda custom integration as well as for Lambda proxy integration.
b. To save the setting, choose the check mark.
5. In Method Execution, for the /{city} ANY method, do the following:
41
Amazon API Gateway Developer Guide
Build an API with Lambda integration
At run time, the client can use these request parameters and the request body to provide time of
the day, the day of the week, and the name of the caller. You already configured the /{city} path
variable.
i. To define a model, choose Models under the API from the API Gateway primary navigation
pane, and then choose Create.
ii. Type GetStartedLambdaIntegrationUserInput for Model name.
iii. Type application/json for Content type.
iv. Leave the Model description blank.
v. Copy the following schema definition into the Model schema editor:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "GetStartedLambdaIntegrationInputModel",
"type": "object",
"properties": {
"callerName": { "type": "string" }
}
}
a. Expand the Mapping Templates section. Choose Add mapping template. Type application/
json for Content-Type. Choose the check-mark icon to save the setting.
b. In the popup that appears, choose Yes, secure this integration.
c. Check the recommended When there are no templates defined for Request body
passthrough.
d. Choose GetStartedLambaIntegrationUserInput from Generate template to generate an
initial mapping template. This option is available because you defined a model schema, without
which you would need to write the mapping template from scratch.
e. Replace the generated mapping script in the mapping template editor with the following:
#set($inputRoot = $input.path('$'))
{
"city": "$input.params('city')",
"time": "$input.params('time')",
"day": "$input.params('day')",
"name": "$inputRoot.callerName"
}
f. Choose Save.
POST /Seattle?time=morning
day:Wednesday
{
"callerName": "John"
}
In this test request, you'll set ANY to POST, set {city} to Seattle, assign Wednesday as the day
header value, and assign "John" as the callerName value.
{
"greeting": "Good morning, John of Seattle. Happy Wednesday!"
}
9. You can also view the logs to examine how API Gateway processes the request and response.
43
Amazon API Gateway Developer Guide
Build an API with Lambda integration
Thu Aug 31 01:07:25 UTC 2017 : Starting execution for request: test-invoke-request
Thu Aug 31 01:07:25 UTC 2017 : HTTP Method: POST, Resource Path: /Seattle
Thu Aug 31 01:07:25 UTC 2017 : Method request path: {city=Seattle}
Thu Aug 31 01:07:25 UTC 2017 : Method request query string: {time=morning}
Thu Aug 31 01:07:25 UTC 2017 : Method request headers: {day=Wednesday}
Thu Aug 31 01:07:25 UTC 2017 : Method request body before transformations:
{ "callerName": "John" }
Thu Aug 31 01:07:25 UTC 2017 : Request validation succeeded for content type
application/json
Thu Aug 31 01:07:25 UTC 2017 : Endpoint request URI: https://
lambda.us-west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-
west-2:123456789012:function:GetStartedLambdaIntegration/invocations
Thu Aug 31 01:07:25 UTC 2017 : Endpoint request
headers: {x-amzn-lambda-integration-tag=test-request,
Authorization=************************************************************************************
X-Amz-Date=20170831T010725Z, x-amzn-apigateway-api-id=beags1mnid, X-Amz-
Source-Arn=arn:aws:execute-api:us-west-2:123456789012:beags1mnid/null/POST/
{city}, Accept=application/json, User-Agent=AmazonAPIGateway_beags1mnid,
X-Amz-Security-Token=FQoDYXdzELL//////////wEaDMHGzEdEOT/VvGhabiK3AzgKrJw
+3zLqJZG4PhOq12K6W21+QotY2rrZyOzqhLoiuRg3CAYNQ2eqgL5D54+63ey9bIdtwHGoyBdq8ecWxJK/
YUnT2Rau0L9HCG5p7FC05h3IvwlFfvcidQNXeYvsKJTLXI05/
yEnY3ttIAnpNYLOezD9Es8rBfyruHfJfOqextKlsC8DymCcqlGkig8qLKcZ0hWJWVwiPJiFgL7laabXs
++ZhCa4hdZo4iqlG729DE4gaV1mJVdoAagIUwLMo+y4NxFDu0r7I0/
EO5nYcCrppGVVBYiGk7H4T6sXuhTkbNNqVmXtV3ch5bOlh7 [TRUNCATED]
Thu Aug 31 01:07:25 UTC 2017 : Endpoint request body after transformations: {
"city": "Seattle",
"time": "morning",
"day": "Wednesday",
"name" : "John"
}
Thu Aug 31 01:07:25 UTC 2017 : Sending request to https://lambda.us-
west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-
west-2:123456789012:function:GetStartedLambdaIntegration/invocations
Thu Aug 31 01:07:25 UTC 2017 : Received response. Integration latency: 328 ms
Thu Aug 31 01:07:25 UTC 2017 : Endpoint response body before transformations:
{"greeting":"Good morning, John of Seattle. Happy Wednesday!"}
Thu Aug 31 01:07:25 UTC 2017 : Endpoint response headers: {x-amzn-Remapped-Content-
Length=0, x-amzn-RequestId=c0475a28-8de8-11e7-8d3f-4183da788f0f, Connection=keep-
alive, Content-Length=62, Date=Thu, 31 Aug 2017 01:07:25 GMT, X-Amzn-Trace-
Id=root=1-59a7614d-373151b01b0713127e646635;sampled=0, Content-Type=application/json}
Thu Aug 31 01:07:25 UTC 2017 : Method response body after transformations:
{"greeting":"Good morning, John of Seattle. Happy Wednesday!"}
Thu Aug 31 01:07:25 UTC 2017 : Method response headers: {X-Amzn-Trace-
Id=sampled=0;root=1-59a7614d-373151b01b0713127e646635, Content-Type=application/json}
Thu Aug 31 01:07:25 UTC 2017 : Successfully completed execution
Thu Aug 31 01:07:25 UTC 2017 : Method completed with status: 200
The logs show the incoming request before the mapping and the integration request after the
mapping. When a test fails, the logs are useful for evaluating whether the original input is correct or
the mapping template works correctly.
44
Amazon API Gateway Developer Guide
Build an API with Lambda integration
1. 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. For Deployment stage, choose New Stage.
3. For Stage name, type a name; for example, test.
Note
The input must be UTF-8 encoded (i.e., unlocalized) text.
4. For Stage description, type a description or leave it blank.
5. For Deployment description, type a description or leave it blank.
6. Choose Deploy. After the API is successfully deployed, you see the API's base URL (the default host
name plus the stage name) displayed as Invoke URL at the top of the Stage Editor. The general
pattern of this base URL is https://api-id.region.amazonaws.com/stageName. For example,
the base URL of the API (beags1mnid) created in the us-west-2 region and deployed to the test
stage is https://beags1mnid.execute-api.us-west-2.amazonaws.com/test.
Copy the following cURL command and paste it into the terminal window.
curl -v -X POST \
'https://beags1mnid.execute-api.us-west-2.amazonaws.com/test/Seattle?time=evening' \
-H 'content-type: application/json' \
-H 'day: Thursday' \
-H 'x-amz-docs-region: us-west-2' \
-d '{
"callerName": "John"
}'
If you change POST to PUT in this method request, you get the same response.
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.
Warning
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.
45
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
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.
1. 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.
The PetStore example API supports the following methods for a client to access the HTTP backend
website of http://petstore-demo-endpoint.execute-api.com/petstore/pets.
• GET /: for read access of the API's root resource that is not integrated with any backend endpoint.
API Gateway responds with an overview of the PetStore website. This is an example of the MOCK
integration type.
• GET /pets: for read access to the API's /pets resource that is integrated with the like-named
backend /pets resource. The backend returns a page of available pets in the PetStore. This is an
example of the HTTP integration type. The URL of the integration endpoint is http://petstore-
demo-endpoint.execute-api.com/petstore/pets.
• POST /pets: for write access to the API's /pets resource that is integrated with the backend /
petstore/pets resource. Upon receiving a correct request, the backend adds the specified pet to the
PetStore and returns the result to the caller. The integration is also HTTP.
• GET /pets/{petId}: for read access to a pet as identified by a petId value as specified as a path
variable of the incoming request URL. This method also has the HTTP integration type. The backend
returns the specified pet found in the PetStore. The URL of the backend HTTP endpoint is http://
petstore-demo-endpoint.execute-api.com/petstore/pets/n, where n is an integer as the
identifier of the queried pet.
46
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
The API supports CORS access via the OPTIONS methods of the MOCK integration type. API Gateway
returns the required headers supporting CORS access.
The following procedure walks you through the steps to create and test an API from an example using
the API Gateway Console.
1. If you haven't already done so, complete the steps in Prerequisites (p. 12).
2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
3. If this is your first time using API Gateway, you see a page that introduces you to the features of the
service. Under REST API, choose Build. When the Create Example API popup appears, choose OK.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
4. Under Create new API, choose Example API and then choose Import to create the example API. For
your first API, the API Gateway console starts with this option as default.
You can scroll down the OpenAPI definition for details of this example API before choosing Import.
5. The newly created API is shown as follows:
47
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
The Resources pane shows the structure of the created 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.
6. 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. Here, we choose the POST /pets
method as an illustration:
The resulting Method Execution pane presents a logical view of the chosen (POST /pets) method's
structure and behaviors: Method Request and Method Response are the API's interface with
48
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
the API's frontend (a client), whereas Integration Request and Integration Response are the
API's interface with the backend (http://petstore-demo-endpoint.execute-api.com/
petstore/pets). A client uses the API to access a backend feature through the Method Request.
API Gateway translates the client request, if necessary, into the form acceptable to the backend
in Integration Request before forwarding the incoming request to the backend. The transformed
request is known as the integration request. Similarly, the backend returns the response to API
Gateway in Integration Response. API Gateway then routes it to Method Response before sending
it to the client. Again, if necessary, API Gateway can map the backend response data to a form
expected by the client.
For the POST method on an API resource, the method request payload can be passed through to the
integration request without modification, if the method request's payload is of the same format as
the integration request's payload.
The GET / method request uses the MOCK integration type and is not tied to any real backend
endpoint. The corresponding Integration Response is set up to return a static HTML page. When
the method is called, the API Gateway simply accepts the request and immediately returns the
configured integration response to the client by way of Method Response. You can use the mock
integration to test an API without requiring a backend endpoint. You can also use it to serve a local
response, generated from a response body-mapping template.
As an API developer, you control the behaviors of your API's frontend interactions by configuring
the method request and a method response. You control the behaviors of your API's backend
interactions by setting up the integration request and integration response. These involve data
mappings between a method and its corresponding integration. We cover the method setup in
Tutorial: Build a REST API with HTTP non-proxy integration (p. 59). For now, we focus on testing
the API to provide an end-to-end user experience.
7. Choose Test shown on Client (as shown in the previous image) to start testing. For example, to test
the POST /pets method, enter the following {"type": "dog","price": 249.99} payload into
the Request Body before choosing the Test button.
49
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
50
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
The input specifies the attributes of the pet that we want to add to the list of pets on the PetStore
website.
8. The results display as follows:
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
51
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
applied: the method request payload is passed through the integration request to the backend and,
similarly, the backend response is passed through the integration response to 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.
9. To deploy the sample API, select the PetStore API, and then choose Deploy API from the Actions
menu.
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.
52
Amazon API Gateway Developer Guide
Tutorial: Create a REST API by importing an example
In the resulting Stage Editor pane, Invoke URL displays the URL to invoke the API's GET / method
request.
10. On Stage Editor, follow the Invoke URL link to submit the GET / method request in a browser.
A successful response return the result, generated from the mapping template in the integration
response.
11. 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 4 (SigV4)
protocols. For an example of such a request, see the section called “Tutorial: Build an API with HTTP
non-proxy integration” (p. 59).
53
Amazon API Gateway Developer Guide
Build an API with HTTP integration
Topics
• Tutorial: Build a REST API with HTTP proxy integration (p. 54)
• Tutorial: Build a REST API with HTTP non-proxy integration (p. 59)
With the all-encompassing proxy resource {proxy+}, and the catch-all ANY verb for the HTTP method,
you can use an HTTP proxy integration to create an API of a single API method. The method exposes the
entire set of the publicly accessible HTTP resources and operations of a website. When the backend web
server opens more resources for public access, the client can use these new resources with the same API
setup. To enable this, the website developer must communicate clearly to the client developer what the
new resources are and what operations are applicable for each of them.
As a quick introduction, the following tutorial demonstrates the HTTP proxy integration. In the tutorial,
we create an API using the API Gateway console to integrate with the PetStore website through a generic
proxy resource {proxy+}, and create the HTTP method placeholder of ANY.
Topics
• Create an API with HTTP proxy integration using the API Gateway console (p. 54)
• Test an API with HTTP proxy integration (p. 56)
Create an API with HTTP proxy integration using the API Gateway console
The following procedure walks you through the steps to create and test an API with a proxy resource for
an HTTP backend using the API Gateway console. The HTTP backend is the PetStore website (http://
petstore-demo-endpoint.execute-api.com/petstore/pets) from Tutorial: Build a REST API
with HTTP non-proxy integration (p. 59), in which screenshots are used as visual aids to illustrate the
API Gateway UI elements. If you are new to using the API Gateway console to create an API, you may
want to follow that section first.
To build an API with HTTP proxy integration with the PetStore website through a proxy
resource
54
Amazon API Gateway Developer Guide
Build an API with HTTP integration
2. If this is your first time using API Gateway, you see a page that introduces you to the features of the
service. Under REST API, choose Build. When the Create Example API popup appears, choose OK.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
a. Select the Configure as proxy resource option to create a proxy resource. Otherwise, leave it
de-selected.
b. Type a name in the Resource Name* input text field.
c. Type a new name or use the default name in the Resource Path* input text field.
d. Choose Create Resource.
e. Select Enable API Gateway CORS, if required.
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.
4. To set up the ANY method for integration with the HTTP backend, do the following:
a. Choose the resource just created and then choose Create Method from the Actions drop-down
menu.
b. Choose ANY from the HTTP method drop-down list and then choose the check mark icon to save
the choice.
c. Choose HTTP Proxy for Integration type.
55
Amazon API Gateway Developer Guide
Build an API with HTTP integration
In the API just created, the API's proxy resource path of {proxy+} becomes the placeholder of any of
the backend endpoints under http://petstore-demo-endpoint.execute-api.com/. For example,
it can be petstore, petstore/pets, and petstore/pets/{petId}. The ANY method serves as a
placeholder for any of the supported HTTP verbs at run time.
• If the backend has made the corresponding backend endpoint available and, if so, has granted the
required access permissions.
• If the client supplies the correct input.
For example, the PetStore API used here does not expose the /petstore resource. As such, you get a
404 Resource Not Found response containing the error message of Cannot GET /petstore.
In addition, the client must be able to handle the output format of the backend in order to parse the
result correctly. API Gateway does not mediate to facilitate interactions between the client and backend.
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.
56
Amazon API Gateway Developer Guide
Build an API with HTTP integration
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. Choose Test to test invoking the method.
For this tutorial, use GET for Method in place of ANY, use petstore/pets for Path in place of the
proxy resource path ({proxy}), and type=fish for Query Strings.
57
Amazon API Gateway Developer Guide
Build an API with HTTP integration
58
Amazon API Gateway Developer Guide
Build an API with HTTP integration
Because the backend website supports the GET /petstore/pets?type=fish request, it returns a
successful response similar to the following:
[
{
"id": 1,
"type": "fish",
"price": 249.99
},
{
"id": 2,
"type": "fish",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
If you try to call GET /petstore, you get a 404 response with an error message of Cannot GET /
petstore. This is because the backend does not support the specified operation. If you call GET /
petstore/pets/1, you 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 and append petstore/pets?type=fish
to the API's Invoke URL. This produces a URL of https://4z9giyi2c1.execute-api.us-
west-2.amazonaws.com/test/petstore/pets?type=fish.
The result should be the same as returned when you use TestInvoke from the API Gateway
console.
Topics
• Create an API with HTTP custom integration (p. 60)
59
Amazon API Gateway Developer Guide
Build an API with HTTP integration
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
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 with the HTTP custom integration of the PetStore
website (http://petstore-demo-endpoint.execute-api.com/petstore/pets.) 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.
3. 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, choose Enable API Gateway
CORS, and choose Create Resource.
4. To expose a GET method on the /pets resource, choose Actions and then Create Method.
60
Amazon API Gateway Developer Guide
Build an API with HTTP integration
Choose GET from the list under the /pets resource node and choose the check mark icon to finish
creating the method.
61
Amazon API Gateway Developer Guide
Build an API with HTTP integration
Note
Other options for an API method include:
The method created is not yet integrated with the backend. The next step sets this up.
5. In the method's Setup pane, select HTTP 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, leave all other settings as default, and then choose Save.
Note
For the integration request's HTTP method, you must choose one supported by the
backend. For HTTP 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.
62
Amazon API Gateway Developer Guide
Build an API with HTTP integration
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.
6. 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 check mark icon to save each
query string parameter as you add it.
63
Amazon API Gateway Developer Guide
Build an API with HTTP integration
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 backend. Because the method
uses AWS_IAM, you must sign the request to invoke the method.
7. 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.
64
Amazon API Gateway Developer Guide
Build an API with HTTP integration
This completes building the simple demo API. It's time to test the API.
8. To test the API using the API Gateway console, choose Test on the Method Execution pane for the
GET /pets method. In the Method Test pane, enter Dog and 2 for the type and page query strings,
respectively, and then choose Test.
The result is shown as follows. (You may need to scroll down to see the test result.)
65
Amazon API Gateway Developer Guide
Build an API with HTTP integration
Now that the test is successful, we can deploy the API to make it publicly available.
9. To deploy the API, select the API and then choose Deploy API from the Actions drop-down menu.
66
Amazon API Gateway Developer Guide
Build an API with HTTP integration
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.
Once deployed, you can obtain the invocation URLs (Invoke URL) of the API's endpoints.
67
Amazon API Gateway Developer Guide
Build an API with HTTP integration
If the GET method supported open access, (i.e., if the method's authorization type were set to
NONE) you could double-click the Invoke URL link to invoke the method in your default browser. If
needed, you could also append necessary query string parameters to the invocation URL. With the
AWS_IAM authorization type described here, you must sign the request with an access key ID and the
corresponding secret key of an IAM user of your AWS account. To do this, you must use a client that
supports the Signature Version 4 (SigV4) protocols. An example of such a client is an app that uses
one of the AWS SDKs or the Postman application or cURL commands. To call a POST, PUT, or PATCH
method that take a payload, you also need to use such a client to handle the payload.
To invoke this API method in the Postman, 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 Type option under the Authorization tab, and then specify the following required
properties before sending the request:
• For AccessKey, type the caller's AWS access key, as provisioned from AWS IAM.
• For SecretKey, type the caller's AWS secret key, as provisioned from AWS IAM when the access key
was first created.
• For AWS Region, type the API-hosting AWS Region, as specified in the invocation URL.
• For Service Name, type execute-api, for the API Gateway execution service.
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.
http://petstore-demo-endpoint.execute-api.com/petstore/pets
If you copy the above URL, paste it into the address bar of a web browser, and press Enter or Return,
you get the following JSON-formatted response body:
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
68
Amazon API Gateway Developer Guide
Build an API with HTTP integration
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
The preceding endpoint can take two query parameters: type and page. For example, change the URL to
the following:
http://petstore-demo-endpoint.execute-api.com/petstore/pets?type=cat&page=2
You 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,
browse to the following:
http://petstore-demo-endpoint.execute-api.com/petstore/pets/1
{
"id": 1,
"type": "dog",
"price": 249.99
}
In addition to supporting GET operations, this endpoint takes POST requests with a payload. For
example, use Postman to send a POST method request to the following:
http://petstore-demo-endpoint.execute-api.com/petstore/pets
Include the header Content-type: application/json and the following request body:
{
"type": "dog",
"price": 249.99
}
69
Amazon API Gateway Developer Guide
Build an API with HTTP integration
{
"pet": {
"type": "dog",
"price": 249.99
},
"message": "success"
}
We now expose these and other features by building an API Gateway API with the HTTP custom
integration of this PetStore website. The tasks include the following:
Topics
• Prerequisites (p. 70)
• Step 1: Create resources (p. 70)
• Step 2: Create and test the methods (p. 71)
• Step 3: Deploy the API (p. 74)
• Step 4: Test the API (p. 74)
Note
Pay attention to the casing used in the steps of this walkthrough. Typing a lowercase letter
instead of an uppercase letter (or vice versa) can cause errors later in the walkthrough.
Prerequisites
1. Complete the steps in Prerequisites for getting started with API Gateway (p. 12), including assigning
API Gateway access permission to the IAM user.
2. At a minimum, follow the steps in Tutorial: Build a REST API with HTTP non-proxy
integration (p. 59) to create a new API named MyDemoAPI in the API Gateway console.
In this step, you create three resources that enable the API to interact with the HTTP endpoint.
1. 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. For Resource Name, type petstorewalkthrough.
70
Amazon API Gateway Developer Guide
Build an API with HTTP integration
3. For Resource Path, accept the default of /petstorewalkthrough, and then choose Create Resource.
1. In the Resources pane, choose /petstorewalkthrough, and then choose Create Resource.
2. For Resource Name, type pets.
3. For Resource Path, accept the default of /petstorewalkthrough/pets, and then choose Create
Resource.
1. 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}. Use curly braces ({ }) around petId so that /
petstorewalkthrough/pets/{petId} is displayed, and then choose Create Resource.
In this step, you integrate the methods with the backend HTTP endpoints, map the GET method request
parameters to the corresponding integration request parameters, and then test the methods.
• Create and integrate the method request of GET /petstorewalkthrough/pets with the
integration request of GET http://petstore-demo-endpoint.execute-api.com/petstore/
pets.
• Map the method request query parameters of petType and petsPage to the integration request
query string parameters of type and page, respectively.
1. In the Resources pane, choose /petstorewalkthrough/pets, choose Create Method from the
Actions menu, and then choose GET under /pets from the drop-down list of the method names.
2. In the /petstorewalkthrough/pets - GET - Setup pane, choose HTTP for Integration type and
choose GET for HTTP method.
3. For Endpoint URL, type http://petstore-demo-endpoint.execute-api.com/petstore/
pets.
4. Choose Save.
5. In the Method Execution pane, choose Method Request, and then choose the arrow next to URL
Query String Parameters.
6. Choose Add query string.
7. For Name, type petType.
This specifies the petType query parameter in the API's method request.
8. Choose the check mark icon to finish creating the method request URL query string parameter.
9. Choose Add query string again.
10. For Name, type petsPage.
This specifies the petsPage query parameter in the API's method request.
11. Choose the check mark icon to finish creating the method request URL query string parameter.
71
Amazon API Gateway Developer Guide
Build an API with HTTP integration
12. Choose Method Execution, choose Integration Request, and then choose the arrow next to URL
Query String Parameters.
13. Delete the petType entry mapped from method.request.querystring.petType and the
petsPage entry mapped from method.request.querystring.petsPage. You perform this step
because the endpoint requires query string parameters named type and page for the request URL,
instead of the default values.
14. Choose Add query string.
15. For Name, type type. This creates the required query string parameter for the integration request
URL.
16. For Mapped from, type method.request.querystring.petType.
This maps the method request's petType query parameter to the integration request's type query
parameter.
17. Choose the check mark icon to finish creating the integration request URL query string parameter.
18. Choose Add query string again.
19. For Name, type page. This creates the required query string parameter for the integration request
URL.
20. For Mapped from, type method.request.querystring.petsPage.
This maps the method request's petsPage query parameter to the integration request's page query
parameter.
21. Choose the check mark icon to finish creating the integration request URL query string parameter.
22. Choose Method Execution. In the Client box, choose TEST. In the Query Strings area, for petType,
type cat. For petsPage, type 2.
23. Choose Test. If successful, Response Body displays the following:
[
{
"id": 4,
"type": "cat",
"price": 999.99
},
{
"id": 5,
"type": "cat",
"price": 249.99
},
{
"id": 6,
"type": "cat",
"price": 49.97
}
]
• Create and integrate the method request of GET /petstorewalkthrough/pets/{petId} with the
integration request of GET http://petstore-demo-endpoint.execute-api.com/petstore/
pets/{id}.
• Map the method request path parameters of petId to the integration request path parameters of id.
1. In the Resources list, choose /petstorewalkthrough/pets/{petId}, choose Create Method from the
Actions drop-down menu, and then choose GET as the HTTP verb for the method.
72
Amazon API Gateway Developer Guide
Build an API with HTTP integration
2. In the Setup pane, choose HTTP for Integration type and choose GET for HTTP method.
3. For Endpoint URL, type http://petstore-demo-endpoint.execute-api.com/petstore/
pets/{id}.
4. Choose Save.
5. In the Method Execution pane, choose Integration Request, and then choose the arrow next to URL
Path Parameters.
6. Choose Add path.
7. For Name, type id.
8. For Mapped from, type method.request.path.petId.
This maps the method request's path parameter of petId to the integration request's path
parameter of id.
9. Choose the check mark icon to finish creating the URL path parameter.
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 displays the following:
{
"id": 1,
"type": "dog",
"price": 249.99
}
• Create and integrate the method request of POST /petstorewalkthrough/pets with the
integration request of POST http://petstore-demo-endpoint.execute-api.com/petstore/
pets.
• Pass the method request JSON payload through to the integration request payload, without
modification.
1. In the Resources pane, choose /petstorewalkthrough/pets, choose Create Method from the
Actions drop-down menu, and then choose POST as the HTTP verb for the method.
2. In the Setup pane, choose HTTP for Integration type and choose POST for HTTP method.
3. For Endpoint URL, type http://petstore-demo-endpoint.execute-api.com/petstore/
pets.
4. Choose Save.
5. In the Method Execution pane, in the Client box, choose TEST. Expand Request Body, and then type
the following:
{
"type": "dog",
"price": 249.99
}
{
"pet": {
"type": "dog",
"price": 249.99
},
73
Amazon API Gateway Developer Guide
Build an API with HTTP integration
"message": "success"
}
In this step, you deploy the API so that you can begin calling it outside of the API Gateway console.
In this step, you go outside of the API Gateway console and use your API to access the HTTP endpoint.
1. 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
https://my-api-id.execute-api.region-id.amazonaws.com/test/petstorewalkthrough/pets
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
https://my-api-id.execute-api.region-id.amazonaws.com/test/petstorewalkthrough/pets?
petType=cat&petsPage=2
74
Amazon API Gateway Developer Guide
Build an API with HTTP integration
[
{
"id": 4,
"type": "cat",
"price": 999.99
},
{
"id": 5,
"type": "cat",
"price": 249.99
},
{
"id": 6,
"type": "cat",
"price": 49.97
}
]
https://my-api-id.execute-api.region-id.amazonaws.com/test/petstorewalkthrough/pets/1
{
"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. Append /petstorewalkthrough/pets so that it looks like
this:
https://my-api-id.execute-api.region-id.amazonaws.com/test/petstorewalkthrough/pets
Content-Type: application/json
{
"type": "dog",
"price": 249.99
}
For example, if you use the cURL command-line tool, run a command similar to the following:
75
Amazon API Gateway Developer Guide
Build an API with HTTP integration
{
"pet": {
"type": "dog",
"price": 249.99
},
"message": "success"
}
This walkthrough uses API Gateway to get example data from a publicly accessible HTTP endpoint and
from an AWS Lambda function you 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 Working with models and mapping templates (p. 377).
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
},
{
76
Amazon API Gateway Developer Guide
Build an API with HTTP integration
"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:
[
{
"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
}
]
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
• Step 1: Create models (p. 77)
• Step 2: Create resources (p. 79)
• Step 3: Create GET methods (p. 80)
• Step 4: Create a Lambda function (p. 81)
• Step 5: Set up and test the methods (p. 82)
• Step 6: Deploy the API (p. 85)
• Step 7: Test the API (p. 85)
• Step 8: Clean up (p. 86)
In this step, you create four models. The first three models represent the data output formats for use
with the HTTP endpoint and the Lambda function. The last model represents the data input schema for
use with the Lambda function.
77
Amazon API Gateway Developer Guide
Build an API with HTTP integration
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PetsModelNoFlatten",
"type": "array",
"items": {
"type": "object",
"properties": {
"number": { "type": "integer" },
"class": { "type": "string" },
"salesPrice": { "type": "number" }
}
}
}
1. Choose Create.
2. For Model name, type PetsModelFlattenSome.
3. For Content type, type application/json.
4. For Model description, type Combines id and type into description, and changes
price to askingPrice.
5. For Model schema, type the following:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PetsModelFlattenSome",
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"askingPrice": { "type": "number" }
}
}
}
1. Choose Create.
2. For Model name, type PetsModelFlattenAll.
3. For Content type, type application/json.
4. For Model description, type Combines id, type, and price into a set of listings.
5. For Model schema, type the following:
{
"$schema": "http://json-schema.org/draft-04/schema#",
78
Amazon API Gateway Developer Guide
Build an API with HTTP integration
"title": "PetsModelFlattenAll",
"type": "object",
"properties": {
"listings": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
1. Choose Create.
2. For Model name, type PetsLambdaModel.
3. For Content type, type application/json.
4. For Model description, type GetPetsInfo model.
5. For Model schema, type the following:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PetsLambdaModel",
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"type": { "type": "string" },
"price": { "type": "number" }
}
}
}
In this step, you create four resources. The first three resources enable you to get the example data from
the HTTP endpoint in the three output formats. The last resource enables you to get the example data
from the Lambda function in the output schema that combines id and type into description and
renames price to askingPrice.
1. In the Resources pane, choose /petstorewalkthrough again, and then choose Create Resource.
2. For Resource Name, type FlattenSome.
79
Amazon API Gateway Developer Guide
Build an API with HTTP integration
3. For Resource Path, accept the default of /petstorewalkthrough/flattensome, and then choose
Create Resource.
1. In the Resources pane, choose /petstorewalkthrough again, and then choose Create Resource.
2. For Resource Name, type FlattenAll.
3. For Resource Path, accept the default of /petstorewalkthrough/flattenall, and then choose Create
Resource.
1. In the Resources pane, choose /petstorewalkthrough again, and then choose Create Resource.
2. For Resource Name, type LambdaFlattenSome.
3. For Resource Path, accept the default of /petstorewalkthrough/lambdaflattensome, and then
choose Create Resource.
In this step, you create a GET method for each of the resources you created in the previous step.
1. In the Resources list, choose /petstorewalkthrough/flattenall, and then choose Create Method.
2. From the drop-down list, choose GET, and then choose the check mark icon to save your choice.
3. In the Setup pane, choose HTTP for the Integration type and GET for HTTP method, type http://
petstore-demo-endpoint.execute-api.com/petstore/pets in Endpoint URL, and choose
Save.
1. In the Resources list, choose /petstorewalkthrough/flattensome, and then choose Create Method.
2. From the drop-down list, choose GET, and then choose the check mark icon to save your choice.
3. In the Setup pane, choose HTTP for the Integration type and GET for HTTP method, type http://
petstore-demo-endpoint.execute-api.com/petstore/pets in Endpoint URL, and then
choose Save.
1. In the Resources list, choose /petstorewalkthrough/noflatten, and then choose Actions, Create
Method.
80
Amazon API Gateway Developer Guide
Build an API with HTTP integration
2. From the drop-down list, choose GET, and then choose the check mark icon to save your choice.
3. In the Setup pane, choose HTTP for the Integration type and GET for HTTP method, type http://
petstore-demo-endpoint.execute-api.com/petstore/pets in Endpoint URL, and then
choose Save.
In this step, you create a Lambda function that returns the sample data.
console.log('Loading event');
Tip
In the preceding code, written in Node.js, console.log writes information to an Amazon
CloudWatch log. event contains the input to the Lambda function. context contains
calling context. callback returns the result. 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. For Handler name, leave the default of index.handler.
8. For Role, choose the Lambda execution role, APIGatewayLambdaExecRole, you created in the Build
an API Gateway REST API with Lambda integration (p. 30).
9. Choose Create Lambda function.
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 need it later.
12. In the pop-up list, choose Edit or test function.
13. For Sample event, replace any code that appears with the following:
Tip
The empty curly braces mean that 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.
81
Amazon API Gateway Developer Guide
Build an API with HTTP integration
In this step, you configure the method responses, integration requests, and integration responses to
specify the input and output data schemas (or models) for the GET methods associated with the HTTP
endpoint and the Lambda function. You also learn to test calling these methods using the API Gateway
console.
To set up the integration for the first GET method and then test it
1. From the API's Resources tree, choose GET under the /petstorewalkthrough/flattenall node.
2. In the Method Execution pane, choose Method Response, and then choose the arrow next to 200.
3. In the Response Models for 200 area, for application/json, choose the pencil icon to start setting
up the model for the method output. For Models, choose PetsModelFlattenAll, and then choose the
check mark icon to save the setting.
4. Choose Method Execution, choose Integration Response, and then choose the arrow next to 200.
5. Expand the Mapping Templates section, choose application/json under Content-Type.
6. For Generate template from model, choose PetsModelFlattenAll to display a mapping template
after the PetsModelFlattenAll model as a starting point.
7. Modify the mapping template code as follows:
#set($inputRoot = $input.path('$'))
{
"listings" : [
#foreach($elem in $inputRoot)
"Item number $elem.id is a $elem.type. The asking price is
$elem.price."#if($foreach.hasNext),#end
#end
]
}
8. Choose Save.
9. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If successful,
Response Body displays 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 set up integration for the second GET method and then test it
1. From the API's Resources tree, choose GET under the /petstorewalkthrough/lambdaflattensome
node.
2. In Method Execution, choose Method Response. And then choose the arrow next to 200 to expand
the section.
82
Amazon API Gateway Developer Guide
Build an API with HTTP integration
3. In the Response Models for 200 area, choose the pencil icon on the row for the content type of
application/json. Choose PetsModelFlattenSome for Models, and then choose the check mark icon
to save the choice.
4. Go back to Method Execution. Choose Integration Response, and then choose the arrow next to
200.
5. In the Mapping Templates section, choose application/json under Content-Type.
6. For Generate template, choose PetsModelFlattenSome to display the mapping script template for
the output of this method.
7. Modify the code as follows, and then choose Save:
#set($inputRoot = $input.path('$'))
[
#foreach($elem in $inputRoot)
{
"description" : "Item $elem.id is a $elem.type.",
"askingPrice" : $elem.price
}#if($foreach.hasNext),#end
#end
]
8. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If successful,
Response Body displays 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 set up integration for the third GET method and then test it
1. From the API's Resources tree, choose GET under the /petstorewalkthrough/flattensome node.
2. In the Method Execution pane, choose Method Response.
3. Choose the arrow next to 200.
4. In the Response Models for 200 area, for application/json, choose the pencil icon. For Models,
choose PetsModelFlattenSome, and then choose the check-mark icon to save the choice.
5. Go back to Method Execution and choose Integration Response.
6. Choose the arrow next to 200 to expand the section.
7. Expand the Mapping Templates area. Choose application/json for Content-Type. For Generate
template, choose PetsModelFlattenSome to display a mapping script template for the output of
this method.
8. Modify the code as follows:
#set($inputRoot = $input.path('$'))
[
83
Amazon API Gateway Developer Guide
Build an API with HTTP integration
#foreach($elem in $inputRoot)
{
"description": "Item $elem.id is a $elem.type.",
"askingPrice": $elem.price
}#if($foreach.hasNext),#end
#end
]
9. Choose Save.
10. Go back to Method Execution and choose TEST in the Client box. And then choose Test. If
successful, Response Body displays 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 set up integration for the fourth GET method and then test it
1. From the API's Resources tree, choose GET under the /petstorewalkthrough/noflatten node.
2. In the Method Execution pane, choose Method Response, and then expand the 200 section.
3. In the Response Models for 200 area, for application/json, choose the pencil icon to update the
response model for this method.
4. Choose PetsModelNoFlatten as the model for the content type of application/json, and then
choose the check-mark icon to save the choice.
5. Choose Method Execution, choose Integration Response, and then choose the arrow next to 200 to
expand the section.
6. Expand the Mapping Templates section. Choose application/json for Content-Type. For Generate
templates, choose PetsModelNoFlatten to display a mapping script template for the output of this
method.
7. 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
]
8. Choose Save.
9. Go back to Method Execution, and in the Client box, choose TEST, and then choose Test. If
successful, Response Body displays the following:
84
Amazon API Gateway Developer Guide
Build an API with HTTP integration
[
{
"number": 1,
"class": "dog",
"salesPrice": 249.99
},
{
"number": 2,
"class": "cat",
"salesPrice": 124.99
},
{
"number": 3,
"class": "fish",
"salesPrice": 0.99
}
]
In this step, you deploy the API so that you can begin calling it outside of the API Gateway console.
In this step, you go outside of the API Gateway console to interact with both the HTTP endpoint and the
Lambda function.
1. 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
https://my-api-id.execute-api.region-id.amazonaws.com/test/petstorewalkthrough/
noflatten
[
{
"number": 1,
"class": "dog",
"salesPrice": 249.99
},
{
"number": 2,
"class": "cat",
85
Amazon API Gateway Developer Guide
Build an API with HTTP integration
"salesPrice": 124.99
},
{
"number": 3,
"class": "fish",
"salesPrice": 0.99
}
]
[
{
"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
}
]
{
"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."
]
}
[
{
"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
}
]
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.
86
Amazon API Gateway Developer Guide
Tutorial: Build an API with private integration
Warning
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.
1. 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.
When a client calls the API, API Gateway connects to the Network Load Balancer through the pre-
configured VPC link. A VPC link is encapsulated by an API Gateway resource of VpcLink. It is responsible
for forwarding API method requests to the VPC resources and returns backend responses to the caller.
For an API developer, a VpcLink is functionally equivalent to an integration endpoint.
To create an API with private integration, you must create a new VpcLink, or choose an existing one,
that is connected to a Network Load Balancer that targets the desired VPC resources. You must have
appropriate permissions (p. 355) to create and manage a VpcLink. You then set up an API method and
integrate it with the VpcLink by setting either HTTP or HTTP_PROXY as the integration type, setting
VPC_LINK as the integration connection type, and setting the VpcLink identifier on the integration
connectionId.
Note
The Network Load Balancer and API must be owned by the same AWS account.
To quickly get started creating an API to access VPC resources, we walk through the essential steps for
building an API with the private integration, using the API Gateway console. Before creating the API, do
the following:
87
Amazon API Gateway Developer Guide
Tutorial: Build an API with private integration
1. Create a VPC resource, create or choose a Network Load Balancer under your account in the same
region, and add the EC2 instance hosting the resource as a target of the Network Load Balancer. For
more information, see Set up a Network Load Balancer for API Gateway private integrations (p. 355).
2. Grant permissions to create the VPC links for private integrations. For more information, see Grant
permissions to create a VPC link (p. 355).
After creating your VPC resource and your Network Load Balancer with your VPC resource configured in
its target groups, follow the instructions below to create an API and integrate it with the VPC resource
via a VpcLink in a private integration.
To create an API with private integration using the API Gateway console
a. From the primary navigation pane, choose VPC links and then choose Create.
b. Choose VPC link for REST APIs.
c. Enter a name, and optionally, a description for your VPC link.
d. Choose a Network Load Balancer from the Target NLB drop-down list.
You must have the Network Load Balancer already created in the same Region as your API for
the Network Load Balancer to be present in the list.
e. Choose Create to start creating the VPC link.
The initial response returns a VpcLink resource representation with the VPC link ID and a PENDING
status. This is because the operation is asynchronous and takes about 2-4 minutes to complete.
Upon successful completion, the status is AVAILABLE. In the meantime, you can proceed to create
the API.
3. Choose APIs from the primary navigation pane and then choose Create API to create a new API of
either an edge-optimized or regional endpoint type.
4. For the root resource (/), choose Create Method from the Actions drop-down menu, and then
choose GET.
5. In the / GET - Setup pane, initialize the API method integration as follows:
We will define the vpcLinkId stage variable after deploying the API to a stage and set its value
to the ID of the VpcLink created in Step 2.
e. Type a URL, for example, http://myApi.example.com, for Endpoint URL.
Here, the host name (for example, myApi.example.com) is used to set the Host header of the
integration request.
Note
For the Network Load Balancer (NLB), be sure to use the NLB DNS name as described in
Getting Started with Network Load Balancers.
f. Leave the Use Default Timeout selection as-is, unless you want to customize the integration
timeouts.
g. Choose Save to finish setting up the integration.
88
Amazon API Gateway Developer Guide
Tutorial: Build an API with AWS integration
With the proxy integration, the API is ready for deployment. Otherwise, you need to proceed to
set up appropriate method responses and integration responses.
h. From the Actions drop-down menu, choose Deploy API and then choose a new or existing stage
to deploy the API.
Note the resulting Invoke URL. You need it to invoke the API. Before doing that, you must set up
the vpcLinkId stage variable.
i. In the Stage Editor, choose the Stage Variables tab and choose Add Stage Variable.
Using the stage variable, you can easily switch to different VPC links for the API by
changing the stage variable value.
This completes creating the API. You can test invoking the API as with other integrations.
All AWS services support dedicated APIs to expose their features. However, the application protocols
or programming interfaces are likely to differ from service to service. An API Gateway API with the AWS
integration has the advantage of providing a consistent application protocol for your client to access
different AWS services.
In this walkthrough, we create an API to expose Amazon SNS. For more examples of integrating an API
with other AWS services, see Amazon API Gateway tutorials and workshops (p. 17).
Unlike the Lambda proxy integration, there is no corresponding proxy integration for other AWS services.
Hence, an API method is integrated with a single AWS action. For more flexibility, similar to the proxy
integration, you can set up a Lambda proxy integration. The Lambda function then parses and processes
requests for other AWS actions.
API Gateway does not retry when the endpoint times out. The API caller must implement retry logic to
handle endpoint timeouts.
This walkthrough builds on the instructions and concepts in Build an API Gateway REST API with Lambda
integration (p. 30).If you have not yet completed that walkthrough, we suggest that you do it first.
Topics
• Prerequisites (p. 90)
• Step 1: Create the resource (p. 90)
• Step 2: Create the GET method (p. 90)
• Step 3: Create the AWS service proxy execution role (p. 90)
89
Amazon API Gateway Developer Guide
Tutorial: Build an API with AWS integration
• Step 4: Specify method settings and test the method (p. 92)
• Step 5: Deploy the API (p. 92)
• Step 6: Test the API (p. 93)
• Step 7: Clean up (p. 93)
Prerequisites
Before you begin this walkthrough, do the following:
1. Complete the steps in Prerequisites for getting started with API Gateway (p. 12).
2. Ensure that the IAM user has access to create policies and roles in IAM. You need to create an IAM
policy and role in this walkthrough.
3. Create a new API named MyDemoAPI. For more information, see Tutorial: Build a REST API with
HTTP non-proxy integration (p. 59).
4. Deploy the API at least once to a stage named test. For more information, see Deploy the
API (p. 44) in Build an API Gateway REST API with Lambda integration (p. 30).
5. Complete the rest of the steps in Build an API Gateway REST API with Lambda integration (p. 30).
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.)
1. In the Resources pane, choose /mydemoawsproxy, and then choose Create Method.
2. For the HTTP method, choose GET, and then save your choice.
90
Amazon API Gateway Developer Guide
Tutorial: Build an API with AWS integration
To create the AWS service proxy execution role and its policy
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. Choose Policies.
3. Do one of the following:
• If the Welcome to Managed Policies page appears, choose Get Started, and then choose Create
Policy.
• If a list of policies appears, choose Create policy.
4. Choose JSON and then enter the following text.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": [
"*"
],
"Action": [
"sns:ListTopics"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
91
Amazon API Gateway Developer Guide
Tutorial: Build an API with AWS integration
}
]
}
For Role ARN, note of the Amazon Resource Name (ARN) for the execution role. You
need it later. The ARN should look similar to: arn:aws:iam::123456789012:role/
APIGatewayAWSProxyExecRole, where 123456789012 is your AWS account ID.
1. In the API Gateway console, in the Resources pane for the API named MyDemoAPI, in /
mydemoawsproxy, choose GET.
2. Choose Integration Request, and then choose AWS Service.
3. For AWS Region, choose the name of the AWS Region where you want to get the Amazon SNS
topics.
4. For AWS Service, choose SNS.
5. For HTTP method, choose GET.
6. For Action, enter ListTopics.
7. For Execution Role, enter the ARN for the execution role.
8. Leave Path Override blank.
9. Choose Save.
10. In the Method Execution pane, in the Client box, choose TEST, and then choose Test. If successful,
Response Body displays a response similar to the following:
{
"ListTopicsResponse": {
"ListTopicsResult": {
"NextToken": null,
"Topics": [
{
"TopicArn": "arn:aws:sns:us-east-1:80398EXAMPLE:MySNSTopic-1"
},
{
"TopicArn": "arn:aws:sns:us-east-1:80398EXAMPLE:MySNSTopic-2"
},
...
{
"TopicArn": "arn:aws:sns:us-east-1:80398EXAMPLE:MySNSTopic-N"
}
]
},
"ResponseMetadata": {
"RequestId": "abc1de23-45fa-6789-b0c1-d2e345fa6b78"
}
}
}
92
Amazon API Gateway Developer Guide
Tutorial: Build an API with AWS integration
1. 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.
3. Append /mydemoawsproxy so that it looks like this:
https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoawsproxy
{"ListTopicsResponse":{"ListTopicsResult":{"NextToken": null,"Topics":
[{"TopicArn": "arn:aws:sns:us-east-1:80398EXAMPLE:MySNSTopic-1"},{"TopicArn":
"arn:aws:sns:us-east-1:80398EXAMPLE:MySNSTopic-2"},...{"TopicArn":
"arn:aws:sns:us-east-1:80398EXAMPLE:MySNSTopic-N}]},"ResponseMetadata":
{"RequestId":"abc1de23-45fa-6789-b0c1-d2e345fa6b78}}}
Step 7: Clean up
You can delete the IAM resources the AWS service proxy needs to work.
Warning
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 Tutorial: Create a REST API as an Amazon S3 proxy in API Gateway (p. 113),
Tutorial: Create a Calc REST API with two AWS service integrations and one Lambda non-
proxy integration (p. 94), or Tutorial: Create a REST API as an Amazon Kinesis proxy in API
Gateway (p. 139).
93
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
In this tutorial, you'll create a Calc Lambda function that implements basic arithmetic operations,
accepting and returning JSON-formatted input and output. Then you'll create a REST API and integrate it
with the Lambda function in the following ways:
1. By exposing a GET method on the /calc resource to invoke the Lambda function, supplying the
input as query string parameters. (AWS Service integration)
2. By exposing a POST method on the /calc resource to invoke the Lambda function, supplying the
input in the method request payload. (AWS Service integration)
3. By exposing a GET on nested /calc/{operand1}/{operand2}/{operator} resources to invoke
the Lambda function, supplying the input as path parameters. (Lambda Function integration)
In addition to trying out this tutorial, you may wish to study the OpenAPI definition file (p. 109) for
the Calc API, which you can import into API Gateway by following the instructions in the section called
“OpenAPI” (p. 480).
Topics
• Create an AWS account (p. 94)
• Create an assumable IAM role (p. 95)
• Create a Calc Lambda function (p. 96)
• Test the Calc Lambda function (p. 96)
• Create a Calc API (p. 98)
• Integration 1: Create a GET method with query parameters to call the Lambda function (p. 99)
• Integration 2: Create a POST method with a JSON payload to call the Lambda function (p. 101)
• Integration 3: Create a GET method with path parameters to call the Lambda function (p. 103)
• OpenAPI definitions of sample API integrated with a Lambda function (p. 109)
If you do not have an AWS account, complete the following steps to create one.
1. Open https://portal.aws.amazon.com/billing/signup.
2. Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call and entering a verification code on the
phone keypad.
94
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
The role you create will need to have Lambda InvokeFunction permission. Otherwise, the API caller will
receive a 500 Internal Server Error response. To give the role this permission, you'll attach the
following IAM policy to it:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "*"
}
]
}
A new Create Policy console window will open up. In that window, do the following:
a. In the JSON tab, replace the existing policy with the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
95
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
"Resource": "*"
}
]
}
a. Under Attach permissions policies, choose your lambda_execute policy from the dropdown
list.
If you don't see your policy in the list, choose the refresh button at the top of the list. (Don't
refresh the browser page!)
b. Choose Next:Tags.
c. Choose Next:Review.
d. For the Role name, type a name such as lambda_invoke_function_assume_apigw_role.
e. Choose Create role.
9. Choose your lambda_invoke_function_assume_apigw_role from the list of roles.
10. Choose the Trust relationships tab.
11. Choose Edit trust relationship.
12. Replace the existing policy with the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com",
"apigateway.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
96
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
if (isNaN(event.a) || isNaN(event.b)) {
callback("400 Invalid Operand");
}
switch(event.op)
{
case "+":
case "add":
res.c = res.a + res.b;
break;
case "-":
case "sub":
res.c = res.a - res.b;
break;
case "*":
case "mul":
res.c = res.a * res.b;
break;
case "/":
case "div":
res.c = res.b===0 ? NaN : Number(event.a) / Number(event.b);
break;
default:
callback("400 Invalid Operator");
break;
}
callback(null, res);
};
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"
}
97
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
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:
{
"a": "Number",
"b": "Number",
"op": "String",
"c": "Number" | "String"
}
You should test the function in the Lambda console before integrating it with the API in the next step.
1. In the Saved test events dropdown menu, choose Configure test events.
2. For the test event name, enter calc2plus5.
3. Replace the test event definition with the following:
{
"a": "2",
"b": "5",
"op": "+"
}
4. Choose Save.
5. Choose Test.
6. Expand Execution result: succeeded. You should see the following:
{
"a": 2,
"b": 5,
"op": "+",
"c": 7
}
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
3. Under Create new API, choose New API.
98
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
1. In the API Gateway console, under your LambdaCalc API's Resources, choose /.
2. In the Actions drop-down menu, choose Create Resource.
3. For Resource Name, enter calc.
4. Choose Create Resource.
5. Choose the /calc resource you just created.
6. In the Actions drop-down menu, choose Create Method.
7. In the method drop-down menu that appears, choose GET.
8. Choose the checkmark icon to save your choice.
9. In the Set up pane:
Now you will set up query parameters for the GET method on /calc so it can receive input on behalf
of the backend Lambda function.
a. Choose the pencil icon next to Request Validator and choose Validate query string parameters
and headers from the drop-down menu. This setting will cause an error message to return to
state the required parameters are missing if the client does not specify them. You will not get
charged for the call to the backend.
99
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
{
"a": "$input.params('operand1')",
"b": "$input.params('operand2')",
"op": "$input.params('operator')"
}
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 backend Lambda function.
The transformed JSON object will be included as the integration request payload.
g. Choose Save.
12. Choose Method Execution.
13. You can now test your GET method to verify that it has been properly set up to invoke the Lambda
function:
100
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
To set up the POST method with a JSON payload to invoke a Lambda function
101
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
a. Choose Create in the Models pane. Type Input in Model name, type application/json in
Content type, and copy the following schema definition into the Model schema box:
{
"type":"object",
"properties":{
"a":{"type":"number"},
"b":{"type":"number"},
"op":{"type":"string"}
},
"title":"Input"
}
This model describes the input data structure and will be used to validate the incoming request
body.
b. Choose Create model.
c. Choose Create in the Models pane. Type Output in Model name, type application/json in
Content type, and copy the following schema definition into the Model schema box:
{
"type":"object",
"properties":{
"c":{"type":"number"}
},
"title":"Output"
}
This model describes the data structure of the calculated output from the backend. It can be
used to map the integration response data to a different model. This tutorial relies on the
passthrough behavior and does not use this model.
d. Locate the API ID for your API at the top of the console screen and make a note of it. It will
appear in parentheses after the API name.
e. In the Models pane, choose Create.
f. Type Result in Model name.
g. Type application/json in Content type.
h. Copy the following schema definition, where restapi-id is the REST API ID you noted earlier,
into the Model schema box:
{
"type":"object",
"properties":{
"input":{
"$ref":"https://apigateway.amazonaws.com/restapis/restapi-id/models/
Input"
},
"output":{
102
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
"$ref":"https://apigateway.amazonaws.com/restapis/restapi-id/models/
Output"
}
},
"title":"Output"
}
This model describes the data structure of the returned response data. It references both the
Input and Output schemas defined in the specified API (restapi-id). Again, this model is not
used in this tutorial because it leverages the passthrough behavior.
i. Choose Create model.
10. In the main navigation pane, under your LambdaCalc API, choose Resources.
11. In the Resources pane, choose the POST method for your API.
12. Choose Method Request.
13. In the Method Request configuration settings, do the following to enable request validation on the
incoming request body:
a. Choose the pencil icon next to Request Validator to choose Validate body. Choose the
checkmark icon to save your choice.
b. Expand the Request Body section, choose Add model
c. Type application/json in the Content-Type input field and choose Input from the drop-
down list in the Model name column. Choose the checkmark icon to save your choice.
14. To test your POST method, do the following:
{
"a": 1,
"b": 2,
"op": "+"
}
{
"a": 1,
"b": 2,
"op": "+",
"c": 3
}
103
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
You'll use a mapping template to map the incoming path parameter values to the required integration
request payload.
This time you'll use the built-in Lambda integration support in the API Gateway console to set up the
method integration.
104
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
{
"a": "$input.params('operand1')",
"b": "$input.params('operand2')",
"op":
#if($input.params('operator')=='%2F')"/"#{else}"$input.params('operator')"#end
This template maps the three URL path parameters, declared when the /calc/{operand1}/
{operand2}/{operator} resource was created, into designated property values in the JSON
object. Because URL paths must be URL-encoded, the division operator must be specified as
%2F instead of /. This template translates the %2F into '/' before passing it to the Lambda
function.
g. Choose Save.
When the method is set up correctly, the settings should look more or less like this:
105
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
106
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
This test result shows the original output from the backend Lambda function, as passed through the
integration response without mapping, because there is no mapping template. Next, you'll model
the data structure of the method response payload after the Result schema.
28. By default, the method response body is assigned an empty model. This will cause the integration
response body to be passed through without mapping. However, when you generate an SDK for one
of the strongly-type languages, such as Java or Objective-C, your SDK users will receive an empty
object as the result. To ensure that both the REST client and SDK clients receive the desired result,
you must model the response data using a predefined schema. Here you'll define a model for the
method response body and to construct a mapping template to translate the integration response
body into the method response body.
a. Choose /calc/{operand1}/{operand2}/{operator}.
b. Choose GET.
c. Choose Method Execution.
d. Choose Method Response.
e. Expand the 200 response,
107
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
f. Under Response Body for 200, choose the pencil icon next to the model for the application/
json content type.
g. From the Models drop-down list, choose Result.
h. Choose the checkmark icon to save your choice.
Setting the model for the method response body ensures that the response data will be cast into
the Result object of a given SDK. To make sure that the integration response data is mapped
accordingly, you'll need a mapping template.
29. To create the mapping template, do the following:
#set($inputRoot = $input.path('$'))
{
"input" : {
"a" : $inputRoot.a,
"b" : $inputRoot.b,
"op" : "$inputRoot.op"
},
"output" : {
"c" : $inputRoot.c
}
}
g. Choose Save.
30. To test the mapping template, do the following:
The integration response from the Lambda function is now mapped to a Result object.
d. Choose Test, and you'll see the following under Response Body in the console:
{
"input": {
"a": 1,
"b": 2,
"op": "+"
},
"output": {
"c": 3
}
}
31. At this point the API can be called only via Test Invoke in the API Gateway console. To make it
available to clients, you'll need to deploy it as follows:
108
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
Note
Always be sure to redeploy your API whenever you add, modify, or delete a resource or method,
update a data mapping, or update stage settings. Otherwise, new features or updates will not
be available to clients of your API.
{
"swagger": "2.0",
"info": {
"version": "2017-04-20T04:08:08Z",
"title": "LambdaCalc"
},
"host": "uojnr9hd57.execute-api.us-east-1.amazonaws.com",
"basePath": "/test",
"schemes": [
"https"
],
"paths": {
"/calc": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "operand2",
"in": "query",
"required": true,
"type": "string"
},
{
"name": "operator",
"in": "query",
"required": true,
"type": "string"
},
{
"name": "operand1",
"in": "query",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
109
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
"$ref": "#/definitions/Result"
},
"headers": {
"operand_1": {
"type": "string"
},
"operand_2": {
"type": "string"
},
"operator": {
"type": "string"
}
}
}
},
"x-amazon-apigateway-request-validator": "Validate query string parameters and
headers",
"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 \"a\" : \"$res.a\",\n \"b\" : \"$res.b\",\n
\"op\" : \"$res.op\",\n \"c\" : \"$res.c\"\n}"
}
}
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"requestTemplates": {
"application/json": "{\n \"a\": \"$input.params('operand1')\",\n \"b
\": \"$input.params('operand2')\", \n \"op\": \"$input.params('operator')\" \n}"
},
"type": "aws"
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "Input",
"required": true,
"schema": {
"$ref": "#/definitions/Input"
}
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
110
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
"$ref": "#/definitions/Result"
}
}
},
"x-amazon-apigateway-request-validator": "Validate body",
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200",
"responseTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n \"a
\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : $inputRoot.op,\n \"c\" :
$inputRoot.c\n}"
}
}
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"passthroughBehavior": "when_no_templates",
"httpMethod": "POST",
"type": "aws"
}
}
},
"/calc/{operand1}/{operand2}/{operator}": {
"get": {
"consumes": [
"application/json"
],
"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/Result"
}
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"default": {
"statusCode": "200",
111
Amazon API Gateway Developer Guide
Tutorial: Calc API with three integrations
"responseTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n
\"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" :
\"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\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",
"passthroughBehavior": "when_no_templates",
"httpMethod": "POST",
"requestTemplates": {
"application/json": "{\n \"a\": \"$input.params('operand1')\",\n \"b\":
\"$input.params('operand2')\",\n \"op\": #if($input.params('operator')=='%2F')\"/
\"#{else}\"$input.params('operator')\"#end\n \n}"
},
"contentHandling": "CONVERT_TO_TEXT",
"type": "aws"
}
}
}
},
"definitions": {
"Input": {
"type": "object",
"required": [
"a",
"b",
"op"
],
"properties": {
"a": {
"type": "number"
},
"b": {
"type": "number"
},
"op": {
"type": "string",
"description": "binary op of ['+', 'add', '-', 'sub', '*', 'mul', '%2F',
'div']"
}
},
"title": "Input"
},
"Output": {
"type": "object",
"properties": {
"c": {
"type": "number"
}
},
"title": "Output"
},
"Result": {
"type": "object",
"properties": {
"input": {
"$ref": "#/definitions/Input"
},
"output": {
"$ref": "#/definitions/Output"
}
},
"title": "Result"
}
112
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
},
"x-amazon-apigateway-request-validators": {
"Validate body": {
"validateRequestParameters": false,
"validateRequestBody": true
},
"Validate query string parameters and headers": {
"validateRequestParameters": true,
"validateRequestBody": false
}
}
}
• Expose GET on the API's root resource to list all of the Amazon S3 buckets of a caller.
• Expose GET on a Folder resource to view a list of all of the objects in an Amazon S3 bucket.
• Expose PUT on a Folder resource to add a bucket to Amazon S3.
• Expose DELETE on a Folder resource to remove a bucket from Amazon S3.
• Expose GET on a Folder/Item resource to view or download an object from an Amazon S3 bucket.
• Expose PUT on a Folder/Item resource to upload an object to an Amazon S3 bucket.
• Expose HEAD on a Folder/Item resource to get object metadata in an Amazon S3 bucket.
• Expose DELETE on a Folder/Item resource to remove an object from an Amazon S3 bucket.
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 Amazon API
Gateway Endpoints and Quotas.
You may want to import the sample API as an Amazon S3 proxy, as shown in OpenAPI definitions of
the sample API as an Amazon S3 proxy (p. 130). For instructions on how to import an API using the
OpenAPI definition, see Configuring a REST API using OpenAPI (p. 480).
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, complete the following steps to create one.
1. Open https://portal.aws.amazon.com/billing/signup.
2. Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call and entering a verification code on the
phone keypad.
Topics
• Set up IAM permissions for the API to invoke Amazon S3 actions (p. 114)
• Create API resources to represent Amazon S3 resources (p. 115)
113
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
• Expose an API method to list the caller's Amazon S3 buckets (p. 116)
• Expose API methods to access an Amazon S3 bucket (p. 122)
• Expose API methods to access an Amazon S3 object in a bucket (p. 125)
• Call the API using a REST API client (p. 128)
• OpenAPI definitions of the sample API as an Amazon S3 proxy (p. 130)
For your API to view or list Amazon S3 buckets and objects, you can use the IAM-
provided AmazonS3ReadOnlyAccess policy in the IAM role. The ARN of this policy is
arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess, which is as shown as follows:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": "*"
}
]
}
This policy document states that any of the Amazon S3 Get* and List* actions can be invoked on any
of the Amazon S3 resources.
For your API to update Amazon S3 buckets and objects , you can use a custom policy for any of the
Amazon S3 Put* actions as shown as follows:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:Put*",
"Resource": "*"
}
]
}
For your API to work with Amazon S3 Get*, List* and Put* actions, you can add the above read-only
and put-only policies to the IAM role.
For your API to invoke the Amazon S3 Post* actions, you must use an Allow policy for the s3:Post*
actions in the IAM role. For a complete list of Amazon S3 actions, see Specifying Amazon S3 Permissions
in a Policy.
For your API to create, view, update, and delete buckets and objects in Amazon S3, you can use the
IAM -provided AmazonS3FullAccess policy in the IAM role. The ARN is arn:aws:iam::aws:policy/
AmazonS3FullAccess.
114
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:*",
"Resource": "*"
}
]
}
Having chosen the desired IAM policies to use, create an IAM role and attach to it the policies. The
resulting IAM role must contain the following trust policy for API Gateway to assume this role at runtime.
{
"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.
1. In the API Gateway console, create an API named MyS3. This API's root resource (/) represents the
Amazon S3 service.
2. Under the API's root resource, create a child resource named Folder and set the required Resource
Path as /{folder}.
3. For the API's Folder resource, create an Item child resource. Set the required Resource Path as /
{item}.
115
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
1. Choose Create method on the root node (/) from the Actions drop-down menu at the top-right
corner of the Resources panel.
2. Choose the GET from the drop-down list of HTTP verbs, and choose the check-mark icon to start
creating the method.
3. In the / - GET - Setup pane, choose AWS Service for Integration type.
4. From the list, choose a region (e.g., us-west-2) for AWS Region.
5. From AWS Service, choose S3.
6. For AWS Subdomain, leave it blank.
7. From HTTP method, choose GET.
8. For Action Type, choose Use path override. With path override, API Gateway forwards the client
request to Amazon S3 as the corresponding Amazon S3 REST API path-style request, in which a
116
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
This setup integrates the frontend GET https://your-api-host/stage/ request with the backend
GET https://your-s3-host/.
Note
After the initial setup, you can modify these settings in the Integration Request page of the
method.
To control who can call this method of our API, we turn on the method authorization flag and set it to
AWS_IAM.
For our API to return successful responses and exceptions properly to the caller, let us declare the 200,
400 and 500 responses in Method Response. We use the default mapping for 200 responses so that
backend responses of the status code not declared here will be returned to the caller as 200 ones.
1. From the Method Execution pane, choose the Method Response box. The API Gateway declares the
200 response by default.
117
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
2. Choose Add response, enter 400 in the input text box, and choose the check-mark to finish the
declaration.
3. Repeat the above step to declare the 500 response type. The final setting is shown as follows:
Because the successful integration response from Amazon S3 returns the bucket list as an XML payload
and the default method response from API Gateway returns a JSON payload, we must map the backend
Content-Type header parameter value to the frontend counterpart. Otherwise, the client will receive
application/json for the content type when the response body is actually an XML string. The
following procedure shows how to set this up. In addition, we also want to display to the client other
header parameters, such as Date and Content-Length.
1. In the API Gateway console, choose Method Response. Add the Content-Type header for the 200
response type.
118
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
119
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
With the above header mappings, API Gateway will translate the Date header from the backend to
the Timestamp header for the client.
3. Still in Integration Response, choose Add integration response, type an appropriate regular
expression in the HTTP status regex text box for a remaining method response status. Repeat until
all the method response status are covered.
120
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
121
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
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.
1. On the /{folder} node from the Resources tree, create the DELETE, GET and PUT methods, one at a
time.
2. Set up the initial integration of each created method with its corresponding Amazon S3 endpoints.
The following screen shot illustrates this setting for the PUT /{folder} method. For the
DELETE /{folder} and GET /{folder} method, replace the PUT value of HTTP method by
DELETE and GET, respectively.
122
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
Notice that we used the {bucket} path parameter in the Amazon S3 endpoint URLs to specify
the bucket. We will need to map the {folder} path parameter of the method requests to the
{bucket} path parameter of the integration requests.
3. To map {folder} to {bucket}:
4. In Method Request, add the Content-Type to the HTTP Request Headers section.
123
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
This is mostly needed for testing, when using the API Gateway console, when you must specify
application/xml for an XML payload.
5. In Integration Request, set up a mapping for the Content-Type header to
method.request.header.Content-Type, following the instructions in Expose an API method to
list the caller's Amazon S3 buckets (p. 116).
6. To test the PUT method, choose Test in the Client box from Method Execution, and enter the
following as input to the testing:
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<LocationConstraint>{region}</LocationConstraint>
</CreateBucketConfiguration>
7. Repeat the preceding steps to create and configure the GET and DELETE method on the API's /
{folder} resource.
124
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
The above examples illustrate how to create a new bucket in the specified region, to view the list of
objects in the bucket, and to delete the bucket. Other Amazon S3 bucket operations allow you work
with the metadata or properties of the bucket. For example, you can set up your API to call the Amazon
S3's PUT /?notification action to set up notifications on the bucket, to call PUT /?acl to set an access
control list on the bucket, etc. The API set up is similar, except for that you must append appropriate
query parameters to the Amazon S3 endpoint URLs. At run time, you must provide the appropriate
XML payload to the method request. The same can be said about supporting the other GET and DELETE
operations on a Amazon S3 bucket. For more information on possible Amazon S3 actions on a bucket,
see Amazon S3 Operations on Buckets.
In this tutorial, we expose the PUT Object operation, the GET Object operation, HEAD Object operation,
and the DELETE Object operation through the API methods of PUT /{folder}/{item}, GET /
{folder}/{item}, HEAD /{folder}/{item} and DELETE /{folder}/{item}, respectively.
The API setups for the PUT, GET and DELETE methods on /{folder}/{item} are the similar to those
on /{folder}, as prescribed in Expose API methods to access an Amazon S3 bucket (p. 122). One
major difference is that the object-related request path has an additional path parameter of {item} and
this path parameter must be mapped to the integration request path parameter of {object}.
125
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
As an illustration, the following screen shot shows the output when testing the GET method on a
{folder}/{item} resource using the API Gateway console. The request correctly returns the plain text
of ("Welcome to README.txt") as the content of the specified file (README.txt) in the given Amazon S3
bucket (apig-demo).
126
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
To download or upload binary files, which in API Gateway is considered any thing other than utf-8
encoded JSON content, additional API settings are necessary. This is outlined as follows:
1. Register the media types of the affected file to the API's binaryMediaTypes. You can do this in the
console:
127
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
The payload size limit is 10 MB. See API Gateway quotas for configuring and running a REST
API (p. 816).
Make sure that files on Amazon S3 have the correct content types added as the files' metadata. For
streamable media content, Content-Disposition:inline may also need to be added to the
metadata.
For more information about the binary support in API Gateway, see Content type conversions in API
Gateway (p. 437).
1. Deploy or redeploy the API. Make a note of the base URL of the API that is displayed next to Invoke
URL at the top of the Stage Editor.
2. Launch Postman.
3. Choose Authorization and then choose AWS Signature. Type your IAM user's Access Key ID and
Secret Access Key into the AccessKey and SecretKeyinput fields, respectively. Type the AWS region
to which your API is deployed in the AWS Region text box. Type execute-api in the Service Name
input field.
You can create a pair of the keys from the Security Credentials tab from your IAM user account in
the IAM Management Console.
4. To add a bucket named apig-demo-5 to your Amazon S3 account in the {region} region:
Note
Be sure that the bucket name must be globally unique.
a. Choose PUT from the drop-down method list and type the method URL (https://api-
id.execute-api.aws-region.amazonaws.com/stage/folder-name
b. Set the Content-Type header value as application/xml. You may need to delete any
existing headers before setting the content type.
c. Choose Body menu item and type the following XML fragment as the request body:
<CreateBucketConfiguration>
<LocationConstraint>{region}</LocationConstraint>
</CreateBucketConfiguration>
d. Choose Send to submit the request. If successful, you should receive a 200 OK response with an
empty payload.
5. To add a text file to a bucket, follow the instructions above. If you specify a bucket name of apig-
demo-5 for {folder} and a file name of Readme.txt for {item} in the URL and provide a text
string of Hello, World! as the file contents (thereby making it the request payload), the request
becomes
128
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
Postman-Token: 6135d315-9cc4-8af8-1757-90871d00847e
Hello, World!
If everything goes well, you should receive a 200 OK response with an empty payload.
6. To get the content of the Readme.txt file we just added to the apig-demo-5 bucket, do a GET
request like the following one:
If successful, you should receive a 200 OK response with the Hello, World! text string as the
payload.
7. To list items in the apig-demo-5 bucket, submit the following request:
If successful, you should receive a 200 OK response with an XML payload showing a single item in
the specified bucket, unless you added more files to the bucket before submitting this request.
Note
To upload or download an image, you need to set content handling to CONVERT_TO_BINARY.
129
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-10-13T23:04:43Z",
"title": "MyS3"
},
"host": "9gn28ca086.execute-api.{region}.amazonaws.com",
"basePath": "/S3",
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Length": {
"type": "string"
},
"Timestamp": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
130
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
"method.response.header.Content-Type":
"integration.response.header.Content-Type",
"method.response.header.Content-Length":
"integration.response.header.Content-Length",
"method.response.header.Timestamp": "integration.response.header.Date"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"uri": "arn:aws:apigateway:us-west-2:s3:path//",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "aws"
}
}
},
"/{folder}": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Length": {
"type": "string"
},
"Date": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
131
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type",
"method.response.header.Date": "integration.response.header.Date",
"method.response.header.Content-Length":
"integration.response.header.content-length"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.bucket": "method.request.path.folder"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "aws"
}
},
"put": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": false,
"type": "string"
},
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Length": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
132
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type",
"method.response.header.Content-Length":
"integration.response.header.Content-Length"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.bucket": "method.request.path.folder",
"integration.request.header.Content-Type": "method.request.header.Content-
Type"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}",
"passthroughBehavior": "when_no_match",
"httpMethod": "PUT",
"type": "aws"
}
},
"delete": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Date": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
133
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type",
"method.response.header.Date": "integration.response.header.Date"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.bucket": "method.request.path.folder"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}",
"passthroughBehavior": "when_no_match",
"httpMethod": "DELETE",
"type": "aws"
}
}
},
"/{folder}/{item}": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "item",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"content-type": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
134
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.content-type":
"integration.response.header.content-type",
"method.response.header.Content-Type":
"integration.response.header.Content-Type"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.object": "method.request.path.item",
"integration.request.path.bucket": "method.request.path.folder"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}/{object}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "aws"
}
},
"head": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "item",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
135
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
},
"headers": {
"Content-Length": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type",
"method.response.header.Content-Length":
"integration.response.header.Content-Length"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.object": "method.request.path.item",
"integration.request.path.bucket": "method.request.path.folder"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}/{object}",
"passthroughBehavior": "when_no_match",
"httpMethod": "HEAD",
"type": "aws"
}
},
"put": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": false,
"type": "string"
},
{
"name": "item",
"in": "path",
"required": true,
136
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
"type": "string"
},
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Length": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type",
"method.response.header.Content-Length":
"integration.response.header.Content-Length"
}
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.object": "method.request.path.item",
"integration.request.path.bucket": "method.request.path.folder",
"integration.request.header.Content-Type": "method.request.header.Content-
Type"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}/{object}",
"passthroughBehavior": "when_no_match",
"httpMethod": "PUT",
"type": "aws"
}
137
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an
Amazon S3 proxy in API Gateway
},
"delete": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "item",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "folder",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Content-Length": {
"type": "string"
},
"Content-Type": {
"type": "string"
}
}
},
"400": {
"description": "400 response"
},
"500": {
"description": "500 response"
}
},
"security": [
{
"sigv4": []
}
],
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"responses": {
"4\\d{2}": {
"statusCode": "400"
},
"default": {
"statusCode": "200"
},
"5\\d{2}": {
"statusCode": "500"
}
},
"requestParameters": {
"integration.request.path.object": "method.request.path.item",
"integration.request.path.bucket": "method.request.path.folder"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{bucket}/{object}",
"passthroughBehavior": "when_no_match",
"httpMethod": "DELETE",
138
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"type": "aws"
}
}
}
},
"securityDefinitions": {
"sigv4": {
"type": "apiKey",
"name": "Authorization",
"in": "header",
"x-amazon-apigateway-authtype": "awsSigv4"
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
For the purpose of illustration, we create an example API to enable a client to do the following:
To accomplish the preceding tasks, the API exposes methods on various resources to invoke the
following, respectively:
• Expose an HTTP GET method on the API's /streams resource and integrate the method with the
ListStreams action in 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 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 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 Kinesis to delete a stream in the caller's account.
139
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
You can apply the instructions presented here to other Kinesis actions. For the complete list of the
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 the API Gateway Import API. For information on how to use the Import API, see
Configuring a REST API using OpenAPI (p. 480).
If you do not have an AWS account, complete the following steps to create one.
1. Open https://portal.aws.amazon.com/billing/signup.
2. Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call and entering a verification code on the
phone keypad.
Create an IAM role and policy for the API to access Kinesis
To allow the API to invoke Kinesis actions, you must have appropriate IAM policies attached to an IAM
role. This section explains how to verify and to create, if necessary, the required IAM role and policies.
To enable read-only access to Kinesis, you can use the AmazonKinesisReadOnlyAccess policy that allows
the Get*, List*, and Describe* actions in Kinesis to be invoked.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:Get*",
"kinesis:List*",
"kinesis:Describe*"
],
"Resource": "*"
}
]
}
140
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
To enable read-write actions in Kinesis, you can use the AmazonKinesisFullAccess policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "kinesis:*",
"Resource": "*"
}
]
}
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.
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
3. Choose New API.
4. In API name, enter KinesisProxy. Leave the default values in the other fields.
141
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
After the API is created, the API Gateway console displays the Resources page, which contains only the
API's root (/) resource.
{
...
}
In the above REST API request, the action is specified in the Action query parameter. Alternatively, you
can specify the action in a X-Amz-Target header, instead:
POST / HTTP/1.1
Host: kinesis.<region>.<domain>
Content-Length: <PayloadSizeBytes>
User-Agent: <UserAgentString>
Content-Type: application/x-amz-json-1.1
Authorization: <AuthParams>
X-Amz-Date: <Date>
X-Amz-Target: Kinesis_20131202.ListStreams
{
...
}
To expose a Kinesis action in the API, add a /streams resource to the API's root. Then set a GET method
on the resource and integrate the method with the ListStreams action of Kinesis.
The following procedure describes how to list Kinesis streams by using the API Gateway console.
In Resource Name, type Streams, leave Resource Path and other fields as the default, and choose
Create Resource.
2. Choose the /Streams resource. From Actions, choose Create Method, choose GET from the list, and
then choose the check mark icon to finish creating the method.
Note
The HTTP verb for a method invoked by a client may differ from the HTTP verb for an
integration required by the backend. We chose GET here, because listing streams is
intuitively a READ operation.
3. In the method's Setup pane, choose AWS Service.
142
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
4. Still in the Integration Request pane, expand the HTTP Headers section:
143
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
We used a request parameter mapping to set the Content-Type header to the static value of
'application/x-amz-json-1.1' to inform Kinesis that the input is of a specific version of JSON.
5. Expand the Mapping Templates section:
{
"ExclusiveStartStreamName": "string",
"Limit": number
}
However, the properties are optional. To use the default values, we opted for an empty JSON
payload here.
144
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
6. Test the GET method on the Streams resource to invoke the ListStreams action in Kinesis:
From the API Gateway console, select the /streams/GET entry from the Resources pane, choose the
Test invocation option, and then choose Test.
145
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
If you already created two streams named "myStream" and "yourStream" in Kinesis, the successful
test returns a 200 OK response containing the following payload:
{
"HasMoreStreams": false,
"StreamNames": [
"myStream",
"yourStream"
]
}
{
"ShardCount": number,
"StreamName": "string"
}
{
"StreamName": "string"
}
{
"StreamName":"string"
}
We can build the 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
146
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
between method and integration requests, and method and integration responses, we create our API
somewhat differently.
We expose the GET, POST, and Delete HTTP methods on a to-be-named Stream resource. We use
the {stream-name} path variable as the placeholder of the stream resource and integrate these API
methods with the 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. We provide mapping templates to transform the data to the required integration
request payload.
1. Create a child resource with the {stream-name} path variable under the previously created /
streams resource.
2. Add the POST, GET, and DELETE HTTP verbs to this resource.
After the methods are created on the resource, the structure of the API looks like the following:
147
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
148
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
Content-Type: 'x-amz-json-1.1'
The task follows the same procedure to set up the request parameter mapping for the GET /
streams method.
5. Add the following body mapping template to map data from the GET /streams/{stream-name}
method request to the POST /?Action=DescribeStream integration request:
{
"StreamName": "$input.params('stream-name')"
}
This mapping template generates the required integration request payload for the
DescribeStream action of Kinesis from the method request's stream-name path parameter value.
6. Test the GET /stream/{stream-name} method to invoke the DescribeStream action in 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 Kinesis stream in the Path field for stream-name,
149
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
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"
},
"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
Content-Type: 'x-amz-json-1.1'
150
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
The task follows the same procedure to set up the request parameter mapping for the GET /
streams method.
3. Add the following body mapping template to map data from the POST /streams/{stream-
name} method request to the POST /?Action=CreateStream integration request:
{
"ShardCount": #if($input.path('$.ShardCount') == '') 5 #else
$input.path('$.ShardCount') #end,
"StreamName": "$input.params('stream-name')"
}
In the preceding mapping template, we set ShardCount to a fixed value of 5 if the client does not
specify a value in the method request payload.
4. Test the POST /streams/{stream-name} method to create a named stream in Kinesis:
From the API Gateway console, select /streams/{stream-name}/POST in the Resources pane,
choose Test to start testing, enter the name of a new Kinesis stream in Path for stream-name, and
choose Test. If the test is successful, a 200 OK response is returned with no data.
After you deploy the API, you can also make a REST API request against the POST method on a
Stream resource to invoke the CreateStream action in Kinesis:
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
}
Content-Type: 'x-amz-json-1.1'
The task follows the same procedure to set up the request parameter mapping for the GET /
streams method.
3. Add the following body mapping template to map data from the DELETE /streams/
{stream-name} method request to the corresponding integration request of POST /?
Action=DeleteStream :
{
"StreamName": "$input.params('stream-name')"
}
151
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
This mapping template generates the required input for the DELETE /streams/{stream-name}
action from the client-supplied URL path name of stream-name.
4. Test the DELETE method to delete a named stream in Kinesis:
From the API Gateway console, select the /streams/{stream-name}/DELETE method node in the
Resources pane, choose Test to start testing, type the name of an existing Kinesis stream in Path for
stream-name, and choose Test. If the test is successful, a 200 OK response is returned with no data.
After you deploy the API, you can also make the following REST API request against the DELETE
method on the Stream resource to call the DeleteStream action in Kinesis:
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
{}
{
"Records": [
{
"Data": blob,
"ExplicitHashKey": "string",
"PartitionKey": "string"
}
],
"StreamName": "string"
}
or
152
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
{
"Data": blob,
"ExplicitHashKey": "string",
"PartitionKey": "string",
"SequenceNumberForOrdering": "string",
"StreamName": "string"
}
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.
{
"ShardIterator": "string",
"Limit": number
}
Here, the source stream from which we are getting records is specified in the required ShardIterator
value, as is shown in the following Kinesis action to obtain a shard iterator:
{
"ShardId": "string",
"ShardIteratorType": "string",
"StartingSequenceNumber": "string",
"StreamName": "string"
}
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:
153
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
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.
154
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
2. Add the following request parameter mapping to set the Content-Type header to an AWS-
compliant version of JSON in the integration request:
Content-Type: 'x-amz-json-1.1'
The task follows the same procedure to set up the request parameter mapping for the GET /
streams method.
3. Add the following body mapping template to map data from the PUT /streams/{stream-
name}/record method request to the corresponding integration request of POST /?
Action=PutRecord :
{
"StreamName": "$input.params('stream-name')",
"Data": "$util.base64Encode($input.json('$.Data'))",
"PartitionKey": "$input.path('$.PartitionKey')"
}
This mapping template assumes that the method request payload is of the following format:
{
"Data": "some data",
"PartitionKey": "some key"
}
155
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PutRecord proxy single-record payload",
"type": "object",
"properties": {
"Data": { "type": "string" },
"PartitionKey": { "type": "string" }
}
}
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.
4. To test the PUT /streams/{stream-name}/record method, set the stream-name path variable
to the name of an existing stream, supply a payload of the required 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"
}
156
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
2. Add the following request parameter mapping to set the Content-Type header to an AWS-
compliant version of JSON in the integration request:
Content-Type: 'x-amz-json-1.1'
The task follows the same procedure to set up the request parameter mapping for the GET /
streams method.
3. Add the following body mapping template to map data from the PUT /streams/{stream-
name}/records method request to the corresponding integration request of POST /?
Action=PutRecords :
{
"StreamName": "$input.params('stream-name')",
"Records": [
#foreach($elem in $input.path('$.records'))
{
"Data": "$util.base64Encode($elem.data)",
"PartitionKey": "$elem.partition-key"
}#if($foreach.hasNext),#end
#end
]
}
157
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
This mapping template assumes that the method request payload can be modelled by the 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" }
}
}
}
}
}
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.
In this tutorial, we used two slightly different payload formats to illustrate that an API developer
can choose to expose the backend data format to the client or hide it from the client. One format
is for the PUT /streams/{stream-name}/records method (above). Another format is used for
the PUT /streams/{stream-name}/record method (in the previous procedure). In production
environment, you should keep both formats consistent.
4.
To test the PUT /streams/{stream-name}/records method, set the stream-name path
variable to an existing stream, supply the following payload, and submit the method request.
{
"records": [
{
"data": "some data",
"partition-key": "some key"
},
{
"data": "some other data",
"partition-key": "some key"
}
]
}
The successful result is a 200 OK response with a payload similar to the following output:
{
"FailedRecordCount": 0,
"Records": [
{
"SequenceNumber": "49559409944537880850133345460167468741933742152373764162",
"ShardId": "shardId-000000000004"
},
{
"SequenceNumber": "49559409944537880850133345460168677667753356781548470338",
"ShardId": "shardId-000000000004"
158
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
}
]
}
2.
The GetShardIterator action requires an input of a ShardId value. To pass a client-supplied
ShardId value, we add a shard-id query parameter to the method request, as shown in the
following:
159
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
In the following body-mapping template, we set the shard-id query parameter value to the
ShardId property value of the JSON payload as the input to the GetShardIterator action in
Kinesis.
3. Configure the body mapping template to generate the required input (ShardId and StreamName)
to the GetShardIterator action from the shard-id and stream-name parameters of
the method request. In addition, the mapping template also sets ShardIteratorType to
TRIM_HORIZON as a default.
{
"ShardId": "$input.params('shard-id')",
"ShardIteratorType": "TRIM_HORIZON",
"StreamName": "$input.params('stream-name')"
}
4. Using the Test option in the API Gateway console, enter an existing stream name as the stream-
name Path variable value, set the shard-id Query string to an existing ShardId value (e.g.,
shard-000000000004), and choose Test.
160
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
{
"ShardIterator": "AAAAAAAAAAFYVN3VlFy..."
}
Make note of the ShardIterator value. You need it to get records from a stream.
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:
161
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
3. Set up the following mapping template to map the Shard-Iterator header parameter value to
the ShardIterator property value of the JSON payload for the GetRecords action in Kinesis.
{
"ShardIterator": "$input.params('Shard-Iterator')"
}
4. Using the Test option in the API Gateway console, type an existing stream name as the stream-
name Path variable value, set the Shard-Iterator Header to the ShardIterator value obtained
from the test run of the GET /streams/{stream-name}/sharditerator method (above), and
choose Test.
{
"MillisBehindLatest": 0,
"NextShardIterator": "AAAAAAAAAAF...",
"Records": [ ... ]
}
162
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"title": "KinesisProxy",
"version": "2016-03-31T18:25:32Z"
},
"paths": {
"/streams/{stream-name}/sharditerator": {
"get": {
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "shard-id",
"in": "query",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetShardIterator",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"ShardId\": \"$input.params('shard-
id')\",\n \"ShardIteratorType\": \"TRIM_HORIZON\",\n \"StreamName\":
\"$input.params('stream-name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
"/streams/{stream-name}/records": {
"get": {
"parameters": [
163
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
{
"name": "stream-name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "Shard-Iterator",
"in": "header",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetRecords",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"ShardIterator\": \"$input.params('Shard-
Iterator')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
},
"put": {
"parameters": [
{
"name": "Content-Type",
"in": "header",
"schema": {
"type": "string"
}
},
{
"name": "stream-name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
164
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PutRecordsMethodRequestPayload"
}
},
"application/x-amz-json-1.1": {
"schema": {
"$ref": "#/components/schemas/PutRecordsMethodRequestPayload"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecords",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\",\n \"Records\": [\n {\n \"Data\":
\"$util.base64Encode($elem.data)\",\n \"PartitionKey\": \"$elem.partition-
key\"\n }#if($foreach.hasNext),#end\n ]\n}",
"application/x-amz-json-1.1": "{\n \"StreamName\":
\"$input.params('stream-name')\",\n \"records\" : [\n {\n \"Data
\" : \"$elem.data\",\n \"PartitionKey\" : \"$elem.partition-key\"\n
}#if($foreach.hasNext),#end\n ]\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
"/streams/{stream-name}": {
"get": {
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
165
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/DescribeStream",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
},
"post": {
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/CreateStream",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
166
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
167
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"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"
}
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
"/streams/{stream-name}/record": {
"put": {
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecord",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
168
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\",\n \"Data\": \"$util.base64Encode($input.json('$.Data'))\",\n
\"PartitionKey\": \"$input.path('$.PartitionKey')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
"/streams": {
"get": {
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/ListStreams",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
}
},
"components": {
"schemas": {
"Empty": {
"type": "object"
},
"PutRecordsMethodRequestPayload": {
"type": "object",
"properties": {
"records": {
"type": "array",
"items": {
"type": "object",
"properties": {
"data": {
"type": "string"
},
"partition-key": {
"type": "string"
}
169
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
}
}
}
}
}
}
}
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-03-31T18:25:32Z",
"title": "KinesisProxy"
},
"basePath": "/test",
"schemes": [
"https"
],
"paths": {
"/streams": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/ListStreams",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
"/streams/{stream-name}": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
170
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
],
"parameters": [
{
"name": "stream-name",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/DescribeStream",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
},
"post": {
"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": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/CreateStream",
"responses": {
"default": {
"statusCode": "200"
}
},
171
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"ShardCount\": 5,\n \"StreamName\":
\"$input.params('stream-name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
},
"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"
}
}
},
"500": {
"description": "500 response",
"headers": {
"Content-Type": {
"type": "string"
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/DeleteStream",
"responses": {
"4\\d{2}": {
"statusCode": "400",
"responseParameters": {
"method.response.header.Content-Type":
"integration.response.header.Content-Type"
}
172
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
},
"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"
}
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
"/streams/{stream-name}/record": {
"put": {
"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": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecord",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
173
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
174
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
],
"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"
}
},
{
"in": "body",
"name": "PutRecordsMethodRequestPayload",
"required": true,
"schema": {
"$ref": "#/definitions/PutRecordsMethodRequestPayload"
}
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecords",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"StreamName\": \"$input.params('stream-
name')\",\n \"Records\": [\n {\n \"Data\":
\"$util.base64Encode($elem.data)\",\n \"PartitionKey\": \"$elem.partition-
key\"\n }#if($foreach.hasNext),#end\n ]\n}",
"application/x-amz-json-1.1": "{\n \"StreamName\":
\"$input.params('stream-name')\",\n \"records\" : [\n {\n \"Data
\" : \"$elem.data\",\n \"PartitionKey\" : \"$elem.partition-key\"\n
}#if($foreach.hasNext),#end\n ]\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
},
175
Amazon API Gateway Developer Guide
Tutorial: Create a REST API as an Amazon Kinesis proxy
"/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"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"type": "aws",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetShardIterator",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.Content-Type": "'application/x-amz-json-1.1'"
},
"requestTemplates": {
"application/json": "{\n \"ShardId\": \"$input.params('shard-
id')\",\n \"ShardIteratorType\": \"TRIM_HORIZON\",\n \"StreamName\":
\"$input.params('stream-name')\"\n}"
},
"passthroughBehavior": "when_no_match",
"httpMethod": "POST"
}
}
}
},
"definitions": {
"Empty": {
"type": "object"
},
"PutRecordsMethodRequestPayload": {
"type": "object",
"properties": {
"records": {
"type": "array",
"items": {
"type": "object",
"properties": {
"data": {
176
Amazon API Gateway Developer Guide
Build a private REST API
"type": "string"
},
"partition-key": {
"type": "string"
}
}
}
}
}
}
}
}
This tutorial takes approximately 30 minutes to complete. First, you use an AWS CloudFormation
template to create an Amazon VPC, a VPC endpoint, an AWS Lambda function, and launch an Amazon
EC2 instance that you'll use to test your API. Next, you use the AWS Management Console to create a
private API and attach a resource policy that allows access only from your VPC endpoint. Lastly, you test
your API.
To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user
with console access. For more information, see Prerequisites (p. 12).
In this tutorial, you use the AWS Management Console. For an AWS CloudFormation template that
creates this API and all related resources, see template.yaml.
Topics
• Step 1: Create dependencies (p. 178)
• Step 2: Create a private API (p. 178)
• Step 3: Create a method and integration (p. 178)
• Step 4: Attach a resource policy (p. 179)
• Step 5: Deploy your API (p. 179)
• Step 6: Verify that your API isn't publicly accessible (p. 180)
• Step 7: Connect to an instance in your VPC and invoke your API (p. 180)
• Step 8: Clean up (p. 181)
• Next steps: Automate with AWS CloudFormation (p. 181)
177
Amazon API Gateway Developer Guide
Build a private REST API
AWS CloudFormation provisions the dependencies for your API, which can take a few minutes. When
the status of your AWS CloudFormation stack is CREATE_COMPLETE, choose Outputs. Note your VPC
endpoint ID. You need it for later steps in this tutorial.
178
Amazon API Gateway Developer Guide
Build a private REST API
6. Select Use Lambda proxy integration. With a Lambda proxy integration, API Gateway sends an
event to Lambda with a defined structure, and transforms the response from your Lambda function
to an HTTP response.
7. For Lambda function, choose the function that you created with the AWS CloudFormation template
in Step 1. The function's name begins with private-api-tutorial.
8. Choose Save and then choose OK to confirm that you grant API Gateway permission to invoke your
Lambda function.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*",
"Condition": {
"StringNotEquals": {
"aws:sourceVpce": "vpceID"
}
}
},
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*"
}
]
}
5. Choose Save.
To deploy an API
179
Amazon API Gateway Developer Guide
Build a private REST API
curl https://abcdef123.execute-api.us-west-2.amazonaws.com/test
Curl indicates that your API's endpoint can't be resolved. If you get a different response, go back to
Step 2, and make sure that you choose Private for your API's endpoint type.
Next, you connect to an Amazon EC2 instance in your VPC to invoke your API.
curl https://abcdef123.execute-api.us-west-2.amazonaws.com/test
180
Amazon API Gateway Developer Guide
WebSocket API tutorials
You successfully created an API that's accessible only from within your Amazon VPC and then verified
that it works.
Step 8: Clean up
To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following
steps delete your REST API and your AWS CloudFormation stack.
Topics
• Tutorial: Building a serverless chat app with a WebSocket API, Lambda and DynamoDB (p. 181)
181
Amazon API Gateway Developer Guide
WebSocket chat app
This tutorial takes approximately 30 minutes to complete. First, you'll use an AWS CloudFormation
template to create Lambda functions that will handle API requests, as well as a DynamoDB table that
stores your client IDs. Then, you'll use the API Gateway console to create a WebSocket API that integrates
with your Lambda functions. Lastly, you'll test your API to verify that messages are sent and received.
To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user
with console access. For more information, see Prerequisites (p. 12).
You also need wscat to connect to your API. For more information, see the section called “Use wscat to
connect to a WebSocket API and send messages to it” (p. 724).
In this tutorial, you use the AWS Management Console. For an AWS CloudFormation template that
creates this API and all related resources, see chat-app.yaml.
Topics
• Step 1: Create Lambda functions and a DynamoDB table (p. 182)
• Step 2: Create a WebSocket API (p. 183)
• Step 3: Test your API (p. 183)
• Step 4: Clean up (p. 185)
• Next steps: Automate with AWS CloudFormation (p. 185)
182
Amazon API Gateway Developer Guide
WebSocket chat app
AWS CloudFormation provisions the resources specified in the template. It can take a few minutes
to finish provisioning your resources. When the status of your AWS CloudFormation stack is
CREATE_COMPLETE, you're ready to move on to the next step.
For Lambda, choose the corresponding Lambda function that you created with AWS CloudFormation
in Step 1. Each function's name matches a route. For example, for the $connect route, choose the
function named WsChatAppStack-ConnectHandler.
10. Review the stage that API Gateway creates for you. By default, API Gateway creates a stage name
production and automatically deploys your API to that stage. Choose Next.
11. Choose Create and deploy.
183
Amazon API Gateway Developer Guide
WebSocket chat app
1. Use the following command to connect to your API. When you connect to your API, API Gateway
invokes the $connect route. When this route is invoked, it calls a Lambda function that stores your
connection ID in DynamoDB.
wscat -c wss://abcdef123.execute-api.us-west-2.amazonaws.com/production
2. Open a new terminal and run the wscat command again with the following parameters.
wscat -c wss://abcdef123.execute-api.us-west-2.amazonaws.com/production
This gives you two connected clients that can exchange messages.
To send a message
• API Gateway determines which route to invoke based on your API's route selection expression. Your
API's route selection expression is $request.body.action. As a result, API Gateway invokes the
sendmessage route when you send the following message:
The Lambda function associated with the invoked route collects the client IDs from DynamoDB.
Then, the function calls the API Gateway Management API and sends the message to those clients.
All connected clients receive the following message:
• API Gateway invokes your API's default route when a client sends a message that doesn't match your
defined routes. The Lambda function associated with the $default route uses the API Gateway
Management API to send the client information about their connection.
test
184
Amazon API Gateway Developer Guide
WebSocket chat app
• Press CTRL+C to disconnect from your API. When a client disconnects from your API, API Gateway
invokes your API's $disconnect route. The Lambda integration for your API's $disconnect route
removes the connection ID from DynamoDB.
Step 4: Clean up
To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following
steps delete your AWS CloudFormation stack and WebSocket API.
185
Amazon API Gateway Developer Guide
Develop
You can use HTTP APIs to send requests to AWS Lambda functions or to any routable HTTP endpoint.
For example, you can create an HTTP API that integrates with a Lambda function on the backend. When
a client calls your API, API Gateway sends the request to the Lambda function and returns the function's
response to the client.
HTTP APIs support OpenID Connect and OAuth 2.0 authorization. They come with built-in support for
cross-origin resource sharing (CORS) and automatic deployments.
You can create HTTP APIs by using the AWS Management Console, the AWS CLI, APIs, AWS
CloudFormation, or SDKs. HTTP APIs use API Gateway Version 2 APIs, which previously supported only
WebSocket APIs.
Topics
• Developing an HTTP API in API Gateway (p. 186)
• Publishing HTTP APIs for customers to invoke (p. 221)
• Protecting your HTTP API (p. 226)
• Monitoring your HTTP API (p. 231)
• Troubleshooting issues with HTTP APIs (p. 239)
As you're developing your API Gateway API, you decide on a number of characteristics of your API. These
characteristics depend on the use case of your API. For example, you might want to only allow certain
clients to call your API, or you might want it to be available to everyone. You might want an API call to
execute a Lambda function, make a database query, or call an application.
Topics
• Creating an HTTP API (p. 186)
• Working with routes for HTTP APIs (p. 187)
• Controlling and managing access to an HTTP API in API Gateway (p. 189)
• Configuring integrations for HTTP APIs (p. 197)
• Configuring CORS for an HTTP API (p. 209)
• Transforming API requests and responses (p. 210)
• Working with OpenAPI definitions for HTTP APIs (p. 215)
The following examples show how to create an API with an AWS Lambda or HTTP integration, a route,
and a default stage that is configured to automatically deploy changes.
This guide assumes that you're already familiar with API Gateway and Lambda. For a more detailed
guide, see Getting started (p. 13).
186
Amazon API Gateway Developer Guide
Routes
Topics
• Create an HTTP API by using the AWS Management Console (p. 187)
• Create an HTTP API by using the AWS CLI (p. 187)
Now your API is ready to invoke. You can test your API by entering its invoke URL in a browser, or by
using Curl.
curl https://api-id.execute-api.us-east-2.amazonaws.com
Example
Now your API is ready to invoke. You can test your API by entering its invoke URL in a browser, or by
using Curl.
curl https://api-id.execute-api.us-east-2.amazonaws.com
187
Amazon API Gateway Developer Guide
Routes
For example, the GET /pets/{petID} route catches a GET request that a client submits to
https://api-id.execute-api.us-east-2.amazonaws.com/pets/6.
A greedy path variable catches all child resources of a route. To create a greedy path variable, add + to
the variable name—for example, {proxy+}. The greedy path variable must be at the end of the resource
path.
When the $default route receives a request, API Gateway sends the full request path to the integration.
For example, you can create an API with only a $default route and integrate it on the ANY method
with the https://petstore-demo-endpoint.execute-api.com HTTP endpoint. When you send
a request to https://api-id.execute-api.us-east-2.amazonaws.com/store/checkout,
API Gateway sends a request to https://petstore-demo-endpoint.execute-api.com/store/
checkout.
To learn more about HTTP integrations, see Working with HTTP proxy integrations for HTTP
APIs (p. 201).
After selecting a stage, API Gateway selects a route. API Gateway selects the route with the most-specific
match, using the following priorities:
If no routes match a request, API Gateway returns {"message":"Not Found"} to the client.
For example, consider an API with a $default stage and the following example routes:
1. GET /pets/dog/1
2. GET /pets/dog/{id}
3. GET /pets/{proxy+}
4. ANY /{proxy+}
5. $default
The following table summarizes how API Gateway routes requests to the example routes.
188
Amazon API Gateway Developer Guide
Access control
• Lambda authorizers use Lambda functions to control access to APIs. For more information, see
Working with AWS Lambda authorizers for HTTP APIs (p. 189).
• JWT authorizers use JSON web tokens to control access to APIs. For more information, see Controlling
access to HTTP APIs with JWT authorizers (p. 195).
• Standard AWS IAM roles and policies offer flexible and robust access controls. You can use IAM roles
and policies to control who can create and manage your APIs, as well as who can invoke them. For
more information, see Using IAM authorization (p. 197).
189
Amazon API Gateway Developer Guide
Access control
The following examples show the structure of each payload format version.
2.0
{
"version": "2.0",
"type": "REQUEST",
"routeArn": "arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request",
"identitySource": ["user1", "123"],
"routeKey": "$default",
"rawPath": "/my/path",
"rawQueryString": "parameter1=value1¶meter1=value2¶meter2=value",
"cookies": ["cookie1", "cookie2"],
"headers": {
"Header1": "value1",
"Header2": "value2"
},
"queryStringParameters": {
"parameter1": "value1,value2",
"parameter2": "value"
},
"requestContext": {
"accountId": "123456789012",
"apiId": "api-id",
"authentication": {
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"domainName": "id.execute-api.us-east-1.amazonaws.com",
"domainPrefix": "id",
"http": {
"method": "POST",
"path": "/my/path",
"protocol": "HTTP/1.1",
"sourceIp": "IP",
"userAgent": "agent"
},
"requestId": "id",
"routeKey": "$default",
"stage": "$default",
"time": "12/Mar/2020:19:03:58 +0000",
"timeEpoch": 1583348638390
},
"pathParameters": { "parameter1": "value1" },
"stageVariables": { "stageVariable1": "value1", "stageVariable2": "value2" }
}
1.0
{
"version": "1.0",
"type": "REQUEST",
"methodArn": "arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request",
"identitySource": "user1,123",
"authorizationToken": "user1,123",
"resource": "/request",
190
Amazon API Gateway Developer Guide
Access control
"path": "/request",
"httpMethod": "GET",
"headers": {
"X-AMZ-Date": "20170718T062915Z",
"Accept": "*/*",
"HeaderAuth1": "headerValue1",
"CloudFront-Viewer-Country": "US",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Is-Mobile-Viewer": "false",
"User-Agent": "..."
},
"queryStringParameters": {
"QueryString1": "queryValue1"
},
"pathParameters": {},
"stageVariables": {
"StageVar1": "stageValue1"
},
"requestContext": {
"path": "/request",
"accountId": "123456789012",
"resourceId": "05c7jb",
"stage": "test",
"requestId": "...",
"identity": {
"apiKey": "...",
"sourceIp": "...",
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"resourcePath": "/request",
"httpMethod": "GET",
"apiId": "abcdef123"
}
}
If you choose the 1.0 format version, Lambda authorizers must return an IAM policy that allows or
denies access to your API route. You can use standard IAM policy syntax in the policy. For examples
of IAM policies, see the section called “ Control access for invoking an API” (p. 292). The context
object is optional. You can pass context properties to Lambda integrations or access logs by using
$context.authorizer.property. To learn more, see the section called “Logging variables” (p. 235).
Example
191
Amazon API Gateway Developer Guide
Access control
"principalId": "abcdef", // The principal user identification associated with the token
sent by the client.
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow|Deny",
"Resource": "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/
[{resource}/[{child-resources}]]"
}
]
},
"context": {
"exampleKey": "exampleValue"
}
}
Simple response
{
"isAuthorized": true/false,
"context": {
"exampleKey": "exampleValue"
}
}
IAM policy
{
"principalId": "abcdef", // The principal user identification associated with the
token sent by the client.
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow|Deny",
"Resource": "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/
{httpVerb}/[{resource}/[{child-resources}]]"
}
]
},
"context": {
"exampleKey": "exampleValue"
}
}
192
Amazon API Gateway Developer Guide
Access control
Simple response
return response;
};
IAM policy
193
Amazon API Gateway Developer Guide
Access control
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": event.routeArn
}]
},
"context": {
"stringKey": "value",
"numberKey": 1,
"booleanKey": true,
"arrayKey": ["value1", "value2"],
"mapKey": { "value1": "value2" }
}
};
}
};
Identity sources
You can optionally specify identity sources for a Lambda authorizer. Identity sources specify the location
of data that's required to authorize a request. For example, you can specify header or query string values
as identity sources. If you specify identity sources, clients must include them in the request. If the client's
request doesn't include the identity sources, API Gateway doesn't invoke your Lambda authorizer, and
the client receives a 401 error. The following identity sources are supported:
Selection expressions
To enable caching, your authorizer must have at least one identity source.
If you enable simple responses for an authorizer, the authorizer's response fully allows or denies all API
requests that match the cached identity source values. For more granular permissions, disable simple
responses and return an IAM policy.
By default, API Gateway uses the cached authorizer response for all routes of an API that use the
authorizer. To cache responses per route, add $context.routeKey to your authorizer's identity sources.
194
Amazon API Gateway Developer Guide
Access control
The following command grants API Gateway permission to invoke your Lambda function. If API Gateway
doesn't have permission to invoke your function, clients receive a 500 Internal Server Error.
After you've created an authorizer and granted API Gateway permission to invoke it, update your route to
use the authorizer.
To troubleshoot errors, enable access logging (p. 233) for your API stage. Include the
$context.authorizer.error logging variable in your log format.
If the logs indicate that API Gateway doesn't have permission to invoke your function, update your
function's resource policy or provide an IAM role to grant API Gateway permission to invoke your
authorizer.
If the logs indicate that your Lambda function returns an invalid response, verify that your Lambda
function returns a response in the required format (p. 191).
If you configure a JWT authorizer for a route of your API, API Gateway validates the JWTs that clients
submit with API requests. API Gateway allows or denies requests based on token validation, and
195
Amazon API Gateway Developer Guide
Access control
optionally, scopes in the token. If you configure scopes for a route, the token must include at least one of
the route's scopes.
You can configure distinct authorizers for each route of an API, or use the same authorizer for multiple
routes.
Note
There is no standard mechanism to differentiate JWT access tokens from other types of JWTs,
such as OpenID Connect ID tokens. Unless you require ID tokens for API authorization, we
recommend that you configure your routes to require authorization scopes. You can also
configure your JWT authorizers to require issuers or audiences that your identity provider uses
only when issuing JWT access tokens.
1. Check the identitySource for a token. The identitySource can include only the token, or the
token prefixed with Bearer .
2. Decode the token.
3. Check the token's algorithm and signature by using the public key that is fetched from the issuer's
jwks_uri. Currently, only RSA-based algorithms are supported.
4. Validate claims. API Gateway evaluates the following token claims:
• kid – The token must have a header claim that matches the key in the jwks_uri that signed the
token.
• iss – Must match the issuer that is configured for the authorizer.
• aud or client_id – Must match one of the audience entries that is configured for the authorizer.
• exp – Must be after the current time in UTC.
• nbf – Must be before the current time in UTC.
• iat – Must be before the current time in UTC.
• scope or scp – The token must include at least one of the scopes in the route's
authorizationScopes.
If any of these steps fail, API Gateway denies the API request.
After validating the JWT, API Gateway passes the claims in the token to the API route’s
integration. Backend resources, such as Lambda functions, can access the JWT claims. For
example, if the JWT includes an identity claim emailID, it's available to a Lambda integration in
$event.requestContext.authorizer.jwt.claims.emailID. For more information about
the payload that API Gateway sends to Lambda integrations, see the section called “AWS Lambda
integrations” (p. 197).
The following AWS CLI command creates a JWT authorizer that uses Amazon Cognito as an identity
provider. For Audience, specify the ID of a client that's associated with the user pool that you specify for
Issuer.
196
Amazon API Gateway Developer Guide
Integrations
--api-id api-id \
--authorizer-type JWT \
--identity-source '$request.header.Authorization' \
--jwt-configuration Audience=audience,Issuer=https://cognito-idp.us-
east-2.amazonaws.com/userPoolID
IAM authorization for HTTP APIs is similar to that for REST APIs (p. 292).
Note
Resource policies aren't currently supported for HTTP APIs.
For examples of IAM policies that grant clients the permission to invoke APIs, see the section called “
Control access for invoking an API” (p. 292).
Topics
• Working with AWS Lambda proxy integrations for HTTP APIs (p. 197)
• Working with HTTP proxy integrations for HTTP APIs (p. 201)
• Working with AWS service integrations for HTTP APIs (p. 202)
• Working with private integrations for HTTP APIs (p. 207)
197
Amazon API Gateway Developer Guide
Integrations
The following examples show the structure of each payload format version.
Note
Header names are lowercased.
Format 2.0 doesn't have multiValueHeaders or multiValueQueryStringParameters
fields. Duplicate headers are combined with commas and included in the headers
field. Duplicate query strings are combined with commas and included in the
queryStringParameters field.
Format 2.0 includes a new cookies field. All cookie headers in the request are combined with
commas and added to the cookies field. In the response to the client, each cookie becomes a
set-cookie header.
2.0
{
"version": "2.0",
"routeKey": "$default",
"rawPath": "/my/path",
"rawQueryString": "parameter1=value1¶meter1=value2¶meter2=value",
"cookies": [
"cookie1",
"cookie2"
],
"headers": {
"header1": "value1",
"header2": "value1,value2"
},
"queryStringParameters": {
"parameter1": "value1,value2",
"parameter2": "value"
},
"requestContext": {
"accountId": "123456789012",
"apiId": "api-id",
"authentication": {
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"authorizer": {
"jwt": {
"claims": {
"claim1": "value1",
"claim2": "value2"
},
"scopes": [
"scope1",
"scope2"
198
Amazon API Gateway Developer Guide
Integrations
]
}
},
"domainName": "id.execute-api.us-east-1.amazonaws.com",
"domainPrefix": "id",
"http": {
"method": "POST",
"path": "/my/path",
"protocol": "HTTP/1.1",
"sourceIp": "IP",
"userAgent": "agent"
},
"requestId": "id",
"routeKey": "$default",
"stage": "$default",
"time": "12/Mar/2020:19:03:58 +0000",
"timeEpoch": 1583348638390
},
"body": "Hello from Lambda",
"pathParameters": {
"parameter1": "value1"
},
"isBase64Encoded": false,
"stageVariables": {
"stageVariable1": "value1",
"stageVariable2": "value2"
}
}
1.0
{
"version": "1.0",
"resource": "/my/path",
"path": "/my/path",
"httpMethod": "GET",
"headers": {
"header1": "value1",
"header2": "value2"
},
"multiValueHeaders": {
"header1": [
"value1"
],
"header2": [
"value1",
"value2"
]
},
"queryStringParameters": {
"parameter1": "value1",
"parameter2": "value"
},
"multiValueQueryStringParameters": {
"parameter1": [
"value1",
"value2"
],
"parameter2": [
"value"
]
},
"requestContext": {
"accountId": "123456789012",
"apiId": "id",
199
Amazon API Gateway Developer Guide
Integrations
"authorizer": {
"claims": null,
"scopes": null
},
"domainName": "id.execute-api.us-east-1.amazonaws.com",
"domainPrefix": "id",
"extendedRequestId": "request-id",
"httpMethod": "GET",
"identity": {
"accessKey": null,
"accountId": null,
"caller": null,
"cognitoAuthenticationProvider": null,
"cognitoAuthenticationType": null,
"cognitoIdentityId": null,
"cognitoIdentityPoolId": null,
"principalOrgId": null,
"sourceIp": "IP",
"user": null,
"userAgent": "user-agent",
"userArn": null,
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"path": "/my/path",
"protocol": "HTTP/1.1",
"requestId": "id=",
"requestTime": "04/Mar/2020:19:15:17 +0000",
"requestTimeEpoch": 1583349317135,
"resourceId": null,
"resourcePath": "/my/path",
"stage": "$default"
},
"pathParameters": null,
"stageVariables": null,
"body": "Hello from Lambda!",
"isBase64Encoded": false
}
With the 1.0 format version, Lambda integrations must return a response in the following format.
Example
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headername": "headervalue", ... },
200
Amazon API Gateway Developer Guide
Integrations
With the 2.0 format version, API Gateway can infer the response format for you. API Gateway makes the
following assumptions if your Lambda function returns valid JSON and doesn't return a statusCode:
• isBase64Encoded is false.
• statusCode is 200.
• content-type is application/json.
• body is the function's response.
The following examples show the output of a Lambda function and API Gateway's interpretation.
To customize the response, your Lambda function should return a response with the following format.
{
"cookies" : ["cookie1", "cookie2"],
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headername": "headervalue", ... },
"body": "Hello from Lambda!"
}
To create an HTTP proxy integration, provide the URL of a publicly routable HTTP endpoint.
201
Amazon API Gateway Developer Guide
Integrations
For example, the route /pets/{petID} catches requests to /pets/6. You can reference path
variables in the integration URI to send the variable's contents to an integration. An example is /pets/
extentendedpath/{petID}.
You can use greedy path variables to catch all child resources of a route. To create a greedy path variable,
add + to the variable name—for example, {proxy+}.
To set up a route with an HTTP proxy integration that catches all requests, create an API route with a
greedy path variable (for example, /parent/{proxy+}). Integrate the route with an HTTP endpoint
(for example, https://petstore-demo-endpoint.execute-api.com/petstore/{proxy}) on the
ANY method. The greedy path variable must be at the end of the resource path.
Parameter mapping
202
Amazon API Gateway Developer Guide
Integrations
To create a first-class integration, choose a supported AWS service action, such as SQS-SendMessage,
configure the request parameters, and provide a role that grants API Gateway permissions to invoke the
integrated AWS service API. Depending on the integration subtype, different request parameters are
required. To learn more, see the section called “AWS service integrations reference” (p. 203).
The following AWS CLI command creates an integration that sends an Amazon SQS message.
Integration subtypes
• EventBridge-PutEvents (p. 204)
• SQS-SendMessage (p. 204)
203
Amazon API Gateway Developer Guide
Integrations
EventBridge-PutEvents
Sends custom events to Amazon EventBridge so that they can be matched to rules.
EventBridge-PutEvents 1.0
Parameter Required
Detail True
DetailType True
Source True
Time False
EventBusName False
Resources False
Region False
TraceHeader False
SQS-SendMessage
SQS-SendMessage 1.0
Parameter Required
QueueUrl True
MessageBody True
DelaySeconds False
MessageAttributes False
MessageDeduplicationId False
MessageGroupId False
MessageSystemAttributes False
Region False
204
Amazon API Gateway Developer Guide
Integrations
To learn more, see SendMessage in the Amazon Simple Queue Service API Reference.
SQS-ReceiveMessage
Retrieves one or more messages (up to 10), from the specified queue.
SQS-ReceiveMessage 1.0
Parameter Required
QueueUrl True
AttributeNames False
MaxNumberOfMessages False
MessageAttributeNames False
ReceiveRequestAttemptId False
VisibilityTimeout False
WaitTimeSeconds False
Region False
To learn more, see ReceiveMessage in the Amazon Simple Queue Service API Reference.
SQS-DeleteMessage
SQS-DeleteMessage 1.0
Parameter Required
ReceiptHandle True
QueueUrl True
Region False
To learn more, see DeleteMessage in the Amazon Simple Queue Service API Reference.
SQS-PurgeQueue
SQS-PurgeQueue 1.0
Parameter Required
QueueUrl True
Region False
To learn more, see PurgeQueue in the Amazon Simple Queue Service API Reference.
205
Amazon API Gateway Developer Guide
Integrations
AppConfig-GetConfiguration
AppConfig-GetConfiguration 1.0
Parameter Required
Application True
Environment True
Configuration True
ClientId True
ClientConfigurationVersion False
Region False
Kinesis-PutRecord
Kinesis-PutRecord 1.0
Parameter Required
StreamName True
Data True
PartitionKey True
SequenceNumberForOrdering False
ExplicitHashKey False
Region False
To learn more, see PutRecord in the Amazon Kinesis Data Streams API Reference.
StepFunctions-StartExecution
StepFunctions-StartExecution 1.0
Parameter Required
StateMachineArn True
Name False
Input False
Region False
206
Amazon API Gateway Developer Guide
Integrations
To learn more, see StartExecution in the AWS Step Functions API Reference.
StepFunctions-StartSyncExecution
Starts a synchronous state machine execution.
StepFunctions-StartSyncExecution 1.0
Parameter Required
StateMachineArn True
Name False
Input False
Region False
TraceHeader False
To learn more, see StartSyncExecution in the AWS Step Functions API Reference.
StepFunctions-StopExecution
Stops an execution.
StepFunctions-StopExecution 1.0
Parameter Required
ExecutionArn True
Cause False
Error False
Region False
To learn more, see StopExecution in the AWS Step Functions API Reference.
You can expose your resources in a VPC for access by clients outside of the VPC by using private
integrations. You can control access to your API by using any of the authorization methods (p. 189)
that API Gateway supports.
To create a private integration, you must first create a VPC link. To learn more about VPC links, see
Working with VPC links for HTTP APIs (p. 208).
After you’ve created a VPC link, you can set up private integrations that connect to an Application Load
Balancer, Network Load Balancer, or resources registered with an AWS Cloud Map service.
To create a private integration, all resources must be owned by the same AWS account (including the
load balancer or AWS Cloud Map service, VPC link and HTTP API).
By default, private integration traffic uses the HTTP protocol. You can specify a tlsConfig if you require
private integration traffic to use HTTPS.
207
Amazon API Gateway Developer Guide
Integrations
Note
For private integrations, API Gateway includes the stage (p. 221) portion of the API endpoint
in the request to your backend resources. For example, a request to the test stage of an
API includes test/route-path in the request to your private integration. To remove the
stage name from the request to your backend resources, use parameter mapping (p. 210) to
overwrite the request path to $request.path.
To create a private integration with an Application Load Balancer or Network Load Balancer, create an
HTTP proxy integration, specify the VPC link to use, and provide the listener ARN of the load balancer.
Use the following command to create a private integration that connects to a load balancer by using a
VPC link.
For integrations with AWS Cloud Map, API Gateway uses DiscoverInstances to identify resources. You
can use query parameters to target specific resources. The registered resources' attributes must include
IP addresses and ports. API Gateway distributes requests across healthy resources that are returned from
DiscoverInstances. To learn more, see DiscoverInstances in the AWS Cloud Map API Reference.
Note
If you use Amazon ECS to populate entries in AWS Cloud Map, you must configure your Amazon
ECS task to use SRV records. "A" records aren't supported. To learn more, see Configuring Your
Service to Use Service Discovery in the Amazon Elastic Container Service Developer Guide.
To create a private integration with AWS Cloud Map, create an HTTP proxy integration, specify the VPC
link to use, and provide the ARN of the AWS Cloud Map service.
Use the following command to create a private integration that uses AWS Cloud Map service discovery to
identify resources.
208
Amazon API Gateway Developer Guide
CORS
To learn more about creating private integrations, see Working with private integrations for HTTP
APIs (p. 207).
A private integration uses a VPC link to encapsulate connections between API Gateway and targeted VPC
resources. You can reuse VPC links across different routes and APIs.
When you create a VPC link, API Gateway creates and manages elastic network interfaces for the VPC
link in your account. This process can take a few minutes. When a VPC link is ready to use, its state
transitions from PENDING to AVAILABLE.
Note
If no traffic is sent over the VPC link for 60 days, it becomes INACTIVE. When a VPC link is in an
INACTIVE state, API Gateway deletes all of the VPC link’s network interfaces. This causes API
requests that depend on the VPC link to fail. If API requests resume, API Gateway reprovisions
network interfaces. It can take a few minutes to create the network interfaces and reactivate the
VPC link. You can use the VPC link status to monitor the state of your VPC link.
Use the following command to create a VPC link. To create a VPC link, all resources involved must be
owned by the same AWS account.
Note
VPC links are immutable. After you create a VPC link, you can’t change its subnets or security
groups.
CORS is typically required to build web applications that access APIs hosted on a different domain
or origin. You can enable CORS to allow requests to your API from a web application hosted on
a different domain. For example, if your API is hosted on https://{api_id}.execute-api.
{region}.amazonaws.com/ and you want to call your API from a web application hosted on
example.com, your API must support CORS.
If you configure CORS for an API, API Gateway automatically sends a response to preflight OPTIONS
requests, even if there isn't an OPTIONS route configured for your API. For a CORS request, API Gateway
adds the configured CORS headers to the response from an integration.
Note
If you configure CORS for an API, API Gateway ignores CORS headers returned from your
backend integration.
209
Amazon API Gateway Developer Guide
Parameter mapping
Example
For more information, see CORS in the Amazon API Gateway Version 2 API Reference.
210
Amazon API Gateway Developer Guide
Parameter mapping
Request parameters are a key-value map. The key identifies the location of the request parameter to
change, and how to change it. The value specifies the new data for the parameter.
Type Syntax
Header append|overwrite|
remove:header.headername
Path overwrite:path
The following table shows supported values that you can map to parameters.
211
Amazon API Gateway Developer Guide
Parameter mapping
Note
To use multiple variables in a selection expression, enclose the variable in brackets. For example,
${request.path.name} ${request.path.id}.
You configure response parameters for each status code that your integration returns. Response
parameters are a key-value map. The key identifies the location of the request parameter to change, and
how to change it. The value specifies the new data for the parameter.
Type Syntax
Header append|overwrite|
remove:header.headername
The following table shows supported values that you can map to parameters.
212
Amazon API Gateway Developer Guide
Parameter mapping
Note
To use multiple variables in a selection expression, enclose the variable in brackets. For example,
${request.path.name} ${request.path.id}.
Reserved headers
The following headers are reserved. You can't configure request or response mappings for these headers.
• access-control-*
• apigw-*
• Authorization
• Connection
• Content-Encoding
• Content-Length
• Content-Location
• Forwarded
• Keep-Alive
• Origin
• Proxy-Authenticate
• Proxy-Authorization
• TE
• Trailers
213
Amazon API Gateway Developer Guide
Parameter mapping
• Transfer-Encoding
• Upgrade
• x-amz-*
• x-amzn-*
• X-Forwarded-For
• X-Forwarded-Host
• X-Forwarded-Proto
• Via
Examples
The following AWS CLI examples configure parameter mappings. For example AWS CloudFormation
templates, see GitHub.
214
Amazon API Gateway Developer Guide
OpenAPI
To migrate from a REST API to an HTTP API, you can export your REST API as an OpenAPI 3.0 definition
file. Then import the API definition as an HTTP API. To learn more about exporting a REST API, see
Export a REST API from API Gateway (p. 487).
Note
HTTP APIs support the same AWS variables as REST APIs. To learn more, see AWS variables for
OpenAPI import (p. 485).
Info
A property is valid according to the OpenAPI specification, but that property isn’t supported for
HTTP APIs.
For example, the following OpenAPI 3.0 snippet produces info on import because HTTP APIs don't
support request validation. API Gateway ignores the requestBody and schema fields.
"paths": {
"/": {
"get": {
"x-amazon-apigateway-integration": {
"type": "AWS_PROXY",
"httpMethod": "POST",
"uri": "arn:aws:lambda:us-east-2:123456789012:function:HelloWorld",
"payloadFormatVersion": "1.0"
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Body"
215
Amazon API Gateway Developer Guide
OpenAPI
}
}
}
}
}
}
...
},
"components": {
"schemas": {
"Body": {
"type": "object",
"properties": {
"key": {
"type": "string"
}
}
}
...
}
...
}
Warning
A property or structure is invalid according to the OpenAPI specification, but it doesn’t block API
creation. You can specify whether API Gateway should ignore these warnings and continue creating
the API, or stop creating the API on warnings.
The following OpenAPI 3.0 document produces warnings on import because HTTP APIs support only
Lambda proxy and HTTP proxy integrations.
"x-amazon-apigateway-integration": {
"type": "AWS",
"httpMethod": "POST",
"uri": "arn:aws:lambda:us-east-2:123456789012:function:HelloWorld",
"payloadFormatVersion": "1.0"
}
Error
The OpenAPI specification is invalid or malformed. API Gateway can’t create any resources from the
malformed document. You must fix the errors, and then try again.
The following API definition produces errors on import because HTTP APIs support only the
OpenAPI 3.0 specification.
{
"swagger": "2.0.0",
"info": {
"title": "My API",
"description": "An Example OpenAPI definition for Errors/Warnings/ImportInfo",
"version": "1.0"
}
...
}
As another example, while OpenAPI allows users to define an API with multiple security
requirements attached to a particular operation, API Gateway does not support this. Each operation
can have only one of IAM authorization, a Lambda authorizer, or a JWT authorizer. Attempting to
model multiple security requirements results in an error.
216
Amazon API Gateway Developer Guide
OpenAPI
Example
Example
You can import the following example OpenAPI 3.0 definition to create an HTTP API.
{
"openapi": "3.0.1",
"info": {
"title": "Example Pet Store",
"description": "A Pet Store API.",
"version": "1.0"
},
"paths": {
"/pets": {
"get": {
"operationId": "GET HTTP",
"parameters": [
{
"name": "type",
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "page",
"in": "query",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"headers": {
"Access-Control-Allow-Origin": {
"schema": {
"type": "string"
}
}
},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pets"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "HTTP_PROXY",
"httpMethod": "GET",
"uri": "http://petstore.execute-api.us-west-1.amazonaws.com/petstore/pets",
217
Amazon API Gateway Developer Guide
OpenAPI
"payloadFormatVersion": 1.0
}
},
"post": {
"operationId": "Create Pet",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NewPet"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "200 response",
"headers": {
"Access-Control-Allow-Origin": {
"schema": {
"type": "string"
}
}
},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NewPetResponse"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "HTTP_PROXY",
"httpMethod": "POST",
"uri": "http://petstore.execute-api.us-west-1.amazonaws.com/petstore/pets",
"payloadFormatVersion": 1.0
}
}
},
"/pets/{petId}": {
"get": {
"operationId": "Get Pet",
"parameters": [
{
"name": "petId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"headers": {
"Access-Control-Allow-Origin": {
"schema": {
"type": "string"
}
}
},
"content": {
218
Amazon API Gateway Developer Guide
OpenAPI
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
}
}
},
"x-amazon-apigateway-integration": {
"type": "HTTP_PROXY",
"httpMethod": "GET",
"uri": "http://petstore.execute-api.us-west-1.amazonaws.com/petstore/pets/
{petId}",
"payloadFormatVersion": 1.0
}
}
}
},
"x-amazon-apigateway-cors": {
"allowOrigins": [
"*"
],
"allowMethods": [
"GET",
"OPTIONS",
"POST"
],
"allowHeaders": [
"x-amzm-header",
"x-apigateway-header",
"x-api-key",
"authorization",
"x-amz-date",
"content-type"
]
},
"components": {
"schemas": {
"Pets": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Pet"
}
},
"Empty": {
"type": "object"
},
"NewPetResponse": {
"type": "object",
"properties": {
"pet": {
"$ref": "#/components/schemas/Pet"
},
"message": {
"type": "string"
}
}
},
"Pet": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"type": {
"type": "string"
219
Amazon API Gateway Developer Guide
OpenAPI
},
"price": {
"type": "number"
}
}
},
"NewPet": {
"type": "object",
"properties": {
"type": {
"$ref": "#/components/schemas/PetType"
},
"price": {
"type": "number"
}
}
},
"PetType": {
"type": "string",
"enum": [
"dog",
"cat",
"fish",
"bird",
"gecko"
]
}
}
}
}
Export an OpenAPI 3.0 definition of your API's latest changes by using the AWS
CLI
The following command exports an OpenAPI definition of an HTTP API to a JSON file named latest-
api-definition.json. Because the command doesn't specify a stage, API Gateway exports the latest
configuration of your API, whether it has been deployed to a stage or not. The exported definition file
doesn't include API Gateway extensions (p. 744).
220
Amazon API Gateway Developer Guide
Publish
--output-type JSON \
--specification OAS30 \
--no-include-extensions \
latest-api-definition.json
For more information, see ExportAPI in the Amazon API Gateway Version 2 API Reference.
An API stage is a logical reference to a lifecycle state of your API (for example, dev, prod, beta, or v2).
Each stage is a named reference to a deployment of the API and is made available for client applications
to call. You can configure different integrations and settings for each stage of an API.
You can use custom domain names to provide a simpler, more intuitive URL for clients to invoke your API
than the default URL, https://api-id.execute-api.region.amazonaws.com/stage.
Topics
• Working with stages for HTTP APIs (p. 221)
• Setting up custom domain names for HTTP APIs (p. 222)
You can create a $default stage that is served from the base of your API's URL—for example,
https://{api_id}.execute-api.{region}.amazonaws.com/. You use this URL to invoke an API
stage.
A deployment is a snapshot of your API configuration. After you deploy an API to a stage, it’s available
for clients to invoke. You must deploy an API for changes to take effect. If you enable automatic
deployments, changes to an API are automatically released for you.
Stage variables
Stage variables are key-value pairs that you can define for a stage of an HTTP API. They act like
environment variables and can be used in your API setup.
For example, you can define a stage variable, and then set its value as an HTTP endpoint for an HTTP
proxy integration. Later, you can reference the endpoint by using the associated stage variable name. By
doing this, you can use the same API setup with a different endpoint at each stage. Similarly, you can use
stage variables to specify a different AWS Lambda function integration for each stage of your API.
Note
Stage variables are not intended to be used for sensitive data, such as credentials. To pass
sensitive data to integrations, use an AWS Lambda authorizer. You can pass sensitive data
to integrations in the output of the Lambda authorizer. To learn more, see the section called
“Lambda authorizer response format” (p. 191).
Examples
To use a stage variable to customize the HTTP integration endpoint, you must first set the name and
value of the stage variable (for example, url) with a value of example.com. Next, set up an HTTP
221
Amazon API Gateway Developer Guide
Custom domain names
proxy integration. Instead of entering the endpoint's URL, 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 the stage of your API.
You can reference stage variables in a similar way to specify a Lambda function name or an AWS role
ARN.
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 (AWS CLI) to do this.
Lambda functions
You can use a stage variable in place of a Lambda function name or alias, as shown in the following
examples.
• arn:aws:apigateway:<region>:lambda:path/2015-03-31/
functions/arn:aws:lambda:<region>:<account_id>:function:
${stageVariables.<function_variable_name>}/invocations
• arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/
arn:aws:lambda:<region>:<account_id>:function:<function_name>:
${stageVariables.<version_variable_name>}/invocations
Note
To use a stage variable for a Lambda function, the function must be in the same account as the
API. Stage variables don't support cross-account Lambda functions.
• arn:aws:iam::<account_id>:${stageVariables.<variable_name>}
222
Amazon API Gateway Developer Guide
Custom domain names
After deploying your API, you (and your customers) can invoke the API using the default base URL of the
following format:
https://api-id.execute-api.region.amazonaws.com/stage
where api-id is generated by API Gateway, region (AWS Region) is specified by you when creating the
API, and stage is specified by you when deploying the API.
With custom domain names, you can set up your API's hostname, and choose a base path (for example,
myservice) to map the alternative URL to your API. For example, a more user-friendly API base URL can
become:
https://api.example.com/myservice
If you don't set any base mapping under a custom domain name, the resulting API's base URL is the same
as the custom domain (for example, https://api.example.com). In this case, the custom domain
name can't support more than one API.
Note
A custom domain can be associated with REST APIs and HTTP APIs. You can use API Gateway
Version 2 APIs to create and manage Regional custom domain names for REST APIs and HTTP
APIs.
For HTTP APIs, TLS 1.2 is the only supported TLS version.
After a custom domain name is created in API Gateway, you must create or update your DNS provider's
resource record to map to your API endpoint. Without such a mapping, API requests bound for the
custom domain name cannot reach API Gateway.
To create a wildcard custom domain name, specify a wildcard (*) as the first subdomain of a custom
domain that represents all possible subdomains of a root domain.
For example, the wildcard custom domain name *.example.com results in subdomains such as
a.example.com, b.example.com, and c.example.com, which all route to the same domain.
Wildcard custom domain names support distinct configurations from API Gateway's standard custom
domain names. For example, in a single AWS account, you can configure *.example.com and
a.example.com to behave differently.
223
Amazon API Gateway Developer Guide
Custom domain names
To create a wildcard custom domain name, you must provide a certificate issued by ACM that has been
validated using either the DNS or the email validation method.
Note
You can't create a wildcard custom domain name if a different AWS account has created a
custom domain name that conflicts with the wildcard custom domain name. For example,
if account A has created a.example.com, then account B can't create the wildcard custom
domain name *.example.com.
If account A and account B share an owner, you can contact the AWS Support Center to request
an exception.
To import an SSL/TLS certificate, you must provide the PEM-formatted SSL/TLS certificate body, its
private key, and the certificate chain for the custom domain name. Each certificate stored in ACM is
identified by its ARN. To use an AWS managed certificate for a domain name, you simply reference its
ARN.
ACM makes it straightforward to set up and use a custom domain name for an API. You create a
certificate for the given domain name (or import a certificate), set up the domain name in API Gateway
with the ARN of the certificate provided by ACM, and map a base path under the custom domain name
to a deployed stage of the API. With certificates issued by ACM, you do not have to worry about exposing
any sensitive certificate details, such as the private key.
For details on setting up a custom domain name, see Getting certificates ready in AWS Certificate
Manager (p. 521) and Setting up a regional custom domain name in API Gateway (p. 531).
An API mapping specifies an API, a stage, and optionally a path to use for the mapping. For example, you
can map the production stage of an API to https://api.example.com/orders.
You can map HTTP and REST API stages to the same custom domain name.
Before you create an API mapping, you must have an API, a stage, and a custom domain name. To
learn more about creating a custom domain name, see the section called “Setting up a regional custom
domain name” (p. 531).
API Gateway routes requests to the API mapping that has the longest matching path. API Gateway
considers only the paths configured for API mappings, and not API routes, to select the API to invoke.
If no path matches the request, API Gateway sends the request to the API that you've mapped to the
empty path (none).
For example, consider a custom domain name https://api.example.com with the following API
mappings:
224
Amazon API Gateway Developer Guide
Custom domain names
Restrictions
• In an API mapping, the custom domain name and mapped APIs must be in the same AWS account.
• API mappings must contain only letters, numbers, and the following characters: $-_.+!*'()/.
• The maximum length for the path in an API mapping is 300 characters.
• You can only map HTTP APIs to a regional custom domain name with the TLS 1.2 security policy.
• You can't map WebSocket APIs to the same custom domain name as an HTTP API or REST API.
For example AWS Serverless Application Model templates that create all resources, see Sessions With
SAM on GitHub.
225
Amazon API Gateway Developer Guide
Protect
AWS CLI
The following AWS CLI command creates an API mapping. In this example, API Gateway sends
requests to api.example.com/v1/orders to the specified API and stage.
AWS CloudFormation
MyApiMapping:
Type: 'AWS::ApiGatewayV2::ApiMapping'
Properties:
DomainName: api.example.com
ApiMappingKey: 'orders/v2/items'
ApiId: !Ref MyApi
Stage: !Ref MyStage
The following AWS CLI command disables the default endpoint for an HTTP API.
After you disable the default endpoint, you must deploy your API for the change to take effect, unless
automatic deployments are enabled.
Topics
• Throttling requests to your HTTP API (p. 227)
226
Amazon API Gateway Developer Guide
Throttling
API Gateway throttles requests to your API using the token bucket algorithm, where a token counts for
a request. Specifically, API Gateway examines the rate and a burst of request submissions against all
APIs in your account, per Region. In the token bucket algorithm, a burst can allow pre-defined overrun of
those limits, but other factors can also cause limits to be overrun in some cases.
When request submissions exceed the steady-state request rate and burst limits, API Gateway begins to
throttle requests. Clients may receive 429 Too Many Requests error responses at this point. Upon
catching such exceptions, the client can resubmit the failed requests in a way that is rate limiting.
As an API developer, you can set the target limits for individual API stages or routes to improve overall
performance across all APIs in your account.
Per-account limits are applied to all APIs in an account in a specified Region. The account-level rate limit
can be increased upon request - higher limits are possible with APIs that have shorter timeouts and
smaller payloads. To request an increase of account-level throttling limits per Region, contact the AWS
Support Center. For more information, see Quotas and important notes (p. 813). Note that these limits
can't be higher than the AWS throttling limits.
Route-level throttling
You can set route-level throttling to override the account-level request throttling limits for a specific
stage or for individual routes in your API. The default route throttling limits can' exceed account-level
rate limits.
You can configure route-level throttling by using the AWS CLI. The following command configures
custom throttling for the specified stage and route of an API.
227
Amazon API Gateway Developer Guide
Mutual TLS
You can use mutual TLS along with other authorization and authentication operations (p. 273) that API
Gateway supports. API Gateway forwards the certificates that clients provide to Lambda authorizers and
to backend integrations.
Important
By default, clients can invoke your API by using the execute-api endpoint that API Gateway
generates for your API. To ensure that clients can access your API only by using a custom domain
name with mutual TLS, disable the default execute-api endpoint. To learn more, see the
section called “Disable the default endpoint” (p. 226).
You will need to keep this certificate valid for the lifetime of your domain name. If a certificate expires
and auto-renew fails, all updates to the domain name will be locked. You will need to update the
ownershipVerificationCertificateArn with a valid ownershipVerificationCertificate
before you can make any other changes. The ownershipVerificationCertificate cannot be
used as a server certificate for another mutual TLS domain in API Gateway. If a certificate is directly re-
imported into ACM, the issuer must stay the same.
You must include the complete chain of trust, starting from the issuing CA certificate, up to the root
CA certificate, in your truststore. API Gateway accepts client certificates issued by any CA present in the
chain of trust. The certificates can be from public or private certificate authorities. Certificates can have
a maximum chain length of four. You can also provide self-signed certificates. The following hashing
algorithms are supported in the truststore:
• SHA-256 or stronger
228
Amazon API Gateway Developer Guide
Mutual TLS
• RSA-2048 or stronger
• ECDSA-256 or stronger
API Gateway validates a number of certificate properties. You can use Lambda authorizers to perform
additional checks when a client invokes an API, including checking whether a certificate has been
revoked. API Gateway validates the following properties:
Validation Description
Name chaining / key chaining The names and subjects of certificates must
form an unbroken chain. Certificates can have a
maximum chain length of four.
-----BEGIN CERTIFICATE-----
<Certificate contents>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<Certificate contents>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<Certificate contents>
-----END CERTIFICATE-----
...
The following AWS CLI command uploads certificates.pem to your Amazon S3 bucket.
After you've uploaded your truststore to Amazon S3, you can configure your custom domain name to use
mutual TLS. Paste the following (slashes included) into a terminal:
229
Amazon API Gateway Developer Guide
Mutual TLS
--mutual-tls-authentication TruststoreUri=s3://bucket-name/key-name
After you create the domain name, you must configure DNS records and basepath mappings for API
operations. To learn more, see Setting up a regional custom domain name in API Gateway (p. 531).
The following example curl command sends a request to api.example.com, that includes my-
cert.pem in the request. my-key.key is the private key for the certificate.
Your API is invoked only if your truststore trusts the certificate. The following conditions will cause API
Gateway to fail the TLS handshake and deny the request with a 403 status code. If your certificate:
• isn't trusted
• is expired
• doesn't use a supported algorithm
Note
API Gateway doesn't verify if a certificate has been revoked.
Use Amazon S3 versioning to maintain multiple versions of your truststore. When you update your
custom domain name to use a new truststore version, API Gateway returns warnings if certificates are
invalid.
API Gateway produces certificate warnings only when you update your domain name. API Gateway
doesn’t notify you if a previously uploaded certificate expires.
The following AWS CLI command updates a custom domain name to use a new truststore version.
230
Amazon API Gateway Developer Guide
Monitor
You'll need to decode the certificates in your truststore in order to identify which certificate produced
the warning. You can use tools such as openssl to decode the certificates and identify their subjects.
The following command displays the contents of a certificate, including its subject:
Update or remove the certificates that produced warnings, and then upload a new truststore to Amazon
S3. After uploading the new truststore, update your custom domain name to use the new truststore.
PENDING_OWNERSHIP_VERIFICATION: This means your previously verified certificate has expired and
ACM was unable to auto-renew it. You will need to renew the certificate or request a new certificate.
More information about certificate renewal can be found at ACM's troubleshooting managed certificate
renewal guide.
Topics
231
Amazon API Gateway Developer Guide
Metrics
The following metrics are supported for HTTP APIs. You can also enable detailed metrics to write route-
level metrics to Amazon CloudWatch.
Metric Description
You can use the dimensions in the following table to filter API Gateway metrics.
Dimension Description
232
Amazon API Gateway Developer Guide
Logging
Dimension Description
specified API ID, stage ID, and
route ID.
1. Ensure that your IAM user has the required permissions to enable logging.
2. Create a CloudWatch Logs log group.
3. Provide the ARN of the CloudWatch Logs log group for a stage of your API.
Example
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:GetLogEvents",
"logs:FilterLogEvents"
],
"Resource": "arn:aws:logs:us-east-2:123456789012:log-group:*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogDelivery",
"logs:PutResourcePolicy",
"logs:UpdateLogDelivery",
"logs:DeleteLogDelivery",
"logs:CreateLogGroup",
"logs:DescribeResourcePolicies",
233
Amazon API Gateway Developer Guide
Logging
"logs:GetLogDelivery",
"logs:ListLogDeliveries"
],
"Resource": "*"
}
]
}
You need the Amazon Resource Name (ARN) for your log group to enable logging. The ARN format is
arn:aws:logs:region:account-id:log-group:log-group-name.
• JSON:
• XML:
234
Amazon API Gateway Developer Guide
Logging
$context.identity.sourceIp,$context.requestTime,$context.httpMethod,$context.routeKey,
$context.protocol,$context.status,$context.responseLength,$context.requestId
Parameter Description
"context" : {
"key": "value",
"numKey": 1,
"boolKey": true
}
calling $context.authorizer.key
returns the "value" string, calling
$context.authorizer.numKey returns the 1,
and calling $context.authorizer.boolKey
returns true.
235
Amazon API Gateway Developer Guide
Logging
Parameter Description
api.example.com/v1/orders/1234, and
the request matches the API mapping with
the path v1/orders, the value is v1/orders.
To learn more, see the section called “API
mappings” (p. 224).
$context.domainName The full domain name used to invoke the API. This
should be the same as the incoming Host header.
236
Amazon API Gateway Developer Guide
Logging
Parameter Description
237
Amazon API Gateway Developer Guide
Logging
Parameter Description
238
Amazon API Gateway Developer Guide
Troubleshooting
Parameter Description
Topics
• Troubleshooting issues with HTTP API Lambda integrations (p. 239)
• Troubleshooting issues with HTTP API JWT authorizers (p. 241)
239
Amazon API Gateway Developer Guide
Lambda integrations
$curl https://api-id.execute-api.us-west-2.amazonaws.com/route
Your logs might include a different error message that indicates that there's a problem with your Lambda
function code. In that case, check your Lambda function code, and verify that your Lambda function
returns a response in the required format (p. 200). If your logs don't include an error message, add
$context.error.message and $context.error.responseType to your log format for more
information to help troubleshoot.
In this case, the logs show that API Gateway didn't have the required permissions to invoke the Lambda
function.
When you create a Lambda integration in the API Gateway console, API Gateway automatically
configures permissions to invoke the Lambda function. When you create a Lambda integration by using
the AWS CLI, AWS CloudFormation, or an SDK, you must grant permissions for API Gateway to invoke the
function. The following AWS CLI command grants permissions for the $default stage and $default
route of an HTTP API to invoke a Lambda function.
240
Amazon API Gateway Developer Guide
JWT authorizers
Confirm the function policy in the Permissions tab of the Lambda console.
Try invoking your API again. You should see your Lambda function's response.
The following command uses curl to send a request to an API with a JWT authorizer that uses
$request.header.Authorization as its identity source.
...
< HTTP/1.1 401 Unauthorized
< Date: Wed, 13 May 2020 04:07:30 GMT
< Content-Length: 26
< Connection: keep-alive
< www-authenticate: Bearer scope="" error="invalid_token" error_description="the token does
not have a valid audience"
< apigw-requestid: Mc7UVioPPHcEKPA=
<
* Connection #0 to host api-id.execute-api.us-west-2.amazonaws.com left intact
{"message":"Unauthorized"}}
In this case, the www-authenticate header shows that the token wasn't issued for a valid audience. For
API Gateway to authorize a request, the JWT's aud or client_id claim must match one of the audience
entries that's configured for the authorizer.
You can also decode a JWT and verify that it matches the issuer, audience, and scopes that your API
requires. The website jwt.io can debug JWTs in the browser. The OpenID Foundation maintains a list of
libraries for working with JWTs.
To learn more about JWT authorizers, see Controlling access to HTTP APIs with JWT
authorizers (p. 195).
241
Amazon API Gateway Developer Guide
Develop
API Gateway REST APIs use a request/response model where a client sends a request to a service and
the service responds back synchronously. This kind of model is suitable for many different kinds of
applications that depend on synchronous communication.
Topics
• Developing a REST API in API Gateway (p. 242)
• Publishing REST APIs for customers to invoke (p. 490)
• Optimizing performance of REST APIs (p. 539)
• Distributing your REST API to clients (p. 548)
• Protecting your REST API (p. 630)
• Monitoring REST APIs (p. 672)
As you're developing your API Gateway API, you decide on a number of characteristics of your API. These
characteristics depend on the use case of your API. For example, you might want to only allow certain
clients to call your API, or you might want it to be available to everyone. You might want an API call to
execute a Lambda function, make a database query, or call an application.
Topics
• Creating a REST API in Amazon API Gateway (p. 242)
• Controlling and managing access to a REST API in API Gateway (p. 273)
• Setting up REST API integrations (p. 323)
• Enable request validation in API Gateway (p. 364)
• Setting up data transformations for REST APIs (p. 376)
• Gateway responses in API Gateway (p. 422)
• Enabling CORS for a REST API resource (p. 429)
• Working with binary media types for REST APIs (p. 436)
• Invoking a REST API in Amazon API Gateway (p. 458)
• Configuring a REST API using OpenAPI (p. 480)
242
Amazon API Gateway Developer Guide
Create and configure
endpoint, also known as the integration endpoint, by forwarding the incoming request to a specified
integration endpoint URI. If necessary, you transform request parameters or body to meet the backend
requirements. For responses, you can create a MethodResponse resource to represent a request
response received by the client and you create an IntegrationResponse resource to represent
the request response that is returned by the backend. You can configure the integration response to
transform the backend response data before returning the data to the client or to pass the backend
response as-is to the client.
To help your customers understand your API, you can also provide documentation for the API, as part
of the API creation or after the API is created. To enable this, add a DocumentationPart resource for a
supported API entity.
To control how clients call an API, use IAM permissions (p. 290), a Lambda authorizer (p. 299), or
an Amazon Cognito user pool (p. 315). To meter the use of your API, set up usage plans (p. 549) to
throttle API requests. You can enable these when creating or updating the API.
You can perform these and other tasks by using the API Gateway console, the API Gateway REST API, the
AWS CLI, or one of the AWS SDKs. We discuss how to perform these tasks next.
Topics
• Choose an endpoint type to set up for an API Gateway API (p. 243)
• Initialize REST API setup in API Gateway (p. 245)
• Set up REST API methods in API Gateway (p. 261)
An API endpoint (p. 6) type refers to the hostname of the API. The API endpoint type can be edge-
optimized, regional, or private, depending on where the majority of your API traffic originates from.
Edge-optimized APIs capitalize the names of HTTP headers (for example, Cookie).
CloudFront sorts HTTP cookies in natural order by cookie name before forwarding the request to your
origin. For more information about the way CloudFront processes cookies, see Caching Content Based on
Cookies.
Any custom domain name that you use for an edge-optimized API applies across all regions.
For a regional API, any custom domain name that you use is specific to the region where the API
is deployed. If you deploy a regional API in multiple regions, it can have the same custom domain
name in all regions. You can use custom domains together with Amazon Route 53 to perform tasks
such as latency-based routing. For more information, see the section called “Setting up a regional
custom domain name” (p. 531) and the section called “Creating an edge-optimized custom domain
name” (p. 527).
243
Amazon API Gateway Developer Guide
Create and configure
If you are changing a public API from edge-optimized to regional or vice versa, note that an edge-
optimized API may have different behaviors than a regional API. For example, an edge-optimized API
removes the Content-MD5 header. Any MD5 hash value passed to the backend can be expressed in
a request string parameter or a body property. However, the regional API passes this header through,
although it may remap the header name to some other name. Understanding the differences helps
you decide how to update an edge-optimized API to a regional one or from a regional API to an edge-
optimized one.
Topics
• Use the API Gateway console to change an API endpoint type (p. 244)
• Use the AWS CLI to change an API endpoint type (p. 245)
To change the API endpoint type of your API, perform one of the following sets of steps:
244
Amazon API Gateway Developer Guide
Create and configure
4. Choose Settings.
5. Change the Endpoint Type to Regional.
6. Choose Save Changes to start the update.
7. Remove the resource policy from your API.
8. Redeploy your API so that the changes will take effect.
To use the AWS CLI to update an edge-optimized API whose API ID is {api-id}, call update-rest-api as
follows:
The successful response has a status code of 200 OK and a payload similar to the following:
"createdDate": "2017-10-16T04:09:31Z",
"description": "Your first API with Amazon API Gateway. This is a sample API that
integrates via HTTP with our demo Pet Store endpoints",
"endpointConfiguration": {
"types": "REGIONAL"
},
"id": "0gsnjtjck8",
"name": "PetStore imported as edge-optimized"
}
Because put-rest-api is for updating API definitions, it is not applicable to updating an API endpoint type.
Because of the default settings, the resulting API is edge-optimized. An alternative is to set up a
regional API (p. 259). To set up a regional API, you must set explicitly the endpoint type of the
API as REGIONAL. To set up an edge-optimized API explicitly, you can set EDGE as the type of the
endpointConfiguration.
When setting up an API, you must choose a region. When deployed, the API is region-specific.
For an edge-optimized API, the base URL is of the http[s]://{restapi-id}.execute-
api.amazonaws.com/stage format, where {restapi-id} is the API's id value generated by API
Gateway. You can assign a custom domain name (for example, apis.example.com) as the API's host
name and call the API with a base URL of the https://apis.example.com/myApi format.
245
Amazon API Gateway Developer Guide
Create and configure
Topics
• Set up an API using the API Gateway console (p. 246)
• Set up an edge-optimized API using AWS CLI commands (p. 246)
• Set up an edge-optimized API using the AWS SDK for Node.js (p. 251)
• Set up an edge-optimized API by importing OpenAPI definitions (p. 257)
• Set up a regional API in API Gateway (p. 259)
You can learn how to set up an API by following an example. For more information, see Tutorial: Create a
REST API by importing an example (p. 46).
Alternatively, you can set up an API by using the API Gateway Import API (p. 480) feature to upload
an external API definition, such as one expressed in OpenAPI 2.0 with the Working with API Gateway
extensions to OpenAPI (p. 744). The example provided in Tutorial: Create a REST API by importing an
example (p. 46) uses the Import API feature.
1. Call the create-rest-api command to set up the RestApi in a specific region (us-west-2).
aws apigateway create-rest-api --name 'Simple PetStore (AWS CLI)' --region us-west-2
{
"name": "Simple PetStore (AWS CLI)",
"id": "vaz7da96z6",
"createdDate": 1494572809
}
Note the returned id of the newly created RestApi. You need it to set up other parts of the API.
2. Call the get-resources command to retrieve the root resource identifier of the RestApi.
{
"items": [
{
"path": "/",
"id": "begaltmsm8"
}
]
246
Amazon API Gateway Developer Guide
Create and configure
Note the root resource Id. You need it to start setting the API's resource tree and configuring
methods and integrations.
3. Call the create-resource command to append a child resource (pets) under the root resource
(begaltmsm8):
{
"path": "/pets",
"pathPart": "pets",
"id": "6sxz2j",
"parentId": "begaltmsm8"
}
To append a child resource under the root, you specify the root resource Id as the parentId
property value. Similarly, to append a child resource under the pets resource, you repeat the
preceding step while replacing the parent-id value with the pets resource id of 6sxz2j:
To make a path part a path parameter, enclose it in a pair of curly brackets. If successful, this
command returns the following response:
{
"path": "/pets/{petId}",
"pathPart": "{petId}",
"id": "rjkmth",
"parentId": "6sxz2j"
}
Now that you created two resources: /pets (6sxz2j) and /pets/{petId} (rjkmth), you can
proceed to set up methods on them.
4. Call the put-method command to add the GET HTTP method on the /pets resource. This creates
an API Method of GET /pets with open access, referencing the /pets resource by its ID value of
6sxz2j.
{
"apiKeyRequired": false,
247
Amazon API Gateway Developer Guide
Create and configure
"httpMethod": "GET",
"authorizationType": "NONE"
}
The method is for open access because authorization-type is set to NONE. To permit only
authenticated users to call the method, you can use IAM roles and policies, a Lambda authorizer
(formerly known as a custom authorizer), or an Amazon Cognito user pool. For more information,
see the section called “Access control” (p. 273).
To enable read access to the /pets/{petId} resource (rjkmth), add the GET HTTP method on it to
create an API Method of GET /pets/{petId} as follows.
{
"apiKeyRequired": false,
"httpMethod": "GET",
"authorizationType": "NONE",
"requestParameters": {
"method.request.path.petId": true
}
}
Note that the method request path parameter of petId must be specified as a required request
parameter for its dynamically set value to be mapped to a corresponding integration request
parameter and passed to the backend.
5. Call the put-method-response command to set up the 200 OK response of the GET /pets
method, specifying the /pets resource by its ID value of 6sxz2j.
{
"statusCode": "200"
}
Similarly, to set the 200 OK response of the GET /pets/{petId} method, do the following,
specifying the /pets/{petId} resource by its resource ID value of rjkmth:
Having set up a simple client interface for the API, you can proceed to set up the integration of the
API methods with the backend.
6. Call the put-integration command to set up an Integration with a specified HTTP endpoint
for the GET /pets method. The /pets resource is identified by its resource Id 6sxz2j:
248
Amazon API Gateway Developer Guide
Create and configure
{
"httpMethod": "GET",
"passthroughBehavior": "WHEN_NO_MATCH",
"cacheKeyParameters": [],
"type": "HTTP",
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"cacheNamespace": "6sxz2j"
}
Similarly, you create an integration request for the GET /pets/{petId} method as follows:
{
"passthroughBehavior": "WHEN_NO_MATCH",
"cacheKeyParameters": [],
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}",
"httpMethod": "GET",
"cacheNamespace": "rjkmth",
"type": "HTTP",
"requestParameters": {
"integration.request.path.id": "method.request.path.petId"
}
}
249
Amazon API Gateway Developer Guide
Create and configure
{
"selectionPattern": "",
"statusCode": "200"
}
With the preceding steps, you finished setting up a simple API that allows your customers to query
available pets on the PetStore website and to view an individual pet of a specified identifier. To
make it callable by your customer, you must deploy the API.
8. Deploy the API to a stage stage, for example, by calling create-deployment:
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
{
"id": 3,
"type": "fish",
250
Amazon API Gateway Developer Guide
Create and configure
"price": 0.99
}
Setting up an API using the AWS SDK for Node.js involves calling the createRestApi,
createResource or getResources, putMethod, putMethodResponse, putIntegration, and
putIntegrationResponse functions.
The following procedures walk you through the essential steps to use these SDK commands to set up a
simple PetStore API supporting the GET /pets and GET /pets/{petId} methods.
To set up a simple PetStore API using the AWS SDK for Node.js
AWS.config.region = 'us-west-2';
var apig = new AWS.APIGateway({apiVersion: '2015/07/09'});
apig.createRestApi({
name: "Simple PetStore (node.js SDK)",
binaryMediaTypes: [
'*'
],
description: "Demo API created using the AWS SDK for node.js",
version: "0.00.001"
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log('Create API failed:\n', err);
}
});
{
id: 'iuo308uaq7',
name: 'PetStore (node.js SDK)',
description: 'Demo API created using the AWS SDK for node.js',
createdDate: 2017-09-05T19:32:35.000Z,
version: '0.00.001',
binaryMediaTypes: [ '*' ]
}
The resulting API's identifier is iuo308uaq7. You need to supply this to continue the setup of the
API.
3. Call the getResources function to retrieve the root resource identifier of the RestApi.
apig.getResources({
restApiId: 'iuo308uaq7'
251
Amazon API Gateway Developer Guide
Create and configure
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log('Get the root resource failed:\n', err);
}
})
{
"items": [
{
"path": "/",
"id": "s4fb0trnk0"
}
]
}
The root resource identifier is s4fb0trnk0. This is the starting point for you to build the API
resource tree, which you do next.
4. Call the createResource function to set up the /pets resource for the API, specifying the root
resource identifier (s4fb0trnk0) on the parentId property.
apig.createResource({
restApiId: 'iuo308uaq7',
parentId: 's4fb0trnk0',
pathPart: 'pets'
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("The '/pets' resource setup failed:\n", err);
}
})
{
"path": "/pets",
"pathPart": "pets",
"id": "8sxa2j",
"parentId": "s4fb0trnk0'"
}
To set up the /pets/{petId} resource, call the following createResource function, specifying
the newly created /pets resource (8sxa2j) on the parentId property.
apig.createResource({
restApiId: 'iuo308uaq7',
parentId: '8sxa2j',
pathPart: '{petId}'
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("The '/pets/{petId}' resource setup failed:\n", err);
}
})
252
Amazon API Gateway Developer Guide
Create and configure
{
"path": "/pets/{petId}",
"pathPart": "{petId}",
"id": "au5df2",
"parentId": "8sxa2j"
}
Throughout this procedure, you refer to the /pets resource by specifying its resource ID of 8sxa2j,
and the /pets/{petId} resource by specifying its resource ID of au5df2.
5. Call the putMethod function to add the GET HTTP method on the /pets resource (8sxa2j). This
sets up the GET /pets Method with open access.
apig.putMethod({
restApiId: 'iuo308uaq7',
resourceId: '8sxa2j,
httpMethod: 'GET',
authorizationType: 'NONE'
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("The 'GET /pets' method setup failed:\n", err);
}
})
{
"apiKeyRequired": false,
"httpMethod": "GET",
"authorizationType": "NONE"
}
To add the GET HTTP method on the /pets/{petId} resource (au5df2), which sets up the API
method of GET /pets/{petId} with open access, call the putMethod function as follows.
apig.putMethod({
restApiId: 'iuo308uaq7',
resourceId: 'au5df2',
httpMethod: 'GET',
authorizationType: 'NONE',
requestParameters: {
"method.request.path.petId" : true
}
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("The 'GET /pets/{petId}' method setup failed:\n", err);
}
})
{
"apiKeyRequired": false,
253
Amazon API Gateway Developer Guide
Create and configure
"httpMethod": "GET",
"authorizationType": "NONE",
"requestParameters": {
"method.request.path.petId": true
}
}
You need to set the requestParameters property as shown in the preceding example to map and
pass the client-supplied petId value to the backend.
6. Call the putMethodResponse function to set up a method response for the GET /pets method.
apig.putMethodResponse({
restApiId: 'iuo308uaq7',
resourceId: "8sxa2j",
httpMethod: 'GET',
statusCode: '200'
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("Set up the 200 OK response for the 'GET /pets' method failed:\n", err);
}
})
{
"statusCode": "200"
}
To set the 200 OK response of the GET /pets/{petId} method, call the putMethodResponse
function, specifying the /pets/{petId} resource identifier (au5df2) on the resourceId property.
apig.putMethodResponse({
restApiId: 'iuo308uaq7',
resourceId: "au5df2",
httpMethod: 'GET',
statusCode: '200'
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("Set up the 200 OK response for the 'GET /pets/{petId}' method failed:
\n", err);
}
})
7. Call the putIntegration function to set up the Integration with a specified HTTP endpoint
for the GET /pets method, supplying the /pets resource identifier (8sxa2j) on the parentId
property.
apig.putIntegration({
restApiId: 'iuo308uaq7',
resourceId: '8sxa2j',
httpMethod: 'GET',
type: 'HTTP',
integrationHttpMethod: 'GET',
uri: 'http://perstore-demo-endpoint.execute-api.com/pets'
254
Amazon API Gateway Developer Guide
Create and configure
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("Set up the integration of the 'GET /' method of the API failed:\n",
err);
}
})
{
"httpMethod": "GET",
"passthroughBehavior": "WHEN_NO_MATCH",
"cacheKeyParameters": [],
"type": "HTTP",
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"cacheNamespace": "8sxa2j"
}
To set up the integration of the GET /pets/{petId} method with the HTTP endpoint of http://
perstore-demo-endpoint.execute-api.com/pets/{id} of the backend, call the following
putIntegration function, supplying the API's /pets/{petId} resource identifier (au5df2) on
the parentId property.
apig.putIntegration({
restApiId: 'iuo308uaq7',
resourceId: 'au5df2',
httpMethod: 'GET',
type: 'HTTP',
integrationHttpMethod: 'GET',
uri: 'http://perstore-demo-endpoint.execute-api.com/pets/{id}',
requestParameters: {
"integration.request.path.id": "method.request.path.petId"
}
}, function(err, data){
if (!err) {
console.log(data);
} else {
console.log("The 'GET /pets/{petId}' method integration setup failed:\n", err);
}
})
{
"httpMethod": "GET",
"passthroughBehavior": "WHEN_NO_MATCH",
"cacheKeyParameters": [],
"type": "HTTP",
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}",
"cacheNamespace": "au5df2",
"requestParameters": {
"integration.request.path.id": "method.request.path.petId"
}
}
255
Amazon API Gateway Developer Guide
Create and configure
8. Call the putIntegrationResponse function to set up the 200 OK integration response for the
GET /pets method, specifying the API's /pets resource identifier (8sxa2j) on the resourceId
property.
apig.putIntegrationResponse({
restApiId: 'iuo308uaq7',
resourceId: '8sxa2j',
httpMethod: 'GET',
statusCode: '200',
selectionPattern: ''
}, function(err, data){
if (!err) {
console.log(data);
} else
console.log("The 'GET /pets' method integration response setup failed:\n", err);
})
{
"selectionPattern": "",
"statusCode": "200"
}
To set up the 200 OK integration response of the GET /pets/{petId} method, call the
putIntegrationResponse function, specifying the API's /pets/{petId} resource identifier
(au5df2) on the resourceId property.
apig.putIntegrationResponse({
restApiId: 'iuo308uaq7',
resourceId: 'au5df2',
httpMethod: 'GET',
statusCode: '200',
selectionPattern: ''
}, function(err, data){
if (!err) {
console.log(data);
} else
console.log("The 'GET /pets/{petId}' method integration response setup failed:\n",
err);
})
9. As a good practice, test invoking the API before deploying it. To test invoking the GET /pets
method, call the testInvokeMethod, specifying the /petsresource identifier (8sxa2j) on the
resourceId property:
apig.testInvokeMethod({
restApiId: 'iuo308uaq7',
resourceId: '8sxa2j',
httpMethod: "GET",
pathWithQueryString: '/'
}, function(err, data){
if (!err) {
console.log(data)
} else {
console.log('Test-invoke-method on 'GET /pets' failed:\n', err);
}
})
256
Amazon API Gateway Developer Guide
Create and configure
To test invoking the GET /pets/{petId} method, call the testInvokeMethod, specifying the /
pets/{petId} resource identifier (au5df2) on the resourceId property:
apig.testInvokeMethod({
restApiId: 'iuo308uaq7',
resourceId: 'au5df2',
httpMethod: "GET",
pathWithQueryString: '/'
}, function(err, data){
if (!err) {
console.log(data)
} else {
console.log('Test-invoke-method on 'GET /pets/{petId}' failed:\n', err);
}
})
10. Finally, you can deploy the API for your customers to call.
apig.createDeployment({
restApiId: 'iuo308uaq7',
stageName: 'test',
stageDescription: 'test deployment',
description: 'API deployment'
}, function(err, data){
if (err) {
console.log('Deploying API failed:\n', err);
} else {
console.log("Deploying API succeeded\n", data);
}
})
The following OpenAPI definitions describe the simple API, exposing only the GET / method integrated
with an HTTP endpoint of the PetStore website in the backend, and returning a 200 OK response.
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"title": "Simple PetStore (OpenAPI)"
},
"schemes": [
"https"
],
"paths": {
"/pets": {
"get": {
"responses": {
"200": {
"description": "200 response"
}
},
"x-amazon-apigateway-integration": {
"responses": {
257
Amazon API Gateway Developer Guide
Create and configure
"default": {
"statusCode": "200"
}
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "http"
}
}
},
"/pets/{petId}": {
"get": {
"parameters": [
{
"name": "petId",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response"
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.path.id": "method.request.path.petId"
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "http"
}
}
}
}
}
The following procedure describes how to import these OpenAPI definitions into API Gateway using the
API Gateway console.
To import the simple OpenAPI definitions using the API Gateway console
To import the OpenAPI definitions using the AWS CLI, save the OpenAPI definitions into a file and then
run the following command, assuming that you use the us-west-2 region and the absolute OpenAPI
file path is file:///path/to/API_OpenAPI_template.json:
258
Amazon API Gateway Developer Guide
Create and configure
To create a regional API, you follow the steps in creating an edge-optimized API (p. 245), but must
explicitly set REGIONAL type as the only option of the API's endpointConfiguration.
In the following, we show how to create a regional API using the API Gateway console, AWS CLI, and the
AWS SDK for Javascript for Node.js.
Topics
• Create a regional API using the API Gateway console (p. 259)
• Create a regional API using the AWS CLI (p. 259)
• Create a regional API using the AWS SDK for JavaScript (p. 260)
• Test a regional API (p. 260)
If this is not your first time using API Gateway, choose Create API. Under REST API, choose Build.
From here on, you can proceed to set up API methods and their associated integrations as described in
creating an edge optimized API (p. 246).
To create a regional API using the AWS CLI, call the create-rest-api command:
259
Amazon API Gateway Developer Guide
Create and configure
{
"createdDate": "2017-10-13T18:41:39Z",
"description": "Simple regional PetStore API",
"endpointConfiguration": {
"types": "REGIONAL"
},
"id": "0qzs2sy7bh",
"name": "Simple PetStore (AWS CLI, Regional)"
}
From here on, you can follow the same instructions given in the section called “Set up an edge-optimized
API using AWS CLI commands” (p. 246) to set up methods and integrations for this API.
apig.createRestApi({
name: "Simple PetStore (node.js SDK, regional)",
endpointConfiguration: {
types: ['REGIONAL']
},
description: "Demo regional API created using the AWS SDK for node.js",
version: "0.00.001"
}, function(err, data){
if (!err) {
console.log('Create API succeeded:\n', data);
restApiId = data.id;
} else {
console.log('Create API failed:\n', err);
}
});
{
"createdDate": "2017-10-13T18:41:39Z",
"description": "Demo regional API created using the AWS SDK for node.js",
"endpointConfiguration": {
"types": "REGIONAL"
},
"id": "0qzs2sy7bh",
"name": "Simple PetStore (node.js SDK, regional)"
}
After completing the preceding steps, you can follow the instructions in the section called “Set up an
edge-optimized API using the AWS SDK for Node.js” (p. 251) to set up methods and integrations for
this API.
{restapi-id}.execute-api.{region}.amazonaws.com
260
Amazon API Gateway Developer Guide
Create and configure
https://{restapi-id}.execute-api.{region}.amazonaws.com/{stage}
Assuming you set up the GET /pets and GET /pets/{petId} methods in this example, you can test
the API by typing the following URLs in a browser:
https://0qzs2sy7bh.execute-api.us-west-2.amazonaws.com/test/pets
and
https://0qzs2sy7bh.execute-api.us-west-2.amazonaws.com/test/pets/1
and
An API method request is an HTTP request. To set up the method request, you configure an HTTP
method (or verb), the path to an API resource, headers, applicable query string parameters. You also
configure a payload when the HTTP method is POST, PUT, or PATCH. For example, to retrieve a pet using
the PetStore sample API (p. 46), you define the API method request of GET /pets/{petId}, where
{petId} is a path parameter that can take a number at run time.
GET /pets/1
Host: apigateway.us-east-1.amazonaws.com
...
If the client specifies an incorrect path, for example, /pet/1 or /pets/one instead of /pets/1, an
exception is thrown.
An API method response is an HTTP response with a given status code. For a non-proxy integration, you
must set up method responses to specify the required or optional targets of mappings. These transform
integration response headers or body to associated method response headers or body. The mapping
can be as simple as an identity transform that passes the headers or body through the integration as-
is. For example, the following 200 method response shows an example of passthrough of a successful
integration response as-is.
200 OK
Content-Type: application/json
...
261
Amazon API Gateway Developer Guide
Create and configure
{
"id": "1",
"type": "dog",
"price": "$249.99"
}
In principle, you can define a method response corresponding to a specific response from the backend.
Typically, this involves any 2XX, 4XX, and 5XX responses. However, this may not be practical, because
often you may not know in advance all the responses that a backend may return. In practice, you can
designate one method response as the default to handle the unknown or unmapped responses from the
backend. It is good practice to designate the 500 response as the default. In any case, you must set up
at least one method response for non-proxy integrations. Otherwise, API Gateway returns a 500 error
response to the client even when the request succeeds at the backend.
To support a strongly typed SDK, such as a Java SDK, for your API, you should define the data model for
input for the method request, and define the data model for output of the method response.
Topics
• Set up a method request in API Gateway (p. 262)
• Set up method responses in API Gateway (p. 268)
• Set up a method using the API Gateway console (p. 270)
For examples of using these tools, see Initialize REST API setup in API Gateway (p. 245).
Topics
• Set up API resources (p. 263)
• Set up an HTTP method (p. 265)
• Set up method request parameters (p. 265)
• Set up method request model (p. 266)
• Set up method request authorization (p. 267)
• Set up method request validation (p. 268)
262
Amazon API Gateway Developer Guide
Create and configure
The API endpoint can be a default host name or a custom domain name. The default host name is of the
following format:
{api-id}.execute-api.{region}.amazonaws.com
In this format, the {api-id} represents the API identifier that is generated by API Gateway. The
{region} variable represents the AWS Region (for example, us-east-1) that you chose when creating
the API. A custom domain name is any user-friendly name under a valid internet domain. For example,
if you have registered an internet domain of example.com, any of *.example.com is a valid custom
domain name. For more information, see create a custom domain name (p. 518).
For the PetStore sample API (p. 46), the root resource (/) exposes the pet store. The /pets resource
represents the collection of pets available in the pet store. The /pets/{petId} exposes an individual
pet of a given identifier (petId). The path parameter of {petId} is part of the request parameters.
To set up an API resource, you choose an existing resource as its parent and then create the child
resource under this parent resource. You start with the root resource as a parent, add a resource to this
parent, add another resource to this child resource as the new parent, and so on, to its parent identifier.
Then you add the named resource to the parent.
With AWS CLI, you can call the get-resources command to find out which resources of an API are
available:
The result is a list of the currently available resources of the API. For our PetStore sample API, this list
looks like the following:
{
"items": [
{
"path": "/pets",
"resourceMethods": {
"GET": {}
},
"id": "6sxz2j",
"pathPart": "pets",
"parentId": "svzr2028x8"
},
{
"path": "/pets/{petId}",
"resourceMethods": {
"GET": {}
},
"id": "rjkmth",
"pathPart": "{petId}",
"parentId": "6sxz2j"
},
{
"path": "/",
"id": "svzr2028x8"
}
]
263
Amazon API Gateway Developer Guide
Create and configure
Each item lists the identifiers of the resource (id) and, except for the root resource, its immediate parent
(parentId), as well as the resource name (pathPart). The root resource is special in that it does not
have any parent. After choosing a resource as the parent, call the following command to add a child
resource.
For example, to add pet food for sale on the PetStore website, add a food resource to the root (/) by
setting path-part to food and parent-id to svzr2028x8. The result looks like the following:
{
"path": "/food",
"pathPart": "food",
"id": "xdsvhp",
"parentId": "svzr2028x8"
}
API Gateway defines a proxy resource as a placeholder for a resource to be specified when the request is
submitted. A proxy resource is expressed by a special path parameter of {proxy+}, often referred to as a
greedy path parameter. The + sign indicates whichever child resources are appended to it. The /parent/
{proxy+} placeholder stands for any resource matching the path pattern of /parent/*. The greedy
path parameter name, proxy, can be replaced by another string in the same way you treat a regular path
parameter name.
Using the AWS CLI, you call the following command to set up a proxy resource under the root (/{proxy
+}):
{
"path": "/{proxy+}",
"pathPart": "{proxy+}",
"id": "234jdr",
"parentId": "svzr2028x8"
}
For the PetStore API example, you can use /{proxy+} to represent both the /pets and /pets/
{petId}. This proxy resource can also reference any other (existing or to-be-added) resources, such as
/food/{type}/{item}, /toys/{type}/{item}, etc., or /food/{type}/{subtype}/{item}, /
264
Amazon API Gateway Developer Guide
Create and configure
toys/{type}/{subtype}/{item}, etc. The backend developer determines the resource hierarchy and
the client developer is responsible for understanding it. API Gateway simply passes whatever the client
submitted to the backend.
An API can have more than one proxy resource. For example, the following proxy resources are allowed
within an API.
/{proxy+}
/parent/{proxy+}
/parent/{child}/{proxy+}
When a proxy resource has non-proxy siblings, the sibling resources are excluded from the representation
of the proxy resource. For the preceding examples, /{proxy+} refers to any resources under the root
resource except for the /parent[/*] resources. In other words, a method request against a specific
resource takes precedence over a method request against a generic resource at the same level of the
resource hierarchy.
A proxy resource cannot have any child resource. Any API resource after {proxy+} is redundant and
ambiguous. The following proxy resources are not allowed within an API.
/{proxy+}/child
/parent/{proxy+}/{child}
/parent/{child}/{proxy+}/{grandchild+}
Closely associated with the proxy resource, API Gateway supports an HTTP method of ANY. This ANY
method represents any HTTP method that is to be supplied at run time. It allows you to use a single API
method setup for all of the supported HTTP methods of DELETE, GET, HEAD, OPTIONS, PATCH, POST,
and PUT.
You can set up the ANY method on a non-proxy resource as well. Combining the ANY method with a
proxy resource, you get a single API method setup for all of the supported HTTP methods against any
resources of an API. Furthermore, the backend can evolve without breaking the existing API setup.
Before setting up an API method, consider who can call the method. Set the authorization type according
to your plan. For open access, set it to NONE. To use IAM permissions, set the authorization type to
AWS_IAM. To use a Lambda authorizer function, set this property to CUSTOM. To use an Amazon Cognito
user pool, set the authorization type to COGNITO_USER_POOLS.
The following AWS CLI command shows how to create a method request of the ANY verb against a
specified resource (6sxz2j), using the IAM permissions to control its access.
To create an API method request with a different authorization type, see the section called “Set up
method request authorization” (p. 267).
265
Amazon API Gateway Developer Guide
Create and configure
parameter. As part of method request setup, you must declare required request parameters to make
them available for the client. For non-proxy integration, you can translate these request parameters to a
form that is compatible with the backend requirement.
For example, for the GET /pets/{petId} method request, the {petId} path variable is a required
request parameter. You can declare this path parameter when calling the put-method command of the
AWS CLI. This is illustrated as follows:
If a parameter is not required, you can set it to false in request-parameters. For example, if the
GET /pets method uses an optional query string parameter of type, and an optional header parameter
of breed, you can declare them using the following CLI command, assuming that the /pets resource id
is 6sxz2j:
Instead of this abbreviated form, you can use a JSON string to set the request-parameters value:
'{"method.request.querystring.type":false,"method.request-header.breed":false}'
GET /pets?type=dog
And the client can query dogs of the poodle breed as follows:
GET /pets?type=dog
breed:poodle
For information on how to map method request parameters to integration request parameters, see the
section called “Integrations” (p. 323).
For an API method that can take input data in a payload, you can use a model. A model is expressed in
a JSON schema draft 4 and describes the data structure of the request body. With a model, a client can
determine how to construct a method request payload as input. More importantly, API Gateway uses the
model to validate a request (p. 364), generate an SDK (p. 604), and initialize a mapping template for
setting up the integration in the API Gateway console. For information about how to create a model, see
Models and Mapping Templates (p. 377).
Depending on the content types, a method payload can have different formats. A model is indexed
against the media type of the applied payload. API Gateway uses the Content-Type request header
to determine the content type. To set up method request models, add key-value pairs of the "<media-
266
Amazon API Gateway Developer Guide
Create and configure
type>":"<model-name>" format to the requestModels map when calling the AWS CLI put-method
command.
To use the same model regardless of the content type, specify $default as the key.
For example, to set a model on the JSON payload of the POST /pets method request of the PetStore
example API, you can call the following AWS CLI command:
Here, petModel is the name property value of a Model resource describing a pet. The actual schema
definition is expressed as a JSON string value of the schema property of the Model resource.
In a Java, or other strongly typed SDK, of the API, the input data is cast as the petModel class derived
from the schema definition. With the request model, the input data in the generated SDK is cast into the
Empty class, which is derived from the default Empty model. In this case, the client cannot instantiate
the correct data class to provide the required input.
To control who can call the API method, you can configure the authorization type on the method. You
can use this type to enact one of the supported authorizers, including IAM roles and policies (AWS_IAM),
an Amazon Cognito user pool (COGNITO_USER_POOLS), or a Lambda authorizer (CUSTOM).
To use IAM permissions to authorize access to the API method, set the authorization-type input
property to AWS_IAM. When this option is set, API Gateway verifies the caller's signature on the request,
based on the caller's IAM user's access key identifier and secret key. If the verified user has permission
to call the method, the request is accepted. Otherwise, the request is rejected and the caller receives an
unauthorized error response. The call to the method does not succeed unless the caller has been granted
permission to invoke the API method or if the caller is allowed to assume a role that has been granted
the permission. The caller has permissions to call this and any other API methods created by anyone of
the same AWS account if the caller has the following IAM policy attached to his or her IAM user:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": "arn:aws:execute-api:*:*:*"
}
]
}
For more information, see the section called “Use IAM permissions” (p. 290).
At present, such a policy can be granted to only the IAM users of the API owner's account. Users from a
different AWS account can call the API methods if they are allowed to assume a role of the API owner
account and the assumed role has the proper permissions for the execute-api:Invoke action. For
information on cross-account permissions, see Using IAM Roles.
267
Amazon API Gateway Developer Guide
Create and configure
You can use AWS CLI, an AWS SDK, or a REST API client, such as Postman, which implements Signature
Version 4 Signing.
To use a Lambda authorizer to authorize access to the API method, set the authorization-type
input property to CUSTOM and set the authorizer-id input property to the id property value of
a Lambda authorizer that already exists. The referenced Lambda authorizer can be of the TOKEN or
REQUEST type. For information about creating a Lambda authorizer, see the section called “Use Lambda
authorizers” (p. 299).
To use an Amazon Cognito user pool to authorize access to the API method, set the authorization-
type input property to COGNITO_USER_POOLS and set the authorizer-id input property to the id
property value of the COGNITO_USER_POOLS authorizer that was already created. For information about
creating an Amazon Cognito user pool authorizer, see the section called “Use Amazon Cognito user pool
as authorizer for a REST API” (p. 315).
This CLI command creates a body-only request validator. Example output is as follows:
{
"validateRequestParameters": true,
"validateRequestBody": true,
"id": "jgpyy6",
"name": "bodyOnlyValidator"
}
With this request validator, you can enable request validation as part of the method request setup:
To be included in request validation, a request parameter must be declared as required. If the query
string parameter for the page is used in request validation, the request-parameters map of the
preceding example must be specified as '{"method.request.querystring.type": false,
"method.request.querystring.page":true}'.
With non-proxy integrations, the specified response parameters and body can be mapped from
the associated integration response data or can be assigned certain static values according to
268
Amazon API Gateway Developer Guide
Create and configure
mappings. These mappings are specified in the integration response. The mapping can be an identical
transformation that passes the integration response through as-is.
With a proxy integration, API Gateway passes the backend response through to the method response
automatically. There is no need for you to set up the API method response. However, with the Lambda
proxy integration, the Lambda function must return a result of this output format (p. 340) for API
Gateway to successfully map the integration response to a method response.
Programmatically, the method response setup amounts to creating a MethodResponse resource of API
Gateway and setting the properties of statusCode, responseParameters, and responseModels.
When setting status codes for an API method, you should choose one as the default to handle any
integration response of an unanticipated status code. It is reasonable to set 500 as the default because
this amounts to casting otherwise unmapped responses as a server-side error. For instructional reasons,
the API Gateway console sets the 200 response as the default. But you can reset it to the 500 response.
To set up a method response, you must have created the method request.
The status code of a method response defines a type of response. For example, responses of 200, 400,
and 500 indicate successful, client-side error and server-side error responses, respectively.
To set up a method response status code, set the statusCode property to an HTTP status code. The
following AWS CLI command creates a method response of 200.
Method response parameters define which headers the client receives in response to the associated
method request. Response parameters also specify a target to which API Gateway maps an integration
response parameter, according to mappings prescribed in the API method's integration response.
A method response model defines a format of the method response body. Before setting up the
response model, you must first create the model in API Gateway. To do so, you can call the create-
model command. The following example shows how to create a PetStorePet model to describe the
body of the response to the GET /pets/{petId} method request.
269
Amazon API Gateway Developer Guide
Create and configure
To set up the method response models to define the payload format, add the "application/
json":"PetStorePet" key-value pair to the requestModels map of MethodResponse resource. The
following AWS CLI command of put-method-response shows how this is done:
Setting up a method response model is necessary when you generate a strongly typed SDK for the API.
It ensures that the output is cast into an appropriate class in Java or Objective-C. In other cases, setting a
model is optional.
• You must have the method available in API Gateway. Follow the instructions in Tutorial: Build a REST
API with HTTP non-proxy integration (p. 59).
• If you want the method to communicate with a Lambda function, you must have already created the
Lambda invocation role and Lambda execution role in IAM. You must also have created the Lambda
function with which your method will communicate in AWS Lambda. To create the roles and function,
use the instructions in Create a Lambda function for Lambda non-proxy integration (p. 38) of the Build
an API Gateway REST API with Lambda integration (p. 30).
• If you want the method to communicate with an HTTP or HTTP proxy integration, you must
have already created, and have access to, the HTTP endpoint URL with which your method will
communicate.
• Verify that your certificates for HTTP and HTTP proxy endpoints are supported by API Gateway.
For details see API Gateway-supported certificate authorities for HTTP and HTTP proxy
integrations (p. 638).
Topics
• Set up an API Gateway method request in the API Gateway console (p. 271)
• Set up an API Gateway method response using the API Gateway console (p. 273)
270
Amazon API Gateway Developer Guide
Create and configure
To use the API Gateway console to specify an API's method request/response, and to configure how the
method will authorize requests, follow these instructions.
Note
These instructions assume you have already completed the steps in Set up an API integration
request using the API Gateway console (p. 328). They are best used to supplement the
discussions given in Build an API Gateway REST API with Lambda integration (p. 30).
1. With the method selected in the Resources pane, choose Method Request from the Method
Execution pane.
2. Under Settings, choose the pencil icon to open the Authorization drop-down menu and choose one
of the available authorizers.
a. To enable open access to the method for any user, choose NONE. This step can be skipped if the
default setting has not been changed.
b. To use IAM permissions to control the client access to the method, choose AWS_IAM. With this
choice, only users of the IAM roles with the correct IAM policy attached are allowed to call this
method.
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. For more information about setting the IAM permissions, see Control access to
an API with IAM permissions (p. 290).
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. 38) section of the Build an API Gateway REST API with Lambda integration (p. 30).
271
Amazon API Gateway Developer Guide
Create and configure
4. To require an API key, choose the pencil icon to open the API Key Required drop-down menu and
choose either true or false according to your API requirements. When enabled, API keys are used
in usage plans (p. 549) to throttle client traffic.
5. To add a query string parameter to the method, do the following:
a. Choose the arrow next to URL Query String Parameters, and then choose Add query string.
b. For Name, type the name of the query string parameter.
c. Choose the check-mark icon to save the new query string parameter name.
d. If the newly created query string parameter is to be used for request validation, choose the
Required option. For more information about the request validation, see Enable request
validation in API Gateway (p. 364).
e. If the newly created query string parameter is to be used as part of a caching key, check
the Caching option. This is applicable only when caching is enabled. For more information
about caching, see Use method or integration parameters as cache keys to index cached
responses (p. 541).
Tip
To remove the query string parameter, choose the x icon associated with it and then choose
Remove this parameter and any dependent parameters to confirm the removal.
To change the name of the query string parameter, remove it and then create a new one.
6. To add a header parameter to the method, do the following:
a. Choose the arrow next to HTTP Request Headers, and then choose Add header.
b. For Name, type the name of the header parameter and then choose the check-mark icon to save
the settings.
c. If the newly created header parameter is to be used for request validation, choose the Required
option. For more information about request validation, see Enable request validation in API
Gateway (p. 364).
d. If the newly created header parameter is to be used as part of a caching key, choose the
Caching option. This is applicable only when caching is enabled. For more information
about caching, see Use method or integration parameters as cache keys to index cached
responses (p. 541).
Tip
To remove the header parameter, choose the x icon associated with it and then choose
Remove this parameter and any dependent parameters to confirm the removal.
To change the name of the header parameter, remove it and then create a new one.
7. To declare the payload format of a method request with the POST, PUT, or PATCH HTTP verb,
expand Request Body, and do the following:
The currently available models for the API include the default Empty and Error models as
well as any models you have created and added to the Models collection of the API. For more
information about creating a model, see Create a model in API Gateway (p. 383).
Note
The model is useful to inform the client of the expected data format of a payload. It is
helpful to generate a skeletal mapping template. It is important to generate a strongly
typed SDK of the API in such languages as Java, C#, Objective-C, and Swift. It is only
required if request validation is enabled against the payload.
272
Amazon API Gateway Developer Guide
Access control
8. To assign an operation name in a Java SDK of this API, generated by API Gateway, expand SDK
Settings and type a name in Operation name. For example, for the method request of GET /pets/
{petId}, the corresponding Java SDK operation name is, by default ,GetPetsPetId. This name
is constructed from the method's HTTP verb (GET) and the resource path variable names (Pets
and PetId). If you set the operation name as getPetById, the SDK operation name becomes
GetPetById.
Set up an API Gateway method response using the API Gateway console
An API method can have one or more responses. Each response is indexed by its HTTP status code. By
default, the API Gateway console adds 200 response to the method responses. You can modify it, for
example, to have the method return 201 instead. You can add other responses, for example, 409 for
access denial and 500 for uninitialized stage variables used.
To use the API Gateway console to modify, delete, or add a response to an API method, follow these
instructions.
1. Choose Method Response from Method Execution for a given method of an API resource.
2. To add a new response, choose Add Response.
a. Type an HTTP status code; for example, 200, 400, or 500) for HTTP Status, and then choose the
check-mark icon to save the choice.
When a backend-returned response does not have a corresponding method response defined,
API Gateway fails to return the response to the client. Instead, it returns a 500 Internal
server error error response.
b. Expand the response of the given status code.
c. Choose Add Header.
d. Type a name for Name under Response Headers for {status}, and then choose the check-
mark icon to save the choice.
If you need to translate any backend-returned header to one defined in a method response, you
must first add the method response header as described in this step .
e. Choose Add Response Model under Response Body for {status}.
f. Type the media type of the response payload for Content type and choose a model from the
Models drop-down menu.
g. Choose the check-mark icon to save the settings.
3. To modify an existing response, expand the response and follow Step 2 above.
4. To remove a response, choose the x icon for the response and confirm you want to delete the
response.
For every response returned from the backend, you must have a compatible response configured as the
method response. However, the configuring method response headers and payload model are optional
unless you map the result from the backend to the method response before returning to the client. Also,
a method response payload model is important if you are generating a strongly typed SDK for your API.
You can use the following mechanisms for authentication and authorization:
273
Amazon API Gateway Developer Guide
Access control
• Resource policies let you create resource-based policies to allow or deny access to your APIs and
methods from specified source IP addresses or VPC endpoints. For more information, see the section
called “Use API Gateway resource policies” (p. 274).
• Standard AWS IAM roles and policies offer flexible and robust access controls that can be applied to
an entire API or individual methods. IAM roles and policies can be used for controlling who can create
and manage your APIs, as well as who can invoke them. For more information, see the section called
“Use IAM permissions” (p. 290).
• IAM tags can be used together with IAM policies to control access. For more information, see the
section called “Attribute-based access control” (p. 808).
• Endpoint policies for interface VPC endpoints allow you to attach IAM resource policies to interface
VPC endpoints to improve the security of your private APIs. For more information, see the section
called “Use VPC endpoint policies for private APIs” (p. 297).
• Lambda authorizers are Lambda functions that control access to REST API methods using bearer
token authentication—as well as information described by headers, paths, query strings, stage
variables, or context variables request parameters. Lambda authorizers are used to control
who can invoke REST API methods. For more information, see the section called “Use Lambda
authorizers” (p. 299).
• Amazon Cognito user pools let you create customizable authentication and authorization solutions
for your REST APIs. Amazon Cognito user pools are used to control who can invoke REST API methods.
For more information, see the section called “Use Amazon Cognito user pool as authorizer for a REST
API” (p. 315).
You can use the following mechanisms for performing other tasks related to access control:
• Cross-origin resource sharing (CORS) lets you control how your REST API responds to cross-domain
resource requests. For more information, see the section called “CORS” (p. 429).
• Client-side SSL certificates can be used to verify that HTTP requests to your backend system are from
API Gateway. For more information, see the section called “Client certificates” (p. 635).
• AWS WAF can be used to protect your API Gateway API from common web exploits. For more
information, see the section called “AWS WAF” (p. 662).
You can use the following mechanisms for tracking and limiting the access that you have granted to
authorized clients:
• Usage plans let you provide API keys to your customers—and then track and limit usage of your
API stages and methods for each API key. For more information, see the section called “Usage
plans” (p. 549).
You can use resource policies for all API endpoint types in API Gateway: private, edge-optimized, and
Regional.
274
Amazon API Gateway Developer Guide
Access control
For private APIs, you can use resource policies together with VPC endpoint policies to control which
principals have access to which resources and actions. For more information, see the section called “Use
VPC endpoint policies for private APIs” (p. 297).
You can attach a resource policy to an API by using the AWS Management Console, AWS CLI, or AWS
SDKs.
API Gateway resource policies are different from IAM identity-based policies. IAM identity-based policies
are attached to IAM users, groups, or roles and define what actions those identities are capable of
doing on which resources. API Gateway resource policies are attached to resources. For a more detailed
discussion of the differences between identity-based policies and resource policies, see Identity-Based
Policies and Resource-Based Policies.
You can use API Gateway resource policies together with IAM policies.
Topics
• Access policy language overview for Amazon API Gateway (p. 275)
• How API Gateway resource policies affect authorization workflow (p. 276)
• API Gateway resource policy examples (p. 285)
• Create and attach an API Gateway resource policy to an API (p. 288)
• AWS condition keys that can be used in API Gateway resource policies (p. 289)
Resource policies are specified using the same syntax as IAM policies. For complete policy language
information, see Overview of IAM Policies and AWS Identity and Access Management Policy Reference in
the IAM User Guide.
For information about how an AWS service decides whether a given request should be allowed or denied,
see Determining Whether a Request is Allowed or Denied.
In its most basic sense, a resource policy contains the following elements:
• Resources – APIs are the Amazon API Gateway resources for which you can allow or deny permissions.
In a policy, you use the Amazon Resource Name (ARN) to identify the resource. You can also use
abbreviated syntax, which API Gateway automatically expands to the full ARN when you save a
resource policy. To learn more, see API Gateway resource policy examples (p. 285).
For the format of the full Resource element, see Resource format of permissions for executing API in
API Gateway (p. 294).
• Actions – For each resource, Amazon API Gateway supports a set of operations. You identify resource
operations that you will allow (or deny) by using action keywords.
For example, the execute-api:Invoke permission will allow the user permission to invoke an API
upon a client request.
For the format of the Action element, see Action format of permissions for executing API in API
Gateway (p. 294).
• Effect – What the effect is when the user requests the specific action—this can be either Allow or
Deny. You can also explicitly deny access to a resource, which you might do in order to make sure that
a user cannot access it, even if a different policy grants access.
275
Amazon API Gateway Developer Guide
Access control
Note
"Implicit deny" is the same thing as "deny by default".
An "implicit deny" is different from an "explicit deny". For more information, see The
Difference Between Denying by Default and Explicit Deny.
• Principal – The account or user who is allowed access to the actions and resources in the statement. In
a resource policy, the principal is the IAM user or account who is the recipient of this permission.
The following example resource policy shows the preceding common policy elements. The policy grants
access to the API under the specified account-id in the specified region to any user whose source IP
address is in the address block 123.4.5.6/24. The policy denies all access to the API if the user's source
IP is not within the range.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:region:account-id:*"
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:region:account-id:*",
"Condition": {
"NotIpAddress": {
"aws:SourceIp": "123.4.5.6/24"
}
}
}
]
}
Topics
• API Gateway resource policy only (p. 276)
• Lambda authorizer and resource policy (p. 278)
• IAM authentication and resource policy (p. 280)
• Amazon Cognito authentication and resource policy (p. 282)
• Policy evaluation outcome tables (p. 284)
In this workflow, an API Gateway resource policy is attached to the API, but no authentication type is
defined for the API. Evaluation of the policy involves seeking an explicit allow based on the inbound
criteria of the caller. An implicit denial or any explicit denial results in denying the caller.
276
Amazon API Gateway Developer Guide
Access control
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:region:account-id:api-id/",
"Condition": {
"IpAddress": {
"aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ]
}
}
}
]
}
277
Amazon API Gateway Developer Guide
Access control
In this workflow, a Lambda authorizer is configured for the API in addition to a resource policy. The
resource policy is evaluated in two phases. Before calling the Lambda authorizer, API Gateway first
evaluates the policy and checks for any explicit denials. If found, the caller is denied access immediately.
Otherwise, the Lambda authorizer is called, and it returns a policy document (p. 309), which is
evaluated in conjunction with the resource policy. The result is determined based on Table A (p. 284)
(near the end of this topic).
The following example resource policy allows calls only from the VPC endpoint whose VPC endpoint
ID is vpce-1a2b3c4d. During the "pre-auth" evaluation, only the calls coming from the VPC endpoint
indicated in the example are allowed to move forward and evaluate the Lambda authorizer. All
remaining calls are blocked.
278
Amazon API Gateway Developer Guide
Access control
279
Amazon API Gateway Developer Guide
Access control
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"arn:aws:execute-api:region:account-id:api-id/"
],
"Condition" : {
"StringNotEquals": {
"aws:SourceVpce": "vpce-1a2b3c4d"
}
}
}
]
}
In this workflow, IAM authentication is configured for the API in addition to a resource policy. After
authenticating the user with the IAM service, the policies attached to the IAM user in addition to the
resource policy are evaluated together. The outcome varies based on whether the caller is in the same
account, or a separate AWS account, from the API owner.
If the caller and API owner are from separate accounts, both the IAM user policies and the resource policy
explicitly allow the caller to proceed. (See Table B (p. 284) at the end of this topic.) In contrast, if the
caller and the API owner are in the same account, then either the user policies or the resource policy
must explicitly allow the caller to proceed. (See Table A (p. 284) below.)
280
Amazon API Gateway Developer Guide
Access control
281
Amazon API Gateway Developer Guide
Access control
The following is an example of a cross-account resource policy. Assuming the IAM user policy contains
an allow, this resource policy allows calls only from the VPC whose VPC ID is vpc-2f09a348. (See Table
B (p. 284) at the end of this topic.)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "",
"Action": "execute-api:Invoke",
"Resource": [
"arn:aws:execute-api:region:account-id:api-id/"
],
"Condition" : {
"StringEquals": {
"aws:SourceVpc": "vpc-2f09a348"
}
}
}
]
}
In this workflow, an Amazon Cognito user pool (p. 315) is configured for the API in addition to a
resource policy. API Gateway first attempts to authenticate the caller through Amazon Cognito. This is
typically performed through a JWT token that is provided by the caller. If authentication is successful,
the resource policy is evaluated independently, and an explicit allow is required. A deny or "neither allow
or deny" results in a deny. The following is an example of a resource policy that might be used together
with Amazon Cognito user pools.
282
Amazon API Gateway Developer Guide
Access control
283
Amazon API Gateway Developer Guide
Access control
The following is an example of a resource policy that allows calls only from specified source IPs,
assuming that the Amazon Cognito authentication token contains an allow. (See Table A (p. 284) near
the end of this topic.)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:region:account-id:api-id/",
"Condition": {
"IpAddress": {
"aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ]
}
}
}
]
}
Table A lists the resulting behavior when access to an API Gateway API is controlled by an IAM policy (or
a Lambda or Amazon Cognito user pools authorizer) and an API Gateway resource policy, both of which
are in the same AWS account.
IAM user policy (or Lambda API Gateway resource policy Resulting behavior
or Amazon Cognito user pools
authorizer)
Neither Allow nor Deny Neither Allow nor Deny Implicit Deny
Table B lists the resulting behavior when access to an API Gateway API is controlled by an IAM policy (or
a Lambda or Amazon Cognito user pools authorizer) and an API Gateway resource policy, which are in
different AWS accounts. If either is silent (neither allow nor deny), cross-account access is denied. This is
because cross-account access requires that both the resource policy and the IAM policy (or a Lambda or
Amazon Cognito user pools authorizer) explicitly grant access.
284
Amazon API Gateway Developer Guide
Access control
IAM user policy (or Lambda API Gateway resource policy Resulting behavior
or Amazon Cognito user pools
authorizer)
Neither Allow nor Deny Neither Allow nor Deny Implicit Deny
The following example policies use a simplified syntax to specify the API resource. This simplified
syntax is an abbreviated way that you can refer to an API resource, instead of specifying the full
Amazon Resource Name (ARN). API Gateway converts the abbreviated syntax to the full ARN
when you save the policy. For example, you can specify the resource execute-api:/stage-
name/GET/pets in a resource policy. API Gateway converts the resource to arn:aws:execute-
api:us-east-2:123456789012:aabbccddee/stage-name/GET/pets when you save the resource
policy. API Gateway builds the full ARN by using the current Region, your AWS account ID, and the ID of
the REST API that the resource policy is associated with. You can use execute-api:/* to represent all
stages, methods, and paths in the current API. For information about access policy language, see Access
policy language overview for Amazon API Gateway (p. 275).
Topics
• Example: Allow users in another AWS account to use an API (p. 285)
• Example: Deny API traffic based on source IP address or range (p. 286)
• Example: Deny API traffic based on source IP address or range when using a private API (p. 286)
• Example: Allow private API traffic based on source VPC or VPC endpoint (p. 287)
The following example resource policy grants API access in one AWS account to two users in a different
AWS account via Signature Version 4 (SigV4) protocols. Specifically, Alice and the root user for the AWS
account identified by account-id-2 are granted the execute-api:Invoke action to execute the GET
action on the pets resource (API) in your AWS account.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
285
Amazon API Gateway Developer Guide
Access control
"Principal": {
"AWS": [
"arn:aws:iam::account-id-2:user/Alice",
"account-id-2"
]
},
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/stage/GET/pets"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
]
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
],
"Condition" : {
"IpAddress": {
"aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ]
}
}
}
]
}
Example: Deny API traffic based on source IP address or range when using a private API
The following example resource policy denies (blocks) incoming traffic to a private API from two
specified source IP address blocks. When using private APIs, the VPC endpoint for execute-api re-
writes the original source IP address. The aws:VpcSourceIp condition filters the request against the
original requester IP address.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
]
286
Amazon API Gateway Developer Guide
Access control
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
],
"Condition" : {
"IpAddress": {
"aws:VpcSourceIp": ["192.0.2.0/24", "198.51.100.0/24"]
}
}
}
]
}
Example: Allow private API traffic based on source VPC or VPC endpoint
The following example resource policies allow incoming traffic to a private API only from a specified
virtual private cloud (VPC) or VPC endpoint.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
]
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
],
"Condition" : {
"StringNotEquals": {
"aws:SourceVpc": "vpc-1a2b3c4d"
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
]
287
Amazon API Gateway Developer Guide
Access control
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
],
"Condition" : {
"StringNotEquals": {
"aws:SourceVpce": "vpce-1a2b3c4d"
}
}
}
]
}
The resource policy can be attached to the API when the API is being created, or it can be attached
afterwards. For private APIs, note that until you attach the resource policy to the private API, all calls to
the API will fail.
Important
If you update the resource policy after the API is created, you'll need to deploy the API to
propagate the changes after you've attached the updated policy. Updating or saving the policy
alone won't change the runtime behavior of the API. For more information about deploying your
API, see Deploying a REST API in Amazon API Gateway (p. 490).
Access can be controlled by IAM condition elements, including conditions on AWS account, source VPC,
source VPC endpoint, or IP range. If the Principal in the policy is set to "*", other authorization types
can be used alongside the resource policy. If the Principal is set to "AWS", authorization will fail for all
resources not secured with AWS_IAM authorization, including unsecured resources.
The following sections describe how to create your own API Gateway resource policy and attach it to
your API. Attaching a policy applies the permissions in the policy to the methods in the API.
Important
If you use the API Gateway console to attach a resource policy to a deployed API, or if you
update an existing resource policy, you'll need to redeploy the API in the console for the changes
to take effect.
Topics
• Attaching API Gateway resource policies (console) (p. 288)
• Attaching API Gateway resource policies (AWS CLI) (p. 289)
288
Amazon API Gateway Developer Guide
Access control
If you don't use one of the Examples, enter your resource policy.
5. Choose Save.
If the API has been deployed previously in the API Gateway console, you'll need to redeploy it for the
resource policy to take effect.
To use the AWS CLI to create a new API and attach a resource policy to it, call the create-rest-api
command as follows:
To use the AWS CLI to attach a resource policy to an existing API, call the update-rest-api command
as follows:
AWS condition keys that can be used in API Gateway resource policies
The following table contains AWS condition keys that can be used in resource policies for APIs in API
Gateway for each authorization type.
For more information about AWS condition keys, see AWS Global Condition Context Keys.
289
Amazon API Gateway Developer Guide
Access control
290
Amazon API Gateway Developer Guide
Access control
• To create, deploy, and manage an API in API Gateway, you must grant the API developer permissions to
perform the required actions supported by the API management component of API Gateway.
• To call a deployed API or to refresh the API caching, you must grant the API caller permissions to
perform required IAM actions supported by the API execution component of API Gateway.
The access control for the two processes involves different permissions models, explained next.
For more information on how to use this permissions model, see the section called “API Gateway
identity-based policies” (p. 784).
In this IAM permissions policy statement, the IAM Resource element contains a list of deployed API
methods identified by given HTTP verbs and API Gateway resource paths. The IAM Action element
contains the required API Gateway API executing actions. These actions include execute-api:Invoke
or execute-api:InvalidateCache, where execute-api designates the underlying API execution
component of API Gateway.
For more information on how to use this permissions model, see Control access for invoking an
API (p. 292).
When an API is integrated with an AWS service (for example, AWS Lambda) in the back end, API Gateway
must also have permissions to access integrated AWS resources (for example, invoking a Lambda
function) on behalf of the API caller. To grant these permissions, create an IAM role of the AWS service
for API Gateway type. When you create this role in the IAM Management console, this resulting role
contains the following IAM trust policy that declares API Gateway as a trusted entity permitted to
assume the role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
If you create the IAM role by calling the create-role command of CLI or a corresponding SDK method, you
must supply the above trust policy as the input parameter of assume-role-policy-document. Do not
291
Amazon API Gateway Developer Guide
Access control
attempt to create such a policy directly in the IAM Management console or calling AWS CLI create-policy
command or a corresponding SDK method.
For API Gateway to call the integrated AWS service, you must also attach to this role appropriate IAM
permissions policies for calling integrated AWS services. For example, to call a Lambda function, you
must include the following IAM permissions policy in the IAM role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "*"
}
]
}
Note that Lambda supports resource-based access policy, which combines both trust and permissions
policies. When integrating an API with a Lambda function using the API Gateway console, you are not
asked to set this IAM role explicitly, because the console sets the resource-based permissions on the
Lambda function for you, with your consent.
Note
To enact access control to an AWS service, you can use either the caller-based permissions
model, where a permissions policy is directly attached to the caller's IAM user or group, or
the role-based permission model, where a permissions policy is attached to an IAM role that
API Gateway can assume. The permissions policies may differ in the two models. For example,
the caller-based policy blocks the access while the role-based policy allows it. You can take
advantage of this to require that an IAM user access an AWS service through an API Gateway API
only.
For private APIs, you should use a combination of an API Gateway resource policy and a VPC endpoint
policy. For more information, see the following topics:
• the section called “Use API Gateway resource policies” (p. 274)
• the section called “Use VPC endpoint policies for private APIs” (p. 297)
Control who can call an API Gateway API method with IAM policies
To control who can or cannot call a deployed API with IAM permissions, create an IAM policy document
with required permissions. A template for such a policy document is shown as follows.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Permission",
"Action": [
"execute-api:Execution-operation"
],
292
Amazon API Gateway Developer Guide
Access control
"Resource": [
"arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path"
]
}
]
}
Here, Permission is to be replaced by Allow or Deny depending on whether you want to grant or
revoke the included permissions. Execution-operation is to be replaced by the operations supported
by the API execution service. METHOD_HTTP_VERB stands for a HTTP verb supported by the specified
resources. Resource-path is the placeholder for the URL path of a deployed API Resource instance
supporting the said METHOD_HTTP_VERB. For more information, see Statement reference of IAM policies
for executing API in API Gateway (p. 294).
Note
For IAM policies to be effective, you must have enabled IAM authentication on API methods by
setting AWS_IAM for the methods' authorizationType property. Failing to do so will make
these API methods publicly accessible.
For example, to grant a user permission to view a list of pets exposed by a specified API, but to deny the
user permission to add a pet to the list, you could include the following statement in the IAM policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/pets"
]
},
{
"Effect": "Deny",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:account-id:api-id/*/POST/pets"
]
}
]
}
To grant a user permission to view a specific pet exposed by an API that is configured as GET /
pets/{petId}, you could include the following statement in the IAM policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/pets/a1b2"
]
}
]
293
Amazon API Gateway Developer Guide
Access control
The following information describes the Action and Resource format of IAM policy statements of access
permissions for executing an API.
execute-api:action
arn:aws:execute-api:region:account-id:api-id/stage-name/HTTP-VERB/resource-path-specifier
where:
• 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.
• stage-name is the name of the stage associated with the method.
• HTTP-VERB is the HTTP verb for the method. It can be one of the following: GET, POST, PUT, DELETE,
PATCH.
• resource-path-specifier is the path to the desired method.
• arn:aws:execute-api:*:*:* for any resource path in any stage, for any API in any AWS region.
• 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.
To learn more, see API Gateway Amazon Resource Name (ARN) reference (p. 739).
294
Amazon API Gateway Developer Guide
Access control
The following policy statement gives the user permission to call any POST method along the path of
mydemoresource, in the stage of test, for the API with the identifier of a123456789, assuming the
corresponding API has been deployed to the AWS region of us-east-1:
{
"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/*/*/petstorewalkthrough/pets"
]
}
]
}
To enable a user to call the API managing service or the API execution service, you must create an IAM
policy for an IAM user, which controls access to the API Gateway entities, and then attach the policy to
the IAM user. The following steps describe how to create your IAM policy.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. Choose Policies, and then choose Create Policy. If a Get Started button appears, choose it, and then
choose Create Policy.
3. Next to Create Your Own Policy, choose Select.
4. For Policy Name, type any value that is easy for you to refer to later. Optionally, type descriptive
text in Description.
5. For Policy Document, type a policy statement with the following format, and then choose Create
Policy:
295
Amazon API Gateway Developer Guide
Access control
"Version": "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"action-statement"
],
"Resource" : [
"resource-statement"
]
},
{
"Effect" : "Allow",
"Action" : [
"action-statement"
],
"Resource" : [
"resource-statement"
]
}
]
}
You have just created an IAM policy. It won't have any effect until you attach it to an IAM user, to an IAM
group containing the user, or to an IAM role assumed by the user.
1. For the chosen user, choose the Permissions tab, and then choose Attach Policy.
2. Under Grant permissions, choose Attach existing policies directly.
3. Choose the policy document just created from the displayed list and then choose Next: Review.
4. Under Permissions summary, choose Add permissions.
Alternatively, you can add the user to an IAM group, if the user is not already a member, and attach
the policy document to the group so that the attached policies are applicable to all group members.
It is helpful to manage and update policy configurations on a group of IAM users. In the following, we
highlight how to attach the policy to an IAM group, assuming that you have already created the group
and added the user to the group.
For API Gateway to call other AWS services on your behalf, create an IAM role of the Amazon API
Gateway type.
296
Amazon API Gateway Developer Guide
Access control
A VPC endpoint policy is an IAM resource policy that you can attach to an interface VPC endpoint to
control access to the endpoint. For more information, see Controlling Access to Services with VPC
Endpoints. You can use an endpoint policy to restrict the traffic going from your internal network to
access your private APIs. You can choose to allow or disallow access to specific private APIs that can be
accessed through the VPC endpoint.
VPC endpoint policies can be used together with API Gateway resource policies. The resource policy is
used to specify which principals can access the API. The endpoint policy specifies which private APIs can
be called via the VPC endpoint. For more information about resource policies, see the section called “Use
API Gateway resource policies” (p. 274).
To attach the policy to the VPC endpoint, you'll need to use the VPC console. For more information, see
Controlling Access to Services with VPC Endpoints.
{
"Statement": [
{
297
Amazon API Gateway Developer Guide
Access control
"Principal": "*",
"Action": [
"execute-api:Invoke"
],
"Effect": "Allow",
"Resource": [
"arn:aws:execute-api:us-east-1:123412341234:a1b2c3d4e5/*",
"arn:aws:execute-api:us-east-1:123412341234:aaaaa11111/*"
]
}
]
}
{
"Statement": [
{
"Principal": "*",
"Action": [
"execute-api:Invoke"
],
"Effect": "Allow",
"Resource": [
"arn:aws:execute-api:us-east-1:123412341234:a1b2c3d4e5/stageName/GET/*"
]
}
]
}
Example 3: VPC endpoint policy granting a specific user access to a specific API
The following example policy grants a specific user access to a specific API via the VPC endpoint that the
policy is attached to.
{
"Statement": [
{
"Principal": {
"AWS": [
"arn:aws:iam::123412341234:user/MyUser"
]
},
"Action": [
"execute-api:Invoke"
],
"Effect": "Allow",
"Resource": [
"arn:aws:execute-api:us-east-1:123412341234:a1b2c3d4e5/*"
]
}
]
}
298
Amazon API Gateway Developer Guide
Access control
For more information, see the section called “Attribute-based access control” (p. 808).
A Lambda authorizer is useful if you want to implement a custom authorization scheme that uses
a bearer token authentication strategy such as OAuth or SAML, or that uses request parameters to
determine the caller's identity.
When a client makes a request to one of your API's methods, API Gateway calls your Lambda authorizer,
which takes the caller's identity as input and returns an IAM policy as output.
• A token-based Lambda authorizer (also called a TOKEN authorizer) receives the caller's identity in a
bearer token, such as a JSON Web Token (JWT) or an OAuth token. For an example application, see
Open Banking Brazil - Authorization Samples on GitHub.
• A request parameter-based Lambda authorizer (also called a REQUEST authorizer) receives the caller's
identity in a combination of headers, query string parameters, stageVariables (p. 420), and
$context (p. 410) variables.
It is possible to use an AWS Lambda function from an AWS account that is different from the one in
which you created your API. For more information, see the section called “Configure a cross-account
Lambda authorizer” (p. 313).
Topics
• Lambda authorizer Auth workflow (p. 299)
• Steps to create an API Gateway Lambda authorizer (p. 300)
• Create an API Gateway Lambda authorizer function in the Lambda console (p. 301)
• Configure a Lambda authorizer using the API Gateway console (p. 306)
• Input to an Amazon API Gateway Lambda authorizer (p. 308)
• Output from an Amazon API Gateway Lambda authorizer (p. 309)
• Call an API with API Gateway Lambda authorizers (p. 311)
• Configure a cross-account Lambda authorizer (p. 313)
299
Amazon API Gateway Developer Guide
Access control
1. The client calls a method on an API Gateway API method, passing a bearer token or request
parameters.
2. API Gateway checks whether a Lambda authorizer is configured for the method. If it is, API Gateway
calls the Lambda function.
3. The Lambda function authenticates the caller by means such as the following:
• If access is denied, API Gateway returns a suitable HTTP status code, such as 403
ACCESS_DENIED.
• If access is allowed, API Gateway executes the method. If caching is enabled in the authorizer
settings, API Gateway also caches the policy so that the Lambda authorizer function doesn't need
to be invoked again.
1. Create the Lambda authorizer function in the Lambda console as described in the section called
“Create a Lambda authorizer function in the Lambda console” (p. 301). You can use one of the
blueprint examples as a starting point and customize the input (p. 308) and output (p. 309) as
desired.
300
Amazon API Gateway Developer Guide
Access control
2. Configure the Lambda function as an API Gateway authorizer and configure an API method
to require it, as described in the section called “Configure a Lambda authorizer using the
console” (p. 306). Alternatively, if you need a cross-account Lambda authorizer, see the section
called “Configure a cross-account Lambda authorizer” (p. 313).
Note
You can also configure an authorizer by using the AWS CLI or an AWS SDK.
3. Test your authorizer by using Postman as described in the section called “Call an API with Lambda
authorizers” (p. 311).
For the example Lambda authorizer functions in this section, which don't call other services, you can use
the built-in AWSLambdaBasicExecutionRole. When creating the Lambda function for your own API
Gateway Lambda authorizer, you'll need to assign an IAM execution role to the Lambda function if it calls
other AWS services. To create the role, follow the instructions in AWS Lambda Execution Role.
To create a token-based Lambda authorizer function, enter the following Node.js code in the Lambda
console and test it in the API Gateway console as follows.
301
Amazon API Gateway Developer Guide
Access control
authResponse.principalId = principalId;
if (effect && resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context = {
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
};
return authResponse;
}
6. Choose Deploy.
7. In the API Gateway console, create a simple API (p. 46) if you don't already have one.
8. Choose your API from the API list.
9. Choose Authorizers.
10. Choose Create New Authorizer.
11. Enter a name for the authorizer.
12. For Type, choose Lambda.
13. For Lambda Function, choose the region where you created your Lambda authorizer function and
choose the function name from the dropdown list.
14. Leave Lambda Invoke Role blank.
15. For Lambda Event Payload, choose Token.
16. For Token Source, enter authorizationToken.
17. Choose Create, and then choose Grant & Create.
18. Choose Test.
19. For the authorizationToken value, enter allow.
20. Choose Test.
In this example, when the API receives a method request, API Gateway passes the source token to this
Lambda authorizer function in the event.authorizationToken attribute. The Lambda authorizer
function reads the token and acts as follows:
302
Amazon API Gateway Developer Guide
Access control
• If the token value is 'allow', the authorizer function returns a 200 OK HTTP response and an IAM
policy that looks like the following, and the method request succeeds:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-
stage/GET/"
}
]
}
• If the token value is 'deny', the authorizer function returns a 403 Forbidden HTTP response and a
Deny IAM policy that looks like the following, and the method request fails:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-
stage/GET/"
}
]
}
• If the token value is 'unauthorized' or an empty string, the authorizer function returns a 401
Unauthorized HTTP response, and the method call fails.
• If the token is anything else, the client receives a 500 Invalid token response, and the method call
fails.
Note
In production code, you may need to authenticate the user before granting authorization. If so,
you can add authentication logic in the Lambda function as well by calling an authentication
provider as directed in the documentation for that provider.
In addition to returning an IAM policy, the Lambda authorizer function must also return the caller's
principal identifier. It can also optionally return a context object containing additional information
that can be passed into the integration backend. For more information, see Output from an Amazon API
Gateway Lambda authorizer (p. 309).
To create a request-based Lambda authorizer function, enter the following Node.js code in the Lambda
console and test it in the API Gateway console as follows.
303
Amazon API Gateway Developer Guide
Access control
// Perform authorization to return the Allow policy for correct parameters and
// the 'Unauthorized' error, otherwise.
var authResponse = {};
var condition = {};
condition.IpAddress = {};
304
Amazon API Gateway Developer Guide
Access control
6. Choose Deploy.
7. In the API Gateway console, create a simple API (p. 46) if you don't already have one.
8. Choose your API from the API list.
9. Choose Authorizers.
10. Choose Create New Authorizer.
11. Enter a name for the authorizer.
12. For Type, choose Lambda.
13. For Lambda Function, choose the region where you created your Lambda authorizer function and
choose the function name from the dropdown list.
14. Leave Lambda Invoke Role blank.
15. For Lambda Event Payload, choose Request.
16. Under Identity Sources, add a Header named headerauth1, a Query String named
QueryString1, and a Stage Variable named StageVar1.
17. Choose Create, and then choose Grant & Create.
18. Choose Test.
19. For headerauth1, enter headerValue1. For QueryString1, enter queryValue1. For StageVar1,
enter stageValue1.
20. Choose Test.
In this example, the Lambda authorizer function checks the input parameters and acts as follows:
• If all the required parameter values match the expected values, the authorizer function returns a 200
OK HTTP response and an IAM policy that looks like the following, and the method request succeeds:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-
stage/GET/"
}
]
}
• Otherwise, the authorizer function returns a 401 Unauthorized HTTP response, and the method call
fails.
Note
In production code, you may need to authenticate the user before granting authorization. If so,
you can add authentication logic in the Lambda function as well by calling an authentication
provider as directed in the documentation for that provider.
In addition to returning an IAM policy, the Lambda authorizer function must also return the caller's
principal identifier. It can also optionally return a context object containing additional information
305
Amazon API Gateway Developer Guide
Access control
that can be passed into the integration backend. For more information, see Output from an Amazon API
Gateway Lambda authorizer (p. 309).
If you choose to let the API Gateway console set the resource-based policy, the Add Permission to
Lambda Function dialog is displayed. Choose OK. After the Lambda authorization is created, you
can test it with appropriate authorization token values to verify that it works as expected.
8. For Lambda Event Payload, choose either Token for a TOKEN authorizer or Request for a REQUEST
authorizer. (This is the same as setting the type property to TOKEN or REQUEST.)
9. Depending on the choice of the previous step, do one of the following:
• Type the name of a header in Token Source. The API client must include a header of this
name to send the authorization token to the Lambda authorizer.
• Optionally, provide a RegEx statement in Token Validation input field. API Gateway
performs initial validation of the input token against this expression and invokes the
authorizer upon successful validation. This helps reduce chances of being charged for invalid
tokens.
• For Authorization Caching, select or clear the Enabled option, depending on whether you
want to cache the authorization policy generated by the authorizer or not. When policy
caching is enabled, you can choose to modify the TTL value. Setting TTL to zero disables
policy caching. When policy caching is enabled, the header name specified in Token Source
becomes the cache key.
Note
The default TTL value is 300 seconds. The maximum value is 3600 seconds; this limit
cannot be increased.
b. For the Request option, do the following:
• For Identity Sources, type a request parameter name of a chosen parameter type. Supported
parameter types are Header, Query String, Stage Variable, and Context. To add more
identity sources, choose Add Identity Source.
API Gateway uses the specified identity sources as the request authorizer caching key. When
caching is enabled, API Gateway calls the authorizer's Lambda function only after successfully
verifying that all the specified identity sources are present at runtime. If a specified identify
306
Amazon API Gateway Developer Guide
Access control
source is missing, null, or empty, API Gateway returns a 401 Unauthorized response
without calling the authorizer Lambda function.
When multiple identity sources are defined, they all used to derive the authorizer's cache
key. Changing any of the cache key parts causes the authorizer to discard the cached policy
document and generate a new one.
• For Authorization Caching, select or deselect the Enabled option, depending on whether
you want to cache the authorization policy generated by the authorizer or not. When policy
caching is enabled, you can choose to modify the TTL value from the default (300). Setting
TTL=0 disables policy caching.
Note
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.
10. Choose Create to create the new Lambda authorizer for the chosen API.
11. After the authorizer is created for the API, you can optionally test invoking the authorizer before it is
configured on a method.
For the TOKEN authorizer, type a valid token in the Identity token input text field and the choose
Test. The token will be passed to the Lambda function as the header you specified in the Identity
token source setting of the authorizer.
For the REQUEST authorizer, type the valid request parameters corresponding to the specified
identity sources and then choose Test.
In addition to using the API Gateway console, you can use AWS CLI or an AWS SDK for API Gateway
to test invoking an authorizer. To do so using the AWS CLI, see test-invoke-authorizer.
Note
Test-invoke for method executions test-invoke for authorizers are independent processes.
To test invoking a method using the API Gateway console, see Use the console to test a
REST API method (p. 459). To test invoking a method using the AWS CLI, see test-invoke-
method.
To test invoking a method and a configured authorizer, deploy the API, and then use cURL
or Postman to call the method, providing the required token or request parameters.
The next procedure shows how to configure an API method to use the Lambda authorizer.
1. Go back to the API. Create a new method or choose an existing method. If necessary, create a new
resource.
2. In Method Execution, choose the Method Request link.
3. Under Settings, expand the Authorization drop-down list to select the Lambda authorizer you
just created (for example, myTestApiAuthorizer), and then choose the check mark icon to save the
choice.
4. Optionally, while still on the Method Request page, choose Add header if you also want to pass the
authorization token to the backend. In Name, type a header name that matches the Token Source
name you specified when you created the Lambda authorizer for the API. Then, choose the check
mark icon to save the settings. This step does not apply to REQUEST authorizers.
307
Amazon API Gateway Developer Guide
Access control
5. Choose Deploy API to deploy the API to a stage. Note the Invoke URL value. You need it when
calling the API. For a REQUEST authorizer using stage variables, you must also define the required
stage variables and specify their values while in Stage Editor.
{
"type":"TOKEN",
"authorizationToken":"{caller-supplied-token}",
"methodArn":"arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/
[{resource}/[{child-resources}]]"
}
In this example, the type property specifies the authorizer type, which is a TOKEN authorizer. The
{caller-supplied-token} originates from the 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 Lambda authorizer configuration.
For the example TOKEN authorizer Lambda function shown in the preceding 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/"
}
For a Lambda authorizer of the REQUEST type, API Gateway passes request parameters to the authorizer
Lambda function as part of the event object. The request parameters include headers, path parameters,
query string parameters, stage variables, and some of request context variables. The API caller can
set the path parameters, headers, and query string parameters. The API developer must set the stage
variables during the API deployment and API Gateway provides the request context at run time.
Note
Path parameters can be passed as request parameters to the Lambda authorizer function, but
they cannot be used as identity sources.
The following example shows an input to a REQUEST authorizer for an API method (GET /request)
with a proxy integration:
{
"type": "REQUEST",
"methodArn": "arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request",
"resource": "/request",
"path": "/request",
"httpMethod": "GET",
"headers": {
"X-AMZ-Date": "20170718T062915Z",
308
Amazon API Gateway Developer Guide
Access control
"Accept": "*/*",
"HeaderAuth1": "headerValue1",
"CloudFront-Viewer-Country": "US",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Is-Mobile-Viewer": "false",
"User-Agent": "..."
},
"queryStringParameters": {
"QueryString1": "queryValue1"
},
"pathParameters": {},
"stageVariables": {
"StageVar1": "stageValue1"
},
"requestContext": {
"path": "/request",
"accountId": "123456789012",
"resourceId": "05c7jb",
"stage": "test",
"requestId": "...",
"identity": {
"apiKey": "...",
"sourceIp": "...",
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"resourcePath": "/request",
"httpMethod": "GET",
"apiId": "abcdef123"
}
}
The requestContext is a map of key-value pairs and corresponds to the $context (p. 410) variable.
Its outcome is API-dependent. API Gateway may add new keys to the map. For more information about
Lambda function input in Lambda proxy integration, see Input format of a Lambda function for proxy
integration (p. 339).
{
"principalId": "yyyyyyyy", // The principal user identification associated with the token
sent by the client.
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
309
Amazon API Gateway Developer Guide
Access control
"Action": "execute-api:Invoke",
"Effect": "Allow|Deny",
"Resource": "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/
[{resource}/[{child-resources}]]"
}
]
},
"context": {
"stringKey": "value",
"numberKey": "1",
"booleanKey": "true"
},
"usageIdentifierKey": "{api-key}"
}
Here, a policy statement specifies 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). For information about setting valid policies for calling an API, see Statement
reference of IAM policies for executing API in API Gateway (p. 294).
In addition, the Resource ARN, as shown in the policy statement output by the authorizer, is currently
limited to 512 characters long. For this reason, you must not use URI with a JWT token of a significant
length in a request URI. You can safely pass the JWT token in a request header, instead.
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 backend. For more information, see $context Variables for data models, authorizers, mapping
templates, and CloudWatch access logging (p. 410).
You can access the stringKey, numberKey, or booleanKey value (for example, "value", "1", or
"true") of the context map in a mapping template by calling $context.authorizer.stringKey,
$context.authorizer.numberKey, or $context.authorizer.booleanKey, respectively. The
returned values are all stringified. Notice that you cannot set a JSON object or array as a valid value of
any key in the context map.
You can use the context map to return cached credentials from the authorizer to the backend, using an
integration request mapping template. This enables the backend to provide an improved user experience
by using the cached credentials to reduce the need to access the secret keys and open the authorization
tokens for every request.
For the Lambda proxy integration, API Gateway passes the context object from a Lambda authorizer
directly to the backend Lambda function as part of the input event. You can retrieve the context key-
value pairs in the Lambda function by calling $event.requestContext.authorizer.key.
{api-key} stands for an API key in the API stage's usage plan. For more information, see the section
called “Usage plans” (p. 549).
The following shows example output from the example Lambda authorizer. The example output contains
a policy statement to block (Deny) calls to the GET method for the dev stage of an API (ymy8tbxw7b) of
an AWS account (123456789012).
{
"principalId": "user",
310
Amazon API Gateway Developer Guide
Access control
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/dev/GET/"
}
]
}
}
In the following, we show how to use Postman to call or test an API with a Lambda TOKEN authorizer.
The method can be applied to calling an API with a Lambda REQUEST authorizer, if you specify the
required path, header, or query string parameters explicitly.
1. Open Postman, choose the GET method, and paste the API's Invoke URL into the adjacent URL field.
Add the Lambda authorization token header and set the value to allow. Choose Send.
311
Amazon API Gateway Developer Guide
Access control
The response shows that the API Gateway Lambda 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 Lambda authorization token header value to deny. Choose Send.
The response shows that the API Gateway Lambda authorizer returns a 403 Forbidden response
without authorizing the call to access the HTTP endpoint.
3. In Postman, change the Lambda authorization token header value to unauthorized and choose
Send.
The response shows that API Gateway returns a 401 Unauthorized response without authorizing the
call to access the HTTP endpoint.
312
Amazon API Gateway Developer Guide
Access control
4. Now, change the Lambda 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.
In this section, we show how to configure a cross-account Lambda authorizer function using the Amazon
API Gateway console.
These instructions assume that you already have an API Gateway API in one AWS account and a Lambda
authorizer function in another account.
Log in to the Amazon API Gateway console in your first account (the one that has your API in it) and do
the following:
313
Amazon API Gateway Developer Guide
Access control
choose to 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 Create an assumable IAM role (p. 95).
If you choose to let the API Gateway console set the resource-based policy, the Add Permission to
Lambda Function dialog is displayed. Choose OK. After the Lambda authorization is created, you
can test it with appropriate authorization token values to verify that it works as expected.
7. For Lambda Event Payload, choose either Token for a TOKEN authorizer or Request for a REQUEST
authorizer.
8. Depending on the choice you made in the previous step, do one of the following:
i. Type the name of a header in Token Source. The API client must include a header of this
name to send the authorization token to the Lambda authorizer.
ii. Optionally, provide a RegEx statement in Token Validation input field. API Gateway
performs initial validation of the input token against this expression and invokes the
authorizer upon successful validation. This helps reduce chances of being charged for
invalid tokens.
iii. For Authorization Caching, select or clear the Enabled option, depending on whether you
want to cache the authorization policy generated by the authorizer or not. When policy
caching is enabled, you can choose to modify the TTL value from the default (300). Setting
TTL=0 disables policy caching. When policy caching is enabled, the header name specified
in Token Source becomes the cache key.
b. For the Request option, do the following:
i. For Identity Sources, type a request parameter name of a chosen parameter type.
Supported parameter types are Header, Query String, Stage Variable, and Context.
To add more identity sources, choose Add Identity Source.
API Gateway uses the specified identity sources as the request authorizer caching key.
When caching is enabled, API Gateway calls the authorizer's Lambda function only
after successfully verifying that all the specified identity sources are present at runtime.
If a specified identify source is missing, null, or empty, API Gateway returns a 401
Unauthorized response without calling the authorizer Lambda function.
When multiple identity sources are defined, they are all used to derive the authorizer's
cache key. Changing any of the cache key parts causes the authorizer to discard the cached
policy document and generate a new one.
ii. For Authorization Caching, leave the Enabled option selected. Leave the TTL value set to
the default (300).
9. Choose Create to create the new Lambda authorizer for the chosen API.
10. You'll see a popup that says Add Permission to Lambda Function: You have selected a Lambda
function from another account. Please ensure that you have the appropriate Function Policy
on this function. You can do this by running the following AWS CLI command from account
123456789012:, followed by an aws lambda add-permission command string.
Copy the command and save it for later. You run the command after you create the authorizer.
11. Choose Create Anyway.
12. Paste the aws lambda add-permission command string that you copied in a previous step into
an AWS CLI window that is configured for your second account. Replace AUTHORIZER_ID with your
authorizer's ID. This will grant your first account access to your second account's Lambda authorizer
function.
314
Amazon API Gateway Developer Guide
Access control
To use an Amazon Cognito user pool with your API, you must first create an authorizer of the
COGNITO_USER_POOLS type and then configure an API method to use that authorizer. After the API is
deployed, the client must first sign the user in to the user pool, obtain an identity or access token for
the user, and then call the API method with one of the tokens, which are typically set to the request's
Authorization header. The API call succeeds only if the required token is supplied and the supplied
token is valid, otherwise, the client isn't authorized to make the call because the client did not have
credentials that could be authorized.
The identity token is used to authorize API calls based on identity claims of the signed-in user. The access
token is used to authorize API calls based on the custom scopes of specified access-protected resources.
For more information, see Using Tokens with User Pools and Resource Server and Custom Scopes.
To create and configure an Amazon Cognito user pool for your API, you perform the following tasks:
• Use the Amazon Cognito console, CLI/SDK, or API to create a user pool—or use one that's owned by
another AWS account.
• Use the API Gateway console, CLI/SDK, or API to create an API Gateway authorizer with the chosen
user pool.
• Use the API Gateway console, CLI/SDK, or API to enable the authorizer on selected API methods.
To call any API methods with a user pool enabled, your API clients perform the following tasks:
• Use the Amazon Cognito CLI/SDK or API to sign a user in to the chosen user pool, and obtain an
identity token or access token.
• Use a client-specific framework to call the deployed API Gateway API and supply the appropriate token
in the Authorization header.
As the API developer, you must provide your client developers with the user pool ID, a client ID, and
possibly the associated client secrets that are defined as part of the user pool.
Note
To let a user sign in using Amazon Cognito credentials and also obtain temporary credentials to
use with the permissions of an IAM role, use Amazon Cognito Federated Identities. For each API
resource endpoint HTTP method, set the authorization type, category Method Execution, to
AWS_IAM.
In this section, we describe how to create a user pool, how to integrate an API Gateway API with the user
pool, and how to invoke an API that's integrated with the user pool.
Topics
• Obtain permissions to create Amazon Cognito user pool authorizers for a REST API (p. 316)
• Create an Amazon Cognito user pool for a REST API (p. 317)
• Integrate a REST API with an Amazon Cognito user pool (p. 318)
• Call a REST API integrated with an Amazon Cognito user pool (p. 322)
• Configure cross-account Amazon Cognito authorizer for a REST API using the API Gateway
console (p. 322)
315
Amazon API Gateway Developer Guide
Access control
Obtain permissions to create Amazon Cognito user pool authorizers for a REST
API
To create an authorizer with an Amazon Cognito user pool, you must have Allow permissions to create
or update an authorizer with the chosen Amazon Cognito user pool. The following IAM policy document
shows an example of such permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"apigateway:POST"
],
"Resource": "arn:aws:apigateway:*::/restapis/*/authorizers",
"Condition": {
"ArnLike": {
"apigateway:CognitoUserPoolProviderArn": [
"arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-
east-1_aD06NQmjO",
"arn:aws:cognito-idp:us-east-1:234567890123:userpool/us-
east-1_xJ1MQtPEN"
]
}
}
},
{
"Effect": "Allow",
"Action": [
"apigateway:PATCH"
],
"Resource": "arn:aws:apigateway:*::/restapis/*/authorizers/*",
"Condition": {
"ArnLike": {
"apigateway:CognitoUserPoolProviderArn": [
"arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-
east-1_aD06NQmjO",
"arn:aws:cognito-idp:us-east-1:234567890123:userpool/us-
east-1_xJ1MQtPEN"
]
}
}
}
]
}
Make sure that the policy is attached to your IAM user, an IAM group that you belong to, or an IAM role
that you're assigned to.
In the preceding policy document, the apigateway:POST action is for creating a new authorizer, and
the apigateway:PATCH action is for updating an existing authorizer. You can restrict the policy to a
specific region or a particular API by overriding the first two wildcard (*) characters of the Resource
values, respectively.
The Condition clauses that are used here are to restrict the Allowed permissions to the specified user
pools. When a Condition clause is present, access to any user pools that don't match the conditions is
denied. When a permission doesn't have a Condition clause, access to any user pool is allowed.
316
Amazon API Gateway Developer Guide
Access control
• You can set an ArnLike or ArnEquals conditional expression to permit creating or updating
COGNITO_USER_POOLS authorizers with the specified user pools only.
• You can set an ArnNotLike or ArnNotEquals conditional expression to permit creating or updating
COGNITO_USER_POOLS authorizers with any user pool that isn't specified in the expression.
• You can omit the Condition clause to permit creating or updating COGNITO_USER_POOLS
authorizers with any user pool, of any AWS account, and in any region.
For more information on the Amazon Resource Name (ARN) conditional expressions,
see Amazon Resource Name Condition Operators. As shown in the example,
apigateway:CognitoUserPoolProviderArn is a list of ARNs of the COGNITO_USER_POOLS user
pools that can or can't be used with an API Gateway authorizer of the COGNITO_USER_POOLS type.
Note the user pool ID, client ID, and any client secret. The client must provide them to Amazon Cognito
for the user to register with the user pool, to sign in to the user pool, and to obtain an identity or access
token to be included in requests to call API methods that are configured with the user pool. Also, you
must specify the user pool name when you configure the user pool as an authorizer in API Gateway, as
described next.
If you're using access tokens to authorize API method calls, be sure to configure the app integration
with the user pool to set up the custom scopes that you want on a given resource server. For more
information about using tokens with Amazon Cognito user pools, see Using Tokens with User Pools. For
more information about resource servers, see Defining Resource Servers for Your User Pool.
Note the configured resource server identifiers and custom scope names. You need them to construct the
access scope full names for OAuth Scopes, which is used by the COGNITO_USER_POOLS authorizer.
317
Amazon API Gateway Developer Guide
Access control
318
Amazon API Gateway Developer Guide
Access control
g. To finish integrating the user pool with the API, choose Create.
5. After creating the COGNITO_USER_POOLS authorizer, you can optionally test invoke it by supplying
an identity token that's provisioned from the user pool. You can obtain this identity token by calling
the Amazon Cognito Identity SDK to perform user sign-in. Make sure to use the returned identity
token, not the access token.
The preceding procedure creates a COGNITO_USER_POOLS authorizer that uses the newly created
Amazon Cognito user pool. Depending on how you enable the authorizer on an API method, you can use
either an identity token or an access token that's provisioned from the integrated user pool. The next
procedure walks you through the steps to configure the authorizer on an API method.
{
"context" : {
"sub" : "$context.authorizer.claims.sub",
"email" : "$context.authorizer.claims.email"
}
}
If you declared a custom claim field when you configured a 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']"
}
}
319
Amazon API Gateway Developer Guide
Access control
At runtime, the method call succeeds if any scope that's specified on the method in this step
matches a scope that's claimed in the incoming token. Otherwise, the call fails with a 401
Unauthorized response.
c. To save the setting, choose the check mark icon.
8. Repeat these steps for other methods that you choose.
With the COGNITO_USER_POOLS authorizer, if the OAuth Scopes option isn't specified, API Gateway
treats the supplied token as an identity token and verifies the claimed identity against the one from the
user pool. Otherwise, API Gateway treats the supplied token as an access token and verifies the access
scopes that are claimed in the token against the authorization scopes declared on the method.
Instead of using the API Gateway console, you can also enable an Amazon Cognito user pool on a
method by specifying an OpenAPI definition file and importing the API definition into API Gateway.
OpenAPI 3.0
"securitySchemes": {
"MyUserPool": {
"type": "apiKey",
"name": "Authorization",
"in": "header",
"x-amazon-apigateway-authtype": "cognito_user_pools",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools",
"providerARNs": [
"arn:aws:cognito-idp:{region}:{account_id}:userpool/{user_pool_id}"
]
}
}
OpenAPI 2.0
"securityDefinitions": {
"MyUserPool": {
"type": "apiKey",
"name": "Authorization",
"in": "header",
"x-amazon-apigateway-authtype": "cognito_user_pools",
"x-amazon-apigateway-authorizer": {
"type": "cognito_user_pools",
"providerARNs": [
"arn:aws:cognito-idp:{region}:{account_id}:userpool/{user_pool_id}"
]
}
320
Amazon API Gateway Developer Guide
Access control
3. To use the identity token for method authorization, add { "MyUserPool": [] } to the security
definition of the method, as shown in the following GET method on the root resource.
"paths": {
"/": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"text/html"
],
"responses": {
"200": {
"description": "200 response",
"headers": {
"Content-Type": {
"type": "string"
}
}
}
},
"security": [
{
"MyUserPool": []
}
],
"x-amazon-apigateway-integration": {
"type": "mock",
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type": "'text/html'"
},
}
},
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"passthroughBehavior": "when_no_match"
}
},
...
}
4. To use the access token for method authorization, change the above security definition to
{ "MyUserPool": [resource-server/scope, ...] }:
"paths": {
"/": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"text/html"
],
"responses": {
"200": {
"description": "200 response",
"headers": {
321
Amazon API Gateway Developer Guide
Access control
"Content-Type": {
"type": "string"
}
}
}
},
"security": [
{
"MyUserPool": ["com.hamuta.movies/drama.view", "http://my.resource.com/
file.read"]
}
],
"x-amazon-apigateway-integration": {
"type": "mock",
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type": "'text/html'"
},
}
},
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"passthroughBehavior": "when_no_match"
}
},
...
}
5. If needed, you can set other API configuration settings by using the appropriate OpenAPI
definitions or extensions. For more information, see Working with API Gateway extensions to
OpenAPI (p. 744).
You can use AWS Amplify to perform these tasks. See Integrating Amazon Cognito With Web and Mobile
Apps for more information.
Configure cross-account Amazon Cognito authorizer for a REST API using the
API Gateway console
You can now also use a Amazon Cognito user pool from a different AWS account as your API authorizer.
Each account can be in any region where Amazon API Gateway is available. The Amazon Cognito user
pool can use bearer token authentication strategies such as OAuth or SAML. This makes it easy to
322
Amazon API Gateway Developer Guide
Integrations
centrally manage and share a central Amazon Cognito user pool authorizer across multiple API Gateway
APIs.
In this section, we show how to configure a cross-account Amazon Cognito user pool using the Amazon
API Gateway console.
These instructions assume that you already have an API Gateway API in one AWS account and a Amazon
Cognito user pool in another account.
Configure cross-account Amazon Cognito authorizer using the API Gateway console
Log in to the Amazon API Gateway console in your first account (the one that has your API in it) and do
the following:
As with the API method, the API integration has an integration request and an integration response.
An integration request encapsulates an HTTP request received by the backend. It might or might not
differ from the method request submitted by the client. An integration response is an HTTP response
encapsulating the output returned by the backend.
Setting up an integration request involves the following: configuring how to pass client-submitted
method requests to the backend; configuring how to transform the request data, if necessary, to the
integration request data; and specifying which Lambda function to call, specifying which HTTP server to
forward the incoming request to, or specifying the AWS service action to invoke.
Setting up an integration response (applicable to non-proxy integrations only) involves the following:
configuring how to pass the backend-returned result to a method response of a given status code,
configuring how to transform specified integration response parameters to preconfigured method
response parameters, and configuring how to map the integration response body to the method
response body according to the specified body-mapping templates.
323
Amazon API Gateway Developer Guide
Integrations
To set up an integration request, you create an Integration resource and use it to configure the
integration endpoint URL. You then set the IAM permissions to access the backend, and specify mappings
to transform the incoming request data before passing it to the backend. To set up an integration
response for non-proxy integration, you create an IntegrationResponse resource and use it to set its
target method response. You then configure how to map backend output to the method response.
Topics
• Set up an integration request in API Gateway (p. 324)
• Set up an integration response in API Gateway (p. 330)
• Set up Lambda integrations in API Gateway (p. 331)
• Set up HTTP integrations in API Gateway (p. 349)
• Set up API Gateway private integrations (p. 354)
• Set up mock integrations in API Gateway (p. 361)
1. Choose an integration type that determines how method request data is passed to the backend.
2. For non-mock integrations, specify an HTTP method and the URI of the targeted integration endpoint,
except for the MOCK integration.
3. For integrations with Lambda functions and other AWS service actions, set an IAM role with required
permissions for API Gateway to call the backend on your behalf.
4. For non-proxy integrations, set necessary parameter mappings to map predefined method request
parameters to appropriate integration request parameters.
5. For non-proxy integrations, set necessary body mappings to map the incoming method request body
of a given content type according to the specified mapping template.
6. For non-proxy integrations, specify the condition under which the incoming method request data is
passed through to the backend as-is.
7. Optionally, specify how to handle type conversion for a binary payload.
8. Optionally, declare a cache namespace name and cache key parameters to enable API caching.
Performing these tasks involves creating an Integration resource of API Gateway and setting appropriate
property values. You can do so using the API Gateway console, AWS CLI commands, an AWS SDK, or the
API Gateway REST API.
Topics
• Basic tasks of an API integration request (p. 324)
• Choose an API Gateway API integration type (p. 326)
• Set up a proxy integration with a proxy resource (p. 327)
• Set up an API integration request using the API Gateway console (p. 328)
324
Amazon API Gateway Developer Guide
Integrations
For example, when a Lambda function returns a file that is fetched from Amazon S3, you can expose this
operation intuitively as a GET method request to the client even though the corresponding integration
request requires that a POST request be used to invoke the Lambda function. For an HTTP endpoint, it is
likely that the method request and the corresponding integration request both use the same HTTP verb.
However, this is not required. You can integrate the following method request:
GET /{var}?query=value
Host: api.domain.net
POST /
Host: service.domain.com
Content-Type: application/json
Content-Length: ...
{
path: "{var}'s value",
type: "value"
}
As an API developer, you can use whatever HTTP verb and URI for a method request suit your
requirements. But you must follow the requirements of the integration endpoint. When the method
request data differs from the integration request data, you can reconcile the difference by providing
mappings from the method request data to the integration request data.
In the preceding examples, the mapping translates the path variable ({var}) and the query parameter
(query) values of the GET method request to the values of the integration request's payload properties
of path and type. Other mappable request data includes request headers and body. These are described
in Set up request and response data mappings using the API Gateway console (p. 387).
When setting up the HTTP or HTTP proxy integration request, you assign the backend HTTP endpoint
URL as the integration request URI value. For example, in the PetStore API, the method request to get a
page of pets has the following integration request URI:
http://petstore-demo-endpoint.execute-api.com/petstore/pets
When setting up the Lambda or Lambda proxy integration, you assign the Amazon Resource Name
(ARN) for invoking the Lambda function as the integration request URI value. This ARN has the following
format:
arn:aws:apigateway:api-region:lambda:path//2015-03-31/functions/arn:aws:lambda:lambda-
region:account-id:function:lambda-function-name/invocations
When setting up the integration request with another AWS service action, the integration request URI is
also an ARN, similar to the integration with the Lambda Invoke action. For example, for the integration
with the GetBucket action of Amazon S3, the integration request URI is an ARN of the following format:
arn:aws:apigateway:api-region:s3:path/{bucket}
325
Amazon API Gateway Developer Guide
Integrations
The integration request URI is of the path convention to specify the action, where {bucket} is the
placeholder of a bucket name. Alternatively, an AWS service action can be referenced by its name. Using
the action name, the integration request URI for the GetBucket action of Amazon S3 becomes the
following:
arn:aws:apigateway:api-region:s3:action/GetBucket
With the action-based integration request URI, the bucket name ({bucket}) must be specified in the
integration request body ({ Bucket: "{bucket}" }), following the input format of GetBucket
action.
For AWS integrations, you must also configure credentials to allow API Gateway to call the integrated
actions. You can create a new or choose an existing IAM role for API Gateway to call the action and then
specify the role using its ARN. The following shows an example of this ARN:
arn:aws:iam::account-id:role/iam-role-name
This IAM role must contain a policy to allow the action to be executed. It must also have API Gateway
declared (in the role's trust relationship) as a trusted entity to assume the role. Such permissions can be
granted on the action itself. They are known as resource-based permissions. For the Lambda integration,
you can call the Lambda's addPermission action to set the resource-based permissions and then set
credentials to null in the API Gateway integration request.
We discussed the basic integration setup. Advanced settings involve mapping method request data
to the integration request data. After discussing the basic setup for an integration response, we cover
advanced topics in Set up request and response data mappings using the API Gateway console (p. 387),
where we also cover passing payload through and handling content encodings.
You choose an API integration type according to the types of integration endpoint you work with and
how you want data to pass to and from the integration endpoint. For a Lambda function, you can have
the Lambda proxy integration, or the Lambda custom integration. For an HTTP endpoint, you can have
the HTTP proxy integration or the HTTP custom integration. For an AWS service action, you have the
AWS integration of the non-proxy type only. API Gateway also supports the mock integration, where API
Gateway serves as an integration endpoint to respond to a method request.
The Lambda custom integration is a special case of the AWS integration, where the integration endpoint
corresponds to the function-invoking action of the Lambda service.
Programmatically, you choose an integration type by setting the type property on the Integration
resource. For the Lambda proxy integration, the value is AWS_PROXY. For the Lambda custom integration
and all other AWS integrations, it is AWS. For the HTTP proxy integration and HTTP integration, the value
is HTTP_PROXY and HTTP, respectively. For the mock integration, the type value is MOCK.
The Lambda proxy integration supports a streamlined integration setup with a single Lambda function.
The setup is simple and can evolve with the backend without having to tear down the existing setup. For
these reasons, it is highly recommended for integration with a Lambda function.
In contrast, the Lambda custom integration allows for reuse of configured mapping templates for
various integration endpoints that have similar requirements of the input and output data formats. The
setup is more involved and is recommended for more advanced application scenarios.
Similarly, the HTTP proxy integration has a streamlined integration setup and can evolve with the
backend without having to tear down the existing setup. The HTTP custom integration is more involved
to set up, but allows for reuse of configured mapping templates for other integration endpoints.
326
Amazon API Gateway Developer Guide
Integrations
• AWS: This type of integration lets an API expose AWS service actions. In AWS integration, you must
configure both the integration request and integration response and set up necessary data mappings
from the method request to the integration request, and from the integration response to the method
response.
• AWS_PROXY: This type of integration lets an API method be integrated with the Lambda function
invocation action with a flexible, versatile, and streamlined integration setup. This integration relies on
direct interactions between the client and the integrated Lambda function.
With this type of integration, also known as the Lambda proxy integration, you do not set the
integration request or the integration response. API Gateway passes the incoming request from the
client as the input to the backend Lambda function. The integrated Lambda function takes the input
of this format (p. 339) and parses the input from all available sources, including request headers, URL
path variables, query string parameters, and applicable body. The function returns the result following
this output format (p. 340).
This is the preferred integration type to call a Lambda function through API Gateway and is not
applicable to any other AWS service actions, including Lambda actions other than the function-
invoking action.
• HTTP: This type of integration lets an API expose HTTP endpoints in the backend. With the HTTP
integration, also known as the HTTP custom integration, you must configure both the integration
request and integration response. You must set up necessary data mappings from the method request
to the integration request, and from the integration response to the method response.
• HTTP_PROXY: The HTTP proxy integration allows a client to access the backend HTTP endpoints with
a streamlined integration setup on single API method. You do not set the integration request or the
integration response. API Gateway passes the incoming request from the client to the HTTP endpoint
and passes the outgoing response from the HTTP endpoint to the client.
• MOCK: This type of integration lets API Gateway return a response without sending the request further
to the backend. This is useful for API testing because it can be used to test the integration set up
without incurring charges for using the backend and to enable collaborative development of an API.
In collaborative development, a team can isolate their development effort by setting up simulations
of API components owned by other teams by using the MOCK integrations. It is also used to return
CORS-related headers to ensure that the API method permits CORS access. In fact, the API Gateway
console integrates the OPTIONS method to support CORS with a mock integration. Gateway
responses (p. 422) are other examples of mock integrations.
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.
API Gateway enacts certain restrictions and limitations when handling methods with either a Lambda
proxy integration or an HTTP proxy integration. For details, see the section called “Important
notes” (p. 819).
327
Amazon API Gateway Developer Guide
Integrations
Note
When using proxy integration with a passthrough, API Gateway returns the default Content-
Type:application/json header if the content type of a payload is unspecified.
A proxy resource is most powerful when it is integrated with a backend using either HTTP proxy
integration or Lambda proxy integration.
The HTTP proxy integration, designated by HTTP_PROXY in the API Gateway REST API, is for integrating
a method request with a backend HTTP endpoint. With this integration type, API Gateway simply passes
the entire request and response between the frontend and the backend, subject to certain restrictions
and limitations (p. 819).
Note
HTTP proxy integration supports multi-valued headers and query strings.
When applying the HTTP proxy integration to a proxy resource, you can set up your API to expose
a portion or an entire endpoint hierarchy of the HTTP backend with a single integration setup. For
example, suppose the backend of the website is organized into multiple branches of tree nodes off
the root node (/site) as: /site/a0/a1/.../aN, /site/b0/b1/.../bM, etc. If you integrate the ANY
method on a proxy resource of /api/{proxy+} with the backend endpoints with URL paths of /site/
{proxy}, a single integration request can support any HTTP operations (GET, POST, etc.) on any of [a0,
a1, ..., aN, b0, b1, ...bM, ...]. If you apply a proxy integration to a specific HTTP method, for
example, GET, instead, the resulting integration request works with the specified (that is, GET) operations
on any of those backend nodes.
The Lambda proxy integration, designated by AWS_PROXY in the API Gateway REST API, is for integrating
a method request with a Lambda function in the backend. With this integration type, API Gateway
applies a default mapping template to send the entire request to the Lambda function and transforms
the output from the Lambda function to HTTP responses.
Similarly, you can apply the Lambda proxy integration to a proxy resource of /api/{proxy+} to set up
a single integration to have a backend Lambda function react individually to changes in any of the API
resources under /api.
The following procedure describes how to use the API Gateway console to specify method settings.
• Choose Lambda Function if your API will be integrated with a Lambda function. At the API level,
this is an AWS integration type.
• Choose HTTP if your API will be integrated with an HTTP endpoint. At the API level, this is the
HTTP integration type.
• Choose AWS Service if your API will be integrated directly with an AWS service. At the API level,
this is the AWS integration type. The Lambda Function option above is a special case of the AWS
integration for invoking a Lambda function and is available only in the API Gateway console. To
328
Amazon API Gateway Developer Guide
Integrations
set up an API Gateway API to create a new Lambda function in AWS Lambda, to set a resource
permission on the Lambda function, or to perform any other Lambda service actions, you must
choose the AWS Service option here.
• Choose Mock if you want API Gateway to act as your backend to return static responses. At the
API level, this is the MOCK integration type. Typically, you can use the MOCK integration when
your API is not yet final, but you want to generate API responses to unblock dependent teams
for testing. For the OPTION method, API Gateway sets the MOCK integration as default to return
CORS-enabling headers for the applied API resource. If you choose this option, skip the rest of the
instructions in this topic and see Set up mock integrations in API Gateway (p. 361).
3. If you chose Lambda Function, do the following:
a. 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, choose us-east-1. For a list of region names and identifiers, see AWS
Lambda in the Amazon Web Services General Reference.
b. For Lambda Function, type the name of the Lambda function, and then choose the function's
corresponding ARN.
c. Choose Save.
4. If you chose HTTP, do the following:
a. For HTTP method, choose the HTTP method type that most closely matches the method in the
HTTP backend.
b. For Endpoint URL, type the URL of the HTTP backend you want this method to use.
c. Choose Save.
5. If you chose Mock, do the following:
• Choose Save.
6. If you chose AWS Service, do the following:
a. For AWS Region, choose the AWS Region you want this method to use to call the action.
b. For AWS Service, choose the AWS service you want this method to call.
c. For AWS Subdomain, type the subdomain used by the AWS service. Typically, you would leave
this blank. Some AWS services can support subdomains as part of the hosts. Consult the service
documentation for the availability and, if available, details.
d. 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.
e. 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.
f. For Execution Role, type the ARN of the IAM role that 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. 38) section. Specify an access policy of the following format, with the desired
number of action and resource statements:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"action-statement"
],
"Resource": [
329
Amazon API Gateway Developer Guide
Integrations
"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
action on behalf of your AWS account:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
g. If the action you typed for Action provides a custom resource path that 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.
h. Choose Save.
For a proxy integration, API Gateway automatically passes the backend output to the client as an HTTP
response. You do not set either an integration response or a method response.
To set up an integration response, you perform the following required and optional tasks:
1. Specify an HTTP status code of a method response to which the integration response data is mapped.
This is required.
2. Define a regular expression to select backend output to be represented by this integration response. If
you leave this empty, the response is the default response that is used to catch any response not yet
configured.
3. If needed, declare mappings consisting of key-value pairs to map specified integration response
parameters to given method response parameters.
4. If needed, add body-mapping templates to transform given integration response payloads into
specified method response payloads.
5. If needed, specify how to handle type conversion for a binary payload.
An integration response is an HTTP response encapsulating the backend response. For an HTTP
endpoint, the backend response is an HTTP response. The integration response status code can take the
330
Amazon API Gateway Developer Guide
Integrations
backend-returned status code, and the integration response body is the backend-returned payload. For
a Lambda endpoint, the backend response is the output returned from the Lambda function. With the
Lambda integration, the Lambda function output is returned as a 200 OK response. The payload can
contain the result as JSON data, including a JSON string or a JSON object, or an error message as a JSON
object. You can assign a regular expression to the selectionPattern property to map an error response to
an appropriate HTTP error response. For more information about the Lambda function error response,
see Handle Lambda errors in API Gateway (p. 346). With the Lambda proxy integration, the Lambda
function must return output of the following format:
{
statusCode: "...", // a valid HTTP status code
headers: {
custom-header: "..." // any API-specific custom header
},
body: "...", // a JSON string.
isBase64Encoded: true|false // for binary support
}
There is no need to map the Lambda function response to its proper HTTP response.
To return the result to the client, set up the integration response to pass the endpoint response through
as-is to the corresponding method response. Or you can map the endpoint response data to the method
response data. The response data that can be mapped includes the response status code, response
header parameters, and response body. If no method response is defined for the returned status
code, API Gateway returns a 500 error. For more information, see Working with models and mapping
templates (p. 377).
In Lambda proxy integration, the required setup is simple. Set the integration's HTTP method to POST,
the integration endpoint URI to the ARN of the Lambda function invocation action of a specific Lambda
function, and grant API Gateway permission to call the Lambda function on your behalf.
In Lambda non-proxy integration, in addition to the proxy integration setup steps, you also specify
how the incoming request data is mapped to the integration request and how the resulting integration
response data is mapped to the method response.
Topics
• Set up Lambda proxy integrations in API Gateway (p. 331)
• Set up Lambda custom integrations in API Gateway (p. 341)
• Set up asynchronous invocation of the backend Lambda function (p. 345)
• Handle Lambda errors in API Gateway (p. 346)
331
Amazon API Gateway Developer Guide
Integrations
Amazon API Gateway Lambda proxy integration is a simple, powerful, and nimble mechanism to build
an API with a setup of a single API method. The Lambda proxy integration allows the client to call a
single Lambda function in the backend. The function accesses many resources or features of other AWS
services, including calling other Lambda functions.
In Lambda proxy integration, when a client submits an API request, API Gateway passes to the integrated
Lambda function the raw request as-is, except that the order of the request parameters is not preserved.
This request data (p. 339) includes the request headers, query string parameters, URL path variables,
payload, and API configuration data. The configuration data can include current deployment stage
name, stage variables, user identity, or authorization context (if any). The backend Lambda function
parses the incoming request data to determine the response that it returns. For API Gateway to pass
the Lambda output as the API response to the client, the Lambda function must return the result in this
format (p. 340).
Because API Gateway doesn't intervene very much between the client and the backend Lambda function
for the Lambda proxy integration, the client and the integrated Lambda function can adapt to changes
in each other without breaking the existing integration setup of the API. To enable this, the client must
follow application protocols enacted by the backend Lambda function.
You can set up a Lambda proxy integration for any API method. But a Lambda proxy integration is more
potent when it is configured for an API method involving a generic proxy resource. The generic proxy
resource can be denoted by a special templated path variable of {proxy+}, the catch-all ANY method
placeholder, or both. The client can pass the input to the backend Lambda function in the incoming
request as request parameters or applicable payload. The request parameters include headers, URL path
variables, query string parameters, and the applicable payload. The integrated Lambda function verifies
all of the input sources before processing the request and responding to the client with meaningful error
messages if any of the required input is missing.
When calling an API method integrated with the generic HTTP method of ANY and the generic resource
of {proxy+}, the client submits a request with a particular HTTP method in place of ANY. The client also
specifies a particular URL path instead of {proxy+}, and includes any required headers, query string
parameters, or an applicable payload.
The following list summarizes runtime behaviors of different API methods with the Lambda proxy
integration:
• ANY /{proxy+}: The client must choose a particular HTTP method, must set a particular resource
path hierarchy, and can set any headers, query string parameters, and applicable payload to pass the
data as input to the integrated Lambda function.
• ANY /res: The client must choose a particular HTTP method and can set any headers, query string
parameters, and applicable payload to pass the data as input to the integrated Lambda function.
• GET|POST|PUT|... /{proxy+}: The client can set a particular resource path hierarchy, any headers,
query string parameters, and applicable payload to pass the data as input to the integrated Lambda
function.
• GET|POST|PUT|... /res/{path}/...: The client must choose a particular path segment (for the
{path} variable) and can set any request headers, query string parameters, and applicable payload to
pass input data to the integrated Lambda function.
• GET|POST|PUT|... /res: The client can choose any request headers, query string parameters, and
applicable payload to pass input data to the integrated Lambda function.
Both the proxy resource of {proxy+} and the custom resource of {custom} are expressed as templated
path variables. However {proxy+} can refer to any resource along a path hierarchy, while {custom}
332
Amazon API Gateway Developer Guide
Integrations
refers to a particular path segment only. For example, a grocery store might organize its online product
inventory by department names, produce categories, and product types. The grocery store's website
can then represent available products by the following templated path variables of custom resources: /
{department}/{produce-category}/{product-type}. For example, apples are represented by /
produce/fruit/apple and carrots by /produce/vegetables/carrot. It can also use /{proxy+}
to represent any department, any produce category, or any product type that a customer can search for
while shopping in the online store. For example, /{proxy+} can refer to any of the following items:
• /produce
• /produce/fruit
• /produce/vegetables/carrot
To let customers search for any available product, its produce category, and the associated store
department, you can expose a single method of GET /{proxy+} with read-only permissions. Similarly,
to allow a supervisor to update the produce department's inventory, you can set up another single
method of PUT /produce/{proxy+} with read/write permissions. To allow a cashier to update the
running total of a vegetable, you can set up a POST /produce/vegetables/{proxy+} method with
read/write permissions. To let a store manager perform any possible action on any available product,
the online store developer can expose the ANY /{proxy+} method with read/write permissions. In any
case, at run time, the customer or the employee must select a particular product of a given type in a
chosen department, a specific produce category in a chosen department, or a specific department.
For more information about setting up API Gateway proxy integrations, see Set up a proxy integration
with a proxy resource (p. 327).
Proxy integration requires that the client have more detailed knowledge of the backend requirements.
Therefore, to ensure optimal app performance and user experience, the backend developer must
communicate clearly to the client developer the requirements of the backend, and provide a robust error
feedback mechanism when the requirements are not met.
API Gateway supports multiple headers and query string parameters that have the same name. Multi-
value headers as well as single-value headers and parameters can be combined in the same requests and
responses. For more information, see Input format of a Lambda function for proxy integration (p. 339)
and Output format of a Lambda function for proxy integration (p. 340).
To set up a proxy resource with the Lambda proxy integration type, create an API
resource with a greedy path parameter (for example, /parent/{proxy+}) and integrate
this resource with a Lambda function backend (for example, arn:aws:lambda:us-
west-2:123456789012:function:SimpleLambda4ProxyResource) on the ANY method. The
greedy path parameter must be at the end of the API resource path. As with a non-proxy resource, you
can set up the proxy resource by using the API Gateway console, importing an OpenAPI definition file, or
calling the API Gateway REST API directly.
The following OpenAPI API definition file shows an example of an API with a proxy resource that is
integrated with a Lambda function named SimpleLambda4ProxyResource.
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"version": "2016-09-12T17:50:37Z",
"title": "ProxyIntegrationWithLambda"
333
Amazon API Gateway Developer Guide
Integrations
},
"paths": {
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"parameters": [
{
"name": "proxy",
"in": "path",
"required": true,
"schema": {
"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:us-east-1:123456789012:function:SimpleLambda4ProxyResource/invocations",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"cacheNamespace": "roq9wj",
"cacheKeyParameters": [
"method.request.path.proxy"
],
"type": "aws_proxy"
}
}
}
},
"servers": [
{
"url": "https://gy415nuibc.execute-api.us-east-1.amazonaws.com/{basePath}",
"variables": {
"basePath": {
"default": "/testStage"
}
}
}
]
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-09-12T17:50:37Z",
"title": "ProxyIntegrationWithLambda"
},
"host": "gy415nuibc.execute-api.us-east-1.amazonaws.com",
"basePath": "/testStage",
"schemes": [
"https"
],
"paths": {
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"produces": [
"application/json"
],
334
Amazon API Gateway Developer Guide
Integrations
"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:us-east-1:123456789012:function:SimpleLambda4ProxyResource/invocations",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"cacheNamespace": "roq9wj",
"cacheKeyParameters": [
"method.request.path.proxy"
],
"type": "aws_proxy"
}
}
}
}
}
In 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
string 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. 339). For API Gateway to map
the Lambda output to HTTP responses successfully, the Lambda function must output the result in the
format described in Output format of a Lambda function for proxy integration (p. 340).
In Lambda proxy integration of a proxy resource through the ANY method, the single backend 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 information of state, city, street, and
building by submitting a request with /state/city/street/house in the URL path for the proxy
resource. The backend Lambda function can then parse the URL path and insert the location tuples into a
DynamoDB table.
In this section, we show how to use AWS CLI to set up an API with the Lambda proxy integration.
Note
For detailed instructions for using the API Gateway console to configure a proxy resource with
the Lambda proxy integration, see Tutorial: Build a Hello World REST API with Lambda proxy
integration (p. 31).
As an example, we use the following sample Lambda function as the backend of the API:
335
Amazon API Gateway Developer Guide
Integrations
}
};
var greeter = 'World';
if (event.greeter && event.greeter!=="") {
greeter = event.greeter;
} else if (event.body && event.body !== "") {
var body = JSON.parse(event.body);
if (body.greeter && body.greeter !== "") {
greeter = body.greeter;
}
} else if (event.queryStringParameters && event.queryStringParameters.greeter &&
event.queryStringParameters.greeter !== "") {
greeter = event.queryStringParameters.greeter;
} else if (event.multiValueHeaders && event.multiValueHeaders.greeter &&
event.multiValueHeaders.greeter != "") {
greeter = event.multiValueHeaders.greeter.join(" and ");
} else if (event.headers && event.headers.greeter && event.headers.greeter != "") {
greeter = event.headers.greeter;
}
Comparing this to the Lambda custom integration setup (p. 342), the input to this Lambda function
can be expressed in the request parameters and body. You have more latitude to allow the client to
pass the same input data. Here, the client can pass the greeter's name in as a query string parameter, a
header, or a body property. The function can also support the Lambda custom integration. The API setup
is simpler. You do not configure the method response or integration response at all.
{
"name": "HelloWorldProxy (AWS CLI)",
"id": "te6si5ach7",
"createdDate": 1508461860
}
{
"items": [
{
"path": "/",
"id": "krznpq9xpg"
}
]
}
336
Amazon API Gateway Developer Guide
Integrations
Note the root resource id value (krznpq9xpg). You need it in the next step and later.
3. Call create-resource to create an API Gateway Resource of /greeting:
{
"path": "/{proxy+}",
"pathPart": "{proxy+}",
"id": "2jf6xt",
"parentId": "krznpq9xpg"
}
Note the resulting {proxy+} resource's id value (2jf6xt). You need it to create a method on the /
{proxy+} resource in the next step.
4. Call put-method to create an ANY method request of ANY /{proxy+}:
{
"apiKeyRequired": false,
"httpMethod": "ANY",
"authorizationType": "NONE"
}
This API method allows the client to receive or send greetings from the Lambda function at the
backend.
5. Call put-integration to set up the integration of the ANY /{proxy+} method with a Lambda
function, named HelloWorld. This function responds to the request with a message of "Hello,
{name}!", if the greeter parameter is provided, or "Hello, World!", if the query string
parameter is not set.
Important
For Lambda integrations, you must use the HTTP method of POST for the integration
request, according to the specification of the Lambda service action for function
337
Amazon API Gateway Developer Guide
Integrations
invocations. The IAM role of apigAwsProxyRole must have policies allowing the
apigateway service to invoke Lambda functions. For more information about IAM
permissions, see the section called “ API Gateway permissions model for invoking an
API” (p. 291).
{
"passthroughBehavior": "WHEN_NO_MATCH",
"cacheKeyParameters": [],
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:1234567890:function:HelloWorld/invocations",
"httpMethod": "POST",
"cacheNamespace": "vvom7n",
"credentials": "arn:aws:iam::1234567890:role/apigAwsProxyRole",
"type": "AWS_PROXY"
}
Instead of supplying an IAM role for credentials, you can call the add-permission command to
add resource-based permissions. This is what the API Gateway console does.
6. Call create-deployment to deploy the API to a test stage:
In all the cases, the output is a 200 response with the following response body:
Hello, jane!
338
Amazon API Gateway Developer Guide
Integrations
{
"resource": "/my/path",
"path": "/my/path",
"httpMethod": "GET",
"headers": {
"header1": "value1",
"header2": "value2"
},
"multiValueHeaders": {
"header1": [
"value1"
],
"header2": [
"value1",
"value2"
]
},
"queryStringParameters": {
"parameter1": "value1",
"parameter2": "value"
},
"multiValueQueryStringParameters": {
"parameter1": [
"value1",
"value2"
],
"parameter2": [
"value"
]
},
"requestContext": {
"accountId": "123456789012",
"apiId": "id",
"authorizer": {
"claims": null,
"scopes": null
},
"domainName": "id.execute-api.us-east-1.amazonaws.com",
"domainPrefix": "id",
"extendedRequestId": "request-id",
"httpMethod": "GET",
"identity": {
"accessKey": null,
"accountId": null,
"caller": null,
"cognitoAuthenticationProvider": null,
"cognitoAuthenticationType": null,
"cognitoIdentityId": null,
"cognitoIdentityPoolId": null,
"principalOrgId": null,
"sourceIp": "IP",
"user": null,
"userAgent": "user-agent",
"userArn": null,
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
339
Amazon API Gateway Developer Guide
Integrations
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"path": "/my/path",
"protocol": "HTTP/1.1",
"requestId": "id=",
"requestTime": "04/Mar/2020:19:15:17 +0000",
"requestTimeEpoch": 1583349317135,
"resourceId": null,
"resourcePath": "/my/path",
"stage": "$default"
},
"pathParameters": null,
"stageVariables": null,
"body": "Hello from Lambda!",
"isBase64Encoded": false
}
Note
In the input:
In the input to the backend Lambda function, the requestContext object is a map of key-value pairs.
In each pair, the key is the name of a $context (p. 410) variable property, and the value is the value of
that property. API Gateway may add new keys to the map.
Depending on the features that are enabled, the requestContext map may vary from API to API. For
example, in the preceding example, no authorization type is specified, so no $context.authorizer.*
or $context.identity.* properties are present. When an authorization type is specified,
this causes API Gateway to pass authorized user information to the integration endpoint in a
requestContext.identity object as follows:
• When the authorization type is AWS_IAM, the authorized user information includes
$context.identity.* properties.
• When the authorization type is COGNITO_USER_POOLS (Amazon Cognito authorizer), the authorized
user information includes $context.identity.cognito* and $context.authorizer.claims.*
properties.
• When the authorization type is CUSTOM (Lambda authorizer), the authorized user information includes
$context.authorizer.principalId and other applicable $context.authorizer.* properties.
In Lambda proxy integration, API Gateway requires the backend Lambda function to return output
according to the following JSON format:
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
340
Amazon API Gateway Developer Guide
Integrations
In the output:
• The headers and multiValueHeaders keys can be unspecified if no extra response headers are to
be returned.
• The headers key can only contain single-value headers.
• The multiValueHeaders key can contain multi-value headers as well as single-value headers. You
can use the multiValueHeaders key to specify all of your extra headers, including any single-value
ones.
• If you specify values for both headers and multiValueHeaders, API Gateway merges them into a
single list. If the same key-value pair is specified in both, only the values from multiValueHeaders
will appear in the merged list.
To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow-
Origin:domain-name to the output headers. domain-name can be * for any domain name. The
output body is marshalled to the frontend as the method response payload. If body is a binary blob, you
can encode it as a Base64-encoded string by setting isBase64Encoded to true and configuring */* as
a Binary Media Type. Otherwise, you can set it to false or leave it unspecified.
Note
For more information about enabling binary support, see Enabling binary support using the API
Gateway console (p. 440). For an example Lambda function, see Return binary media from a
Lambda proxy integration (p. 447).
If the function output is of a different format, API Gateway returns a 502 Bad Gateway error response.
To return a response in a Lambda function in Node.js, you can use commands such as the following:
341
Amazon API Gateway Developer Guide
Integrations
message of "Missing the required greeter parameter." if the greeter parameter is not set in
the incoming request. We name the function HelloWorld.
You can create it in the Lambda console or by using the AWS CLI. In this section, we reference this
function using the following ARN:
arn:aws:lambda:us-east-1:123456789012:function:HelloWorld
With the Lambda function set in the backend, proceed to set up the API.
{
"name": "HelloWorld (AWS CLI)",
"id": "te6si5ach7",
"createdDate": 1508461860
}
{
"items": [
{
"path": "/",
"id": "krznpq9xpg"
}
]
342
Amazon API Gateway Developer Guide
Integrations
Note the root resource id value (krznpq9xpg). You need it in the next step and later.
3. Call create-resource to create an API Gateway Resource of /greeting:
{
"path": "/greeting",
"pathPart": "greeting",
"id": "2jf6xt",
"parentId": "krznpq9xpg"
}
Note the resulting greeting resource's id value (2jf6xt). You need it to create a method on the /
greeting resource in the next step.
4. Call put-method to create an API method request of GET /greeting?greeter={name}:
{
"apiKeyRequired": false,
"httpMethod": "GET",
"authorizationType": "NONE",
"requestParameters": {
"method.request.querystring.greeter": false
}
}
This API method allows the client to receive a greeting from the Lambda function at the backend.
The greeter parameter is optional because the backend should handle either an anonymous caller
or a self-identified caller.
5. Call put-method-response to set up the 200 OK response to the method request of GET /
greeting?greeter={name}:
343
Amazon API Gateway Developer Guide
Integrations
{"application/json":"{\"greeter\":\"$input.params('greeter')\"}"}
The mapping template supplied here translates the greeter query string parameter to the
greeter property of the JSON payload. This is necessary because input to a Lambda function
in the Lambda function must be expressed in the body. You could use JSON string of the map
(for example, "{\"greeter"\: \"'john'\"}") as the request-template input value to the
put-integration command. However, using the file input avoids the difficult, and sometimes
impossible, quote-escaping that is required to stringify a JSON object.
Important
For Lambda integrations, you must use the HTTP method of POST for the integration
request, according to the specification of the Lambda service action for function
invocations. The uri parameter is the ARN of the function-invoking action.
Successful output is similar to the following:
{
"passthroughBehavior": "WHEN_NO_MATCH",
"cacheKeyParameters": [],
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations",
"httpMethod": "POST",
"requestTemplates": {
"application/json": "{\"greeter\":\"$input.params('greeter')\"}"
},
"cacheNamespace": "krznpq9xpg",
"credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole",
"type": "AWS"
}
The IAM role of apigAwsProxyRole must have policies that allow the apigateway service to
invoke Lambda functions. Instead of supplying an IAM role for credentials, you can call the add-
permission command to add resource-based permissions. This is how the API Gateway console adds
these permissions.
7. Call put-integration-response to set up the integration response to pass the Lambda function
output to the client as the 200 OK method response.
344
Amazon API Gateway Developer Guide
Integrations
--region us-west-2 \
--rest-api-id te6si5ach7 \
--resource-id 2jf6xt \
--http-method GET \
--status-code 200 \
--selection-pattern ""
By setting the selection-pattern to an empty string, the 200 OK response is the default.
{
"selectionPattern": "",
"statusCode": "200"
}
You can configure the Lambda function for a Lambda non-proxy integration to be invoked
asynchronously by specifying 'Event' as the Lambda invocation type. This is done as follows:
345
Amazon API Gateway Developer Guide
Integrations
There are two types of errors that Lambda can return: standard errors and custom errors. In your API, you
must handle these differently.
With the Lambda proxy integration, Lambda is required to return an output of the following format:
{
"isBase64Encoded" : "boolean",
"statusCode": "number",
"headers": { ... },
"body": "JSON string"
}
In this output, statusCode is typically 4XX for a client error and 5XX for a server error. API Gateway
handles these errors by mapping the Lambda error to an HTTP error response, according to the specified
statusCode. For API Gateway to pass the error type (for example, InvalidParameterException), as
part of the response to the client, the Lambda function must include a header (for example, "X-Amzn-
ErrorType":"InvalidParameterException") in the headers property.
Topics
• Handle standard Lambda errors in API Gateway (p. 346)
• Handle custom Lambda errors in API Gateway (p. 348)
{
"errorMessage": "<replaceable>string</replaceable>",
"errorType": "<replaceable>string</replaceable>",
"stackTrace": [
"<replaceable>string</replaceable>",
...
]
}
Here, errorMessage is a string expression of the error. The errorType is a language-dependent error
or exception type. The stackTrace is a list of string expressions showing the stack trace leading to the
occurrence of the error.
This function returns the following standard Lambda error, containing Malformed input ... as the
error message:
{
"errorMessage": "Malformed input ...",
346
Amazon API Gateway Developer Guide
Integrations
"errorType": "Error",
"stackTrace": [
"exports.handler (/var/task/index.js:3:14)"
]
}
Similarly, consider the following Python Lambda function, which raises an Exception with the same
Malformed input ... error message.
{
"stackTrace": [
[
"/var/task/lambda_function.py",
3,
"lambda_handler",
"raise Exception('Malformed input ...')"
]
],
"errorType": "Exception",
"errorMessage": "Malformed input ..."
}
Note that the errorType and stackTrace property values are language-dependent. The standard
error also applies to any error object that is an extension of the Error object or a subclass of the
Exception class.
To map the standard Lambda error to a method response, you must first decide on an HTTP status code
for a given Lambda error. You then set a regular expression pattern on the selectionPattern property
of the IntegrationResponse associated with the given HTTP status code. In the API Gateway console,
this selectionPattern is denoted as Lambda Error Regex in the Integration Response configuration
editor.
Note
API Gateway uses Java pattern-style regexes for response mapping. For more information, see
Pattern in the Oracle documentation.
For example, to set up a new selectionPattern expression, using AWS CLI, call the following put-
integration-response command:
Make sure that you also set up the corresponding error code (400) on the method response (p. 269).
Otherwise, API Gateway throws an invalid configuration error response at runtime.
Note
At runtime, API Gateway matches the Lambda error's errorMessage against the pattern of
the regular expression on the selectionPattern property. If there is a match, API Gateway
returns the Lambda error as an HTTP response of the corresponding HTTP status code. If
there is no match, API Gateway returns the error as a default response or throws an invalid
configuration exception if no default response is configured.
Setting the selectionPattern value to .* for a given response amounts to resetting this
response as the default response. This is because such a selection pattern will match all error
347
Amazon API Gateway Developer Guide
Integrations
messages, including null, i.e., any unspecified error message. The resulting mapping overrides
the default mapping.
To update an existing selectionPattern value using the AWS CLI, call the update-integration-
response operation to replace the /selectionPattern path value with the specified regex expression
of the Malformed* pattern.
To set the selectionPattern expression using the API Gateway console, type the expression in the
Lambda Error Regex text box when setting up or updating an integration response of a specified HTTP
status code.
Instead of the standard error described in the preceding section, AWS Lambda allows you to return a
custom error object as JSON string. The error can be any valid JSON object. For example, the following
JavaScript (Node.js) Lambda function returns a custom error:
You must turn the myErrorObj object into a JSON string before calling callback to exit the function.
Otherwise, the myErrorObj is returned as a string of "[object Object]". When a method of your
API is integrated with the preceding Lambda function, API Gateway receives an integration response with
the following payload:
{
"errorMessage": "{\"errorType\":\"InternalServerError\",\"httpStatus\":500,\"requestId
\":\"e5849002-39a0-11e7-a419-5bb5807c9fb2\",\"trace\":{\"function\":\"abc()\",\"line\":123,
\"file\":\"abc.js\"}}"
}
As with any integration response, you can pass through this error response as-is to the method response.
Or you can have a body-mapping template to transform the payload into a different format. For
example, consider the following body-mapping template for a method response of 500 status code:
{
errorMessage: $input.path('$.errorMessage');
}
This template translates the integration response body that contains the custom error JSON string to the
following method response body. This method response body contains the custom error JSON object:
{
"errorMessage" : {
errorType : "InternalServerError",
348
Amazon API Gateway Developer Guide
Integrations
httpStatus : 500,
requestId : context.awsRequestId,
trace : {
"function": "abc()",
"line": 123,
"file": "abc.js"
}
}
};
Depending on your API requirements, you may need to pass some or all of the custom error properties as
method response header parameters. You can achieve this by applying the custom error mappings from
the integration response body to the method response headers.
For example, the following OpenAPI extension defines a mapping from the errorMessage.errorType,
errorMessage.httpStatus, errorMessage.trace.function, and errorMessage.trace
properties to the error_type, error_status, error_trace_function, and error_trace headers,
respectively.
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.error_trace_function":
"integration.response.body.errorMessage.trace.function",
"method.response.header.error_status":
"integration.response.body.errorMessage.httpStatus",
"method.response.header.error_type":
"integration.response.body.errorMessage.errorType",
"method.response.header.error_trace":
"integration.response.body.errorMessage.trace"
},
...
}
}
}
"error_status":"500",
"error_trace":"{\"function\":\"abc()\",\"line\":123,\"file\":\"abc.js\"}",
"error_trace_function":"abc()",
"error_type":"InternalServerError"
API Gateway supports the following endpoint ports: 80, 443 and 1024-65535.
349
Amazon API Gateway Developer Guide
Integrations
With proxy integration, setup is simple. You only need to set the HTTP method and the HTTP endpoint
URI, according to the backend requirements, if you are not concerned with content encoding or caching.
With custom integration, setup is more involved. In addition to the proxy integration setup steps, you
need to specify how the incoming request data is mapped to the integration request and how the
resulting integration response data is mapped to the method response.
Topics
• Set up HTTP proxy integrations in API Gateway (p. 350)
• Set up HTTP custom integrations in API Gateway (p. 354)
As with a non-proxy resource, you can set up a proxy resource with the HTTP proxy integration by using
the API Gateway console, importing an OpenAPI definition file, or calling the API Gateway REST API
directly. For detailed instructions about using the API Gateway console to configure a proxy resource with
the HTTP integration, see Tutorial: Build a REST API with HTTP proxy integration (p. 54).
The following OpenAPI definition file shows an example of an API with a proxy resource that is
integrated with the PetStore website.
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"version": "2016-09-12T23:19:28Z",
"title": "PetStoreWithProxyResource"
},
"paths": {
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"parameters": [
{
"name": "proxy",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.path.proxy": "method.request.path.proxy"
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/{proxy}",
"passthroughBehavior": "when_no_match",
"httpMethod": "ANY",
350
Amazon API Gateway Developer Guide
Integrations
"cacheNamespace": "rbftud",
"cacheKeyParameters": [
"method.request.path.proxy"
],
"type": "http_proxy"
}
}
}
},
"servers": [
{
"url": "https://4z9giyi2c1.execute-api.us-east-1.amazonaws.com/{basePath}",
"variables": {
"basePath": {
"default": "/test"
}
}
}
]
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-09-12T23:19:28Z",
"title": "PetStoreWithProxyResource"
},
"host": "4z9giyi2c1.execute-api.us-east-1.amazonaws.com",
"basePath": "/test",
"schemes": [
"https"
],
"paths": {
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "proxy",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.path.proxy": "method.request.path.proxy"
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/{proxy}",
"passthroughBehavior": "when_no_match",
"httpMethod": "ANY",
"cacheNamespace": "rbftud",
"cacheKeyParameters": [
"method.request.path.proxy"
],
351
Amazon API Gateway Developer Guide
Integrations
"type": "http_proxy"
}
}
}
}
}
The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200
OK response with the payload containing the first batch of pets, as returned from the backend.
• Set ANY as GET and {proxy+} as pets?type=dog
The run-time instances of the ANY method and proxy resource are both valid. The call returns a
200 OK response with the payload containing the first batch of specified dogs, as returned from the
backend.
• Set ANY as GET and {proxy+} as pets/{petId}
The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200
OK response with the payload containing the specified pet, as returned from the backend.
• Set ANY as POST and {proxy+} as pets
352
Amazon API Gateway Developer Guide
Integrations
Content-Type: application/json
Content-Length: ...
{
"type" : "dog",
"price" : 1001.00
}
{
"type" : "dog",
"price" : 1001.00
}
The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200
OK response with the payload containing the newly created pet, as returned from the backend.
• Set ANY as GET and {proxy+} as pets/cat
GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/cat
GET http://petstore-demo-endpoint.execute-api.com/petstore/pets/cat
The run-time instance of the proxy resource path does not correspond to a backend 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"
}
]
}
GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test
GET http://petstore-demo-endpoint.execute-api.com/petstore/pets
353
Amazon API Gateway Developer Guide
Integrations
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 returns a 404
Not Found response with the Cannot GET /petstore message as returned from the backend.
For any client request, if the targeted endpoint URL is invalid or the HTTP verb is valid but not
supported, the backend returns a 404 Not Found response. For an unsupported HTTP method, a 403
Forbidden response is returned.
As part of the method request setup, you set the requestParameters property on a Method resource.
This declares which method request parameters, which are provisioned from the client, are to be
mapped to integration request parameters or applicable body properties before being dispatched to the
backend. Then, as part of the integration request setup, you set the requestParameters property on the
corresponding Integration resource to specify the parameter-to-parameter mappings. You also set the
requestTemplates property to specify mapping templates, one for each supported content type. The
mapping templates map method request parameters, or body, to the integration request body.
Similarly, as part of the method response setup, you set the responseParameters property on the
MethodResponse resource. This declares which method response parameters, to be dispatched to the
client, are to be mapped from integration response parameters or certain applicable body properties
that were returned from the backend. Then, as part of the integration response setup, you set the
responseParameters property on the corresponding IntegrationResponse resource to specify the
parameter-to-parameter mappings. You also set the responseTemplates map to specify mapping
templates, one for each supported content type. The mapping templates map integration response
parameters, or integration response body properties, to the method response body.
For more information about setting up mapping templates, see Setting up data transformations for
REST APIs (p. 376).
To create a private integration, you must first create a Network Load Balancer. Your Network Load
Balancer must have a listener that routes requests to resources in your VPC. To improve the availability
of your API, ensure that your Network Load Balancer routes traffic to resources in more than one
Availability Zone in the AWS Region. Then, you create a VPC link that you use to connect your API and
your Network Load Balancer. After you create a VPC link, you create private integrations to route traffic
from your API to resources in your VPC through your VPC link and Network Load Balancer.
Note
The Network Load Balancer and API must be owned by the same AWS account.
With the API Gateway private integration, you can enable access to HTTP/HTTPS resources within a VPC
without detailed knowledge of private network configurations or technology-specific appliances.
Topics
• Set up a Network Load Balancer for API Gateway private integrations (p. 355)
354
Amazon API Gateway Developer Guide
Integrations
For each VPC you have resources in, you only need to configure one NLB and one VPCLink. The NLB
supports multiple listeners and target groups per NLB. You can configure each service as a specific
listener on the NLB and use a single VPCLink to connect to the NLB. When creating the private
integration in API Gateway you then define each service using the specific port that is assigned
for each service. For more information, see the section called “Tutorial: Build an API with private
integration” (p. 87).
Note
The Network Load Balancer and API must be owned by the same AWS account.
To create a Network Load Balancer for private integration using the API Gateway console
1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://
console.aws.amazon.com/ec2/.
2. Set up a web server on an Amazon EC2 instance. For an example setup, see Installing a LAMP Web
Server on Amazon Linux.
3. Create a Network Load Balancer, register the EC2 instance with a target group, and add the target
group to a listener of the Network Load Balancer. For details, follow the instructions in Getting
Started with Network Load Balancers.
After the Network Load Balancer is created, note its ARN. You will need it to create a VPC link in API
Gateway for integrating the API with the VPC resources behind the Network Load Balancer.
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"ec2:CreateVpcEndpointServiceConfiguration",
"ec2:DeleteVpcEndpointServiceConfigurations",
"ec2:DescribeVpcEndpointServiceConfigurations",
"ec2:ModifyVpcEndpointServicePermissions"
],
355
Amazon API Gateway Developer Guide
Integrations
"Resource":"*"
},
{
"Effect":"Allow",
"Action":[
"elasticloadbalancing:DescribeLoadBalancers"
],
"Resource":"*"
}
]
}
2. Create or choose an IAM role and attach the preceding policy to the role.
3. Assign the IAM role to you or a user in your account who is creating VPC links.
Set up an API Gateway API with private integrations using the API Gateway
console
For instructions using the API Gateway Console to set up an API with private integration, see Tutorial:
Build a REST API with API Gateway private integration (p. 87).
Set up an API Gateway API with private integrations using the AWS CLI
Before creating an API with the private integration, you must have your VPC resource set up and a
Network Load Balancer created and configured with your VPC source as the target. If the requirements
are not met, follow Set up a Network Load Balancer for API Gateway private integrations (p. 355) to
install the VPC resource, create a Network Load Balancer, and set the VPC resource as a target of the
Network Load Balancer.
Note
The Network Load Balancer and API must be owned by the same AWS account.
For you to be able to create and manage a VpcLink, you must also have the appropriate permissions
configured. For more information, see Grant permissions to create a VPC link (p. 355).
Note
You only need the permissions to create a VpcLink in your API. You do not need the
permissions to use the VpcLink.
After the Network Load Balancer is created, note its ARN. You need it to create a VPC link for the private
integration.
For this discussion, we assume the ARN of the Network Load Balancer is
arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/my-
vpclink-test-nlb/1f8df693cd094a72.
The preceding command immediately returns the following response, acknowledging the receipt of
the request, and showing the PENDING status for the VpcLink being created.
356
Amazon API Gateway Developer Guide
Integrations
"status": "PENDING",
"targetArns": [
"arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/my-
vpclink-test-nlb/1f8df693cd094a72"
],
"id": "gim7c3",
"name": "my-test-vpc-link"
}
It takes 2-4 minutes for API Gateway to finish creating the VpcLink. When the operation finishes
successfully, the status is AVAILABLE. You can verify this by calling the following CLI command:
If the operation fails, you get a FAILED status, with the statusMessage containing the error
message. For example, if you attempt to create a VpcLink with a Network Load Balancer that is
already associated with a VPC endpoint, you get the following on the statusMessage property:
Only after the VpcLink is created successfully are we ready to create the API and integrate it with
the VPC resource through the VpcLink.
Note the id value of the newly created VpcLink (gim7c3 in the preceding output). You need it to
set up the private integration.
2. Set up an API by creating an API Gateway RestApi resource:
We have dropped the input parameters of endpoint-url and region to use the default region as
specified in the AWS configuration.
Note the RestApi's id value in the returned result. In this example, we assume it is abcdef123.
You need this value to perform further operations on the API, including setting up methods and
integrations.
For illustration purposes, we will create an API with only a GET method on the root resource (/) and
integrate the method with the VpcLink.
3. Set up the GET / method. First get the identifier of the root resource (/):
In the output, note the id value of the / path. In this example, we assume it to be skpp60rab7.
To use the IAM permissions, a Lambda authorizer, or an Amazon Cognito user pool to authenticate
the caller, set the authorization-type to AWS_IAM, CUSTOM, or COGNITO_USER_POOLS,
respectively.
357
Amazon API Gateway Developer Guide
Integrations
If you do not use the proxy integration with the VpcLink, you must also set up at least a method
response of the 200 status code. We will use the proxy integration here.
4. Set up the private integration of the HTTP_PROXY type and call the put-integration command
as follows:
For a private integration, you must set connection-type to VPC_LINK and set connection-
id to either your VpcLink's identifier or a stage variable referencing your VpcLink ID. The uri
parameter is not used for routing requests to your endpoint, but is used for setting the Host header
and for certificate validation.
{
"passthroughBehavior": "WHEN_NO_MATCH",
"timeoutInMillis": 29000,
"connectionId": "gim7c3",
"uri": "http://myApi.example.com",
"connectionType": "VPC_LINK",
"httpMethod": "GET",
"cacheNamespace": "skpp60rab7",
"type": "HTTP_PROXY",
"cacheKeyParameters": []
}
Using a stage variable, you set the connectionId property when creating the integration:
Alternatively, you can update the integration to reset the connectionId value with a stage
variable:
358
Amazon API Gateway Developer Guide
Integrations
Make sure to use a stringified JSON list as the patch-operations parameter value.
Using a stage variable to set the connectionId value has the advantage of having the same API
integrated with different VpcLinks by resetting the stage variable value. This is useful for switching
your API to a different VPC link to migrate to a different Network Load Balancer or a different VPC.
Because we used the private proxy integration, the API is now ready for deployment and for test
runs. With the non-proxy integration, you must also set up the method response and integration
response, just as you would when setting up an API with HTTP custom integrations (p. 60).
5. To test the API, deploy the API. This is necessary if you have used the stage variable as a placeholder
of the VpcLink ID. To deploy the API with a stage variable, call the create-deployment command
as follows:
To update the stage variable with a different VpcLink ID (e.g., asf9d7), call the update-stage
command:
Alternatively, you can type the API's invoke-URL in a web browser to view the result.
When you hardcode the connection-id property with the VpcLink ID literal, you can also call
test-invoke-method to test invoking the API before it is deployed.
You can use a stage variable to reference the VpcLink ID. Or you can assign the ID value directly to
connectionId.
The following JSON-formatted OpenAPI file shows an example of an API with a VPC link as referenced
by a stage variable (${stageVariables.vpcLinkId}):
359
Amazon API Gateway Developer Guide
Integrations
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2017-11-17T04:40:23Z",
"title": "MyApiWithVpcLink"
},
"host": "p3wocvip9a.execute-api.us-west-2.amazonaws.com",
"basePath": "/test",
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"uri": "http://myApi.example.com",
"passthroughBehavior": "when_no_match",
"connectionType": "VPC_LINK",
"connectionId": "${stageVariables.vpcLinkId}",
"httpMethod": "GET",
"type": "http_proxy"
}
}
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
Region Account ID
us-east-1 392220576650
us-east-2 718770453195
360
Amazon API Gateway Developer Guide
Integrations
Region Account ID
us-west-1 968246515281
us-west-2 109351309407
ca-central-1 796887884028
eu-west-1 631144002099
eu-west-2 544388816663
eu-west-3 061510835048
eu-central-1 474240146802
eu-north-1 394634713161
ap-northeast-1 969236854626
ap-northeast-2 020402002396
ap-southeast-1 195145609632
ap-southeast-2 798376113853
ap-south-1 507069717855
ap-east-1 174803364771
sa-east-1 287228555773
me-south-1 855739686837
As an API developer, you decide how API Gateway responds to a mock integration request. For this, you
configure the method's integration request and integration response to associate a response with a given
status code. For a method with the mock integration to return a 200 response, configure the integration
request body mapping template to return the following.
{"statusCode": 200}
Configure a 200 integration response to have the following body mapping template, for example:
{
"statusCode": 200,
"message": "Go ahead without me."
}
361
Amazon API Gateway Developer Guide
Integrations
Similarly, for the method to return, for example, a 500 error response, set up the integration request
body mapping template to return the following.
{"statusCode": 500}
Set up a 500 integration response with, for example, the following mapping template:
{
"statusCode": 500,
"message": "The invoked method is not supported on the API resource."
}
Alternatively, you can have a method of the mock integration return the default integration response
without defining the integration request mapping template. The default integration response is the one
with an undefined HTTP status regex. Make sure appropriate passthrough behaviors are set.
Note
Mock integrations aren't intended to support large response templates. If you need them for
your use case, you should consider using a Lambda integration instead.
Using an integration request mapping template, you can inject application logic to decide which mock
integration response to return based on certain conditions. For example, you could use a scope query
parameter on the incoming request to determine whether to return a successful response or an error
response:
{
#if( $input.params('scope') == "internal" )
"statusCode": 200
#else
"statusCode": 500
#end
}
This way, the method of the mock integration lets internal calls to go through while rejecting other types
of calls with an error response.
In this section, we describe how to use the API Gateway console to enable the mock integration for an
API method.
Topics
• Enable mock integration using the API Gateway console (p. 362)
1. Choose an API resource and create a method. In the method Setup pane, choose Mock for
Integration type, and then choose Save.
2. Choose Method Request from Method Execution. Expand URL Query String Parameters. Choose
Add query string to add a scope query parameter. This determines if the caller is internal or
otherwise.
3. From Method Execution, choose Method Response.
4. Under HTTP Status, add 500.
5. Choose Integration Request from Method Execution. Expand Mapping Templates. Choose or add
an application/json mapping template. Enter the following in the template editor:
362
Amazon API Gateway Developer Guide
Integrations
{
#if( $input.params('scope') == "internal" )
"statusCode": 200
#else
"statusCode": 500
#end
}
Choose Save.
6. Choose Integration Response from Method Execution. Expand the 200 response and then the
Mapping Templates section. Choose or add an application/json mapping template and enter the
following response body mapping template in the template editor.
{
"statusCode": 200,
"message": "Go ahead without me"
}
Choose Save.
7. Choose Add integration response to add a 500 response. Enter 5\d{2} in HTTP status regex. For
Method response status, choose 500, and then choose Save.
8. Expand 5\d{2} and then expand Mapping Templates and choose Add mapping template. Enter
application/json for Content-Type and then choose the check mark icon to save the setting. In
the template editor, enter the following integration response body mapping template:
{
"statusCode": 500,
"message": "The invoked method is not supported on the API resource."
}
Choose Save.
9. Choose Test from Method Execution. Do the following:
a. Enter scope=internal under Query Strings. Choose Test. The test result shows:
Request: /?scope=internal
Status: 200
Latency: 26 ms
Response Body
{
"statusCode": 200,
"message": "Go ahead without me"
}
Response Headers
{"Content-Type":"application/json"}
b. Enter scope=public under Query Strings or leave it blank. Choose Test. The test result
shows:
Request: /
Status: 500
363
Amazon API Gateway Developer Guide
Request validation
Latency: 16 ms
Response Body
{
"statusCode": 500,
"message": "The invoked method is not supported on the API resource."
}
Response Headers
{"Content-Type":"application/json"}
You can also return headers in a mock integration response by first adding a header to the method
response and then setting up a header mapping in the integration response. In fact, this is how the API
Gateway console enables CORS support by returning CORS required headers.
Topics
• Overview of basic request validation in API Gateway (p. 364)
• Set up basic request validation in API Gateway (p. 365)
• Test basic request validation in API Gateway (p. 370)
• OpenAPI definitions of a sample API with basic request validation (p. 373)
• The required request parameters in the URI, query string, and headers of an incoming request are
included and non-blank.
• The applicable request payload adheres to the configured JSON schema request model (p. 383) of
the method.
To enable basic validation, you specify validation rules in a request validator, add the validator to the
API's map of request validators, and assign the validator to individual API methods.
Note
Request body validation and request body passthrough (p. 409) are two separate issues. When
a request payload cannot be validated because no model schema can be matched, you can
choose to passthrough or block the original payload.
For example, when you enable request validation with a mapping template for the
application/json media type, you might want to pass an XML payload through to the
backend even though the enabled request validation will fail. This might be the case if you
expect to support the XML payload on the method in the future. To fail the request with an XML
payload, you must explicitly choose the NEVER option for the content passthrough behavior.
364
Amazon API Gateway Developer Guide
Request validation
Topics
• Set up basic request validation by importing OpenAPI definition (p. 365)
• Set up request validators using the API Gateway REST API (p. 368)
• Set up basic request validation using the API Gateway console (p. 369)
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"title": "ReqValidation Sample",
"version": "1.0.0"
},
"servers": [
{
"url": "/{basePath}",
"variables": {
"basePath": {
"default": "/v1"
}
}
}
],
"x-amazon-apigateway-request-validators": {
"all": {
"validateRequestBody": true,
"validateRequestParameters": true
},
"params-only": {
"validateRequestBody": false,
"validateRequestParameters": true
}
}
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"title": "ReqValidation Sample",
365
Amazon API Gateway Developer Guide
Request validation
"version": "1.0.0"
},
"schemes": [
"https"
],
"basePath": "/v1",
"produces": [
"application/json"
],
"x-amazon-apigateway-request-validators" : {
"all" : {
"validateRequestBody" : true,
"validateRequestParameters" : true
},
"params-only" : {
"validateRequestBody" : false,
"validateRequestParameters" : true
}
},
...
}
You select a validator's name when enabling the validator on the API or on a method, as shown in
the next step.
2. To enable a request validator on all methods of an API, specify an x-amazon-apigateway-request-
validator property (p. 774) property at the API level of the OpenAPI definition file. To enable
a request validator on an individual method, specify the x-amazon-apigateway-request-
validator property at the method level. For example, the following x-amazon-apigateway-
request-validator property enables the params-only validator on all API methods, unless
otherwise overridden.
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"title": "ReqValidation Sample",
"version": "1.0.0"
},
"servers": [
{
"url": "/{basePath}",
"variables": {
"basePath": {
"default": "/v1"
}
}
}
],
"x-amazon-apigateway-request-validator": "params-only",
...
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"title": "ReqValidation Sample",
"version": "1.0.0"
},
366
Amazon API Gateway Developer Guide
Request validation
"schemes": [
"https"
],
"basePath": "/v1",
"produces": [
"application/json"
],
...
"x-amazon-apigateway-request-validator" : "params-only",
...
}
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"title": "ReqValidation Sample",
"version": "1.0.0"
},
"servers": [
{
"url": "/{basePath}",
"variables": {
"basePath": {
"default": "/v1"
}
}
}
],
"paths": {
"/validation": {
"post": {
"x-amazon-apigateway-request-validator": "all",
...
}
}
}
...
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"title": "ReqValidation Sample",
"version": "1.0.0"
},
"schemes": [
"https"
],
"basePath": "/v1",
"produces": [
"application/json"
],
...
367
Amazon API Gateway Developer Guide
Request validation
"paths": {
"/validation": {
"post": {
"x-amazon-apigateway-request-validator" : "all",
...
},
...
}
}
...
}
3. In API Gateway, create the API with request validators enabled by importing this sample OpenAPI
definition (p. 373):
Copy the JSON object from this sample OpenAPI definition (p. 373) and paste it here.
{
"stageName" : "testStage",
"stageDescription" : "Test stage",
"description" : "First deployment",
"cacheClusterEnabled" : "false"
}
For instructions on how to test the request validation using the API Gateway REST API, see Test basic
request validation using the API Gateway REST API (p. 370). For instructions on how to test using the
API Gateway console, see Test basic request validation using the API Gateway console (p. 373).
To enable the basic request validation using the API Gateway REST API
We assume that you have an API similar to the sample API (p. 373), but have not set up the
request validators. If your API already has request validators enabled, call the appropriate
requestvalidator:update or method:put action instead of requestvalidator:create or
method:put.
368
Amazon API Gateway Developer Guide
Request validation
1. To set up the params-only request validator, call the requestvalidator:create action as follows:
{
"name" : "params-only",
"validateRequestBody" : "false",
"validateRequestParameters" : "true"
}
2. To set up the all request validator, call the requestvalidator:create action as follows:
{
"name" : "all",
"validateRequestBody" : "true",
"validateRequestParameters" : "true"
}
If the preceding validator keys already exist in the RequestValidators map, call the
requestvalidator:update action instead to reset the validation rules.
3. To apply the all request validator to the POST method, call method:put to enable the specified
validator (as identified by the requestValidatorId property), or call method:update to update the
enabled validator.
{
"authorizationType" : "NONE",
...,
"requestValidatorId" : "all"
}
369
Amazon API Gateway Developer Guide
Request validation
When you choose one of the above validators to enable it on an API method, the API Gateway console
adds the validator to the API's RequestValidators map if the validator has not already been added to the
validators map of the API.
1. Sign in to the API Gateway console if you're not already logged in.
2. Create a new or choose an existing API.
3. Create a new or choose an existing resource of the API.
4. Create a new or choose an existing method the resource.
5. Choose Method Request.
6. Choose the pencil icon of Request Validator under Settings.
7. Choose Validate body, Validate query string parameters and headers, or Validate
body, query string parameters, and headers from the Request Validator drop-down list.
Then choose the check mark icon to save your choice.
To test and use the request validator in the console, follow the instructions in Test basic request
validation using the API Gateway console (p. 373).
Topics
• Test basic request validation using the API Gateway REST API (p. 370)
• Test basic request validation using the API Gateway console (p. 373)
Test basic request validation using the API Gateway REST API
To see the invocation URL of the deployed API, you can export the API from the stage, making sure to
include the Accept: application/json or Accept: application/yaml header:
370
Amazon API Gateway Developer Guide
Request validation
Host: apigateway.us-east-1.amazonaws.com
X-Amz-Date: 20170306T234936Z
Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20170306/us-east-1/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature={sig4_hash}
You can ignore the ?extensions=validators query parameter if you don't want to download the
OpenAPI specifications related to the request validation.
To test request validation using the API Gateway REST API calls
Because the required parameter of q1 is set and not blank, the request passes the validation. API
Gateway returns the following 200 OK response:
[
{
"id": 1,
"type": "cat",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "cat",
"price": 0.99
}
]
Because the required parameter of q1 is not set, the request fails to pass the validation. API Gateway
returns the following 400 Bad Request response:
{
"message": "Missing required request parameters: [q1]"
}
371
Amazon API Gateway Developer Guide
Request validation
Because the required parameter of q1 is blank, the request fails to pass the validation. API Gateway
returns the same 400 Bad Request response as in the previous example.
4. Call POST /validation.
{
"name" : "Marco",
"type" : "dog",
"price" : 260
}
Because the required header parameter of h1 is set (and not blank) and the payload format adheres
to the RequestDataModel required properties and associated constraints, the request passes the
validation. API Gateway returns the following successful response.
{
"pet": {
"name": "Marco",
"type": "dog",
"price": 260
},
"message": "success"
}
5. Call POST /validation, without specifying the h1 header or setting its value blank.
{
"name" : "Marco",
"type" : "dog",
"price" : 260
}
Because the required header parameter of h1 is missing or set to blank, the request fails to pass the
validation. API Gateway returns the following 400 Bad Request response:
{
"message": "Missing required request parameters: [h1]"
}
6. Call POST /validation, setting the type property of the payload to bird.
372
Amazon API Gateway Developer Guide
Request validation
"name" : "Molly",
"type" : "bird",
"price" : 269
}
Because the type property value is not a member of the enumeration of ["dog", "cat",
"fish"], the request fails to pass the validation. API Gateway returns the following 400 Bad
Request response:
{
"message": "Invalid request body"
}
Setting price to 501 violates the constraint on the property. This causes the validation to fail and
the same 400 Bad Request response is returned.
To test the request validation on a method using TestInvoke in the API Gateway console
1. Choose Resources for the API that you've configured a request validators map for.
2. Choose a method for which you have enabled the request validation with a specified request
validator.
3. Under Method Execution, in the Client box, choose Test.
4. Try different values for required request parameter or applicable body, and then choose Test to see
the response.
When the method call passes validation, you should get expected responses. If validation fails, the
following error message returns if the payload is not the correct format:
{
"message": "Invalid request body"
}
If the request parameters aren't valid, the following error message returns:
{
"message": "Missing required request parameters: [p1]"
}
373
Amazon API Gateway Developer Guide
Request validation
blank in the incoming request. The all validator is enabled on the POST method. This validator verifies
that the required header parameter (h1) is set and not blank. It also verifies that the payload format
adheres to the specified RequestBodyModel schema.
This model requires that the input JSON object contains the name, type, and price properties. The
name property can be any string, type must be one of the specified enumeration fields (["dog",
"cat", "fish"]), and price must range between 25 and 500. The id parameter is not required.
For more information about the behavior of this API, see Enable request validation in API
Gateway (p. 364).
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"title": "ReqValidators Sample",
"version": "1.0.0"
},
"schemes": [
"https"
],
"basePath": "/v1",
"produces": [
"application/json"
],
"x-amazon-apigateway-request-validators" : {
"all" : {
"validateRequestBody" : true,
"validateRequestParameters" : true
},
"params-only" : {
"validateRequestBody" : false,
"validateRequestParameters" : true
}
},
"x-amazon-apigateway-request-validator" : "params-only",
"paths": {
"/validation": {
"post": {
"x-amazon-apigateway-request-validator" : "all",
"parameters": [
{
"in": "header",
"name": "h1",
"required": true
},
{
"in": "body",
"name": "RequestBodyModel",
"required": true,
"schema": {
"$ref": "#/definitions/RequestBodyModel"
}
}
],
"responses": {
"200": {
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Error"
}
},
374
Amazon API Gateway Developer Guide
Request validation
"headers" : {
"test-method-response-header" : {
"type" : "string"
}
}
}
},
"security" : [{
"api_key" : []
}],
"x-amazon-apigateway-auth" : {
"type" : "none"
},
"x-amazon-apigateway-integration" : {
"type" : "http",
"uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"httpMethod" : "POST",
"requestParameters": {
"integration.request.header.custom_h1": "method.request.header.h1"
},
"responses" : {
"2\\d{2}" : {
"statusCode" : "200"
},
"default" : {
"statusCode" : "400",
"responseParameters" : {
"method.response.header.test-method-response-header" : "'static value'"
},
"responseTemplates" : {
"application/json" : "json 400 response template",
"application/xml" : "xml 400 response template"
}
}
}
}
},
"get": {
"parameters": [
{
"name": "q1",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Error"
}
},
"headers" : {
"test-method-response-header" : {
"type" : "string"
}
}
}
},
"security" : [{
"api_key" : []
}],
"x-amazon-apigateway-auth" : {
"type" : "none"
},
375
Amazon API Gateway Developer Guide
Data transformations
"x-amazon-apigateway-integration" : {
"type" : "http",
"uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"httpMethod" : "GET",
"requestParameters": {
"integration.request.querystring.type": "method.request.querystring.q1"
},
"responses" : {
"2\\d{2}" : {
"statusCode" : "200"
},
"default" : {
"statusCode" : "400",
"responseParameters" : {
"method.response.header.test-method-response-header" : "'static value'"
},
"responseTemplates" : {
"application/json" : "json 400 response template",
"application/xml" : "xml 400 response template"
}
}
}
}
}
}
},
"definitions": {
"RequestBodyModel": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"type": { "type": "string", "enum": ["dog", "cat", "fish"] },
"name": { "type": "string" },
"price": { "type": "number", "minimum": 25, "maximum": 500 }
},
"required": ["type", "name", "price"]
},
"Error": {
"type": "object",
"properties": {
}
}
}
}
A mapping template is a script expressed in Velocity Template Language (VTL) and applied to the
payload using JSONPath expressions.
The payload can have a data model according to the JSON schema draft 4. You must define the model
in order to have API Gateway to generate a SDK or to enable basic request validation for your API. You
don't have to define any model to create a mapping template. However, a model can help you create a
template because API Gateway will generate a template blueprint based on a provided model.
376
Amazon API Gateway Developer Guide
Data transformations
This section explains how to map the API request and response payload using models and mapping
templates.
Topics
• Working with models and mapping templates (p. 377)
• Set up request and response data mappings using the API Gateway console (p. 387)
• Models and mapping template examples (p. 390)
• Amazon API Gateway API request and response data mapping reference (p. 405)
• API Gateway mapping template and access logging variable reference (p. 410)
A mapping template is a script expressed in Velocity Template Language (VTL) and applied to the
payload using JSONPath expressions.
The payload can have a data model according to the JSON schema draft 4. You must define the model
in order to have API Gateway to generate a SDK or to enable basic request validation for your API. You
don't have to define any model to create a mapping template. However, a model can help you create a
template because API Gateway will generate a template blueprint based on a provided model.
Topics
• Models (p. 377)
• Mapping templates (p. 380)
• Create a model in API Gateway (p. 383)
• Use a mapping template to override an API's request and response parameters and status
codes (p. 383)
Models
In API Gateway, a model defines the data structure of a payload. In API Gateway models are defined
using the JSON schema draft 4.
The following JSON object describes sample data that describes the fruit or vegetable inventory in the
produce department of a likely supermarket.
Suppose we have an API for managing fruit and vegetable inventory in the produce department of a
supermarket. When a manager queries the backend for the current inventory, the server sends back the
following response payload:
{
"department": "produce",
"categories": [
"fruit",
"vegetables"
],
"bins": [
{
"category": "fruit",
377
Amazon API Gateway Developer Guide
Data transformations
"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
}
]
}
We can use the following JSON schema to define the model for the preceding data:
{
"$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": {
"type": "object",
"properties": {
"category": { "type": "string" },
"type": { "type": "string" },
"price": { "type": "number" },
"unit": { "type": "string" },
"quantity": { "type": "integer" }
}
}
}
}
}
• The $schema object represents a valid JSON Schema version identifier. In this example, it refers to
JSON Schema, draft v4.
378
Amazon API Gateway Developer Guide
Data transformations
• The title object is a human-readable identifier for the model. In this example, it is
GroceryStoreInputModel.
• The top-level, or root, construct in the JSON data is an object.
• The root object in the JSON data contains department, categories, and bins properties.
• The department property is a string object in the JSON data.
• The categories property is an array in the JSON data. The array contains string values in the JSON
data.
• The bins property is an array in the JSON data. The array contains objects in the JSON data. Each of
these objects in the JSON data contains a category string, a type string, a price number, a unit
string, and a quantity integer (a number without a fraction or exponent part).
Alternatively, you could include part of this schema (for example, the item definition of the bins array)
in a separate section of the same file, and use the $ref primitive to reference this reusable definition in
other parts of the schema. Using $ref, the preceding model definition file can be expressed as follows:
{
"$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": "#/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,
suppose you have the following full-fledged model named Bin that is created under an API with an
identifier of fugvjdxtri:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "GroceryStoreInputModel",
379
Amazon API Gateway Developer Guide
Data transformations
"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 follows:
{
"$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/Bin"
}
}
}
}
The referencing and referenced models must be from the same API.
The examples don't use advanced JSON schema features, such as specifying required items, minimums
and maximums (for allowed string lengths, numeric values, and array item lengths), and regular
expressions. For more information, see Introducing JSON and JSON schema draft 4.
For more complex JSON data formats and their models, see the following examples:
• Input model (photos example) (p. 391) and Output model (photos example) (p. 392) in the Photos
example (p. 390)
• Input model (news article example) (p. 394) and Output model (news article example) (p. 396) in
the News article example (p. 393)
• Input model (sales invoice example) (p. 397) and Output model (sales invoice example) (p. 400) in
the Sales invoice example (p. 396)
• Input model (employee record example) (p. 401) and Output model (employee record
example) (p. 404) in the Employee record example (p. 401)
To experiment with models in API Gateway, follow the instructions in Map response payload (p. 76),
specifically Step 1: Create models (p. 77).
Mapping templates
When the backend returns the query results (shown in the Models (p. 377) section), the manager of the
produce department might be interested in reading them, as follows:
380
Amazon API Gateway Developer Guide
Data transformations
{
"choices": [
{
"kind": "apples",
"suggestedPrice": "1.99 per pound",
"available": 232
},
{
"kind": "bananas",
"suggestedPrice": "0.19 per each",
"available": 112
},
{
"kind": "carrots",
"suggestedPrice": "1.29 per bag",
"available": 57
}
]
}
To enable this, we need to provide API Gateway with a mapping template to translate the data from the
backend format. The following mapping template does that.
#set($inputRoot = $input.path('$'))
{
"choices": [
#foreach($elem in $inputRoot.bins)
{
"kind": "$elem.type",
"suggestedPrice": "$elem.price per $elem.unit",
"available": $elem.quantity
}#if($foreach.hasNext),#end
#end
]
}
Let us now examine some details of the preceding output mapping template:
• The $inputRoot variable represents the root object in the original JSON data from the previous
section. The variables in an output mapping template map to the original JSON data, not the desired
transformed JSON data schema.
• The choices array in the output mapping template is mapped from the bins array with the root
object in the original JSON data ($inputRoot.bins).
• In the output mapping template, each of the objects in the choices array (represented by $elem) are
mapped from the corresponding objects in the bins array within the root object in the original JSON
data.
• In the output mapping template, for each of objects in the choices object, the values of the kind
and available objects (represented by $elem.type and $elem.quantity) are mapped from the
corresponding values of the type and value objects in each of the objects in the original JSON data's
bins array, respectively.
• In the output mapping template, for each of objects in the choices object, the value of the
suggestedPrice object is a concatenation of the corresponding value of the price and unit
objects in each of the objects in the original JSON data, respectively, with each value separated by the
word per.
For more information about the Velocity Template Language, see Apache Velocity - VTL Reference. For
more information about JSONPath, see JSONPath - XPath for JSON.
381
Amazon API Gateway Developer Guide
Data transformations
The mapping template assumes that the underlying data is of a JSON object. It does not require that a
model be defined for the data. As an API developer, you know the data formats at both the front and
backends. That knowledge can guide you to define the necessary mappings without ambiguity.
To have an SDK generated for the API, the preceding data is returned as a language-specific object. For
strongly typed languages, such as Java, Objective-C, or Swift, the object corresponds to a user-defined
data type (UDT). API Gateway creates such a UDT if you provide it with a data model. For the preceding
method response example, you can define the following payload model in the integration response:
{
"$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" }
}
}
}
}
}
• The $schema object represents a valid JSON schema version identifier. In this example, it refers to
JSON schema, draft v4.
• The title object is a human-readable identifier for the model. In this example, it is
GroceryStoreOutputModel.
• The top-level, or root, construct in the JSON data is an object.
• The root object in the JSON data contains an array of objects.
• Each object in the array of objects contains a kind string, a suggestedPrice string, and an
available integer (a number without a fraction or exponent part).
With this model, you can call an SDK to retrieve the kind, suggestedPrice, and
available property values by reading the GroceryStoreOutputModel[i].kind,
GroceryStoreOutputModel[i].suggestedPrice, and
GroceryStoreOutputModel[i].available properties, respectively. If no model is provided, API
Gateway uses the empty model to create a default UDT. In this case, you aren't able to read these
properties using a strongly-typed SDK.
• Input mapping template (photos example) (p. 392) and Output mapping template (photos
example) (p. 393) in the Photos example (p. 390)
• Input mapping template (news article example) (p. 395) and Output mapping template (news article
example) (p. 396) in the News article example (p. 393)
• Input mapping template (sales invoice example) (p. 398) and Output mapping template (sales invoice
example) (p. 400) in the Sales invoice example (p. 396)
• Input mapping template (employee record example) (p. 402) and Output mapping template
(employee record example) (p. 405) in the Employee record example (p. 401)
382
Amazon API Gateway Developer Guide
Data transformations
To experiment with mapping templates in API Gateway, follow the instructions in Map response
payload (p. 76), specifically Step 5: Set up and test the methods (p. 82).
Topics
• Prerequisites (p. 383)
• Create a model with the API Gateway console (p. 383)
Prerequisites
• You must have an API available in API Gateway. Follow the instructions in Creating a REST API in
Amazon API Gateway (p. 242).
• To create a new header (or overwrite an existing header) as a concatenation of two parameters
• To override the response code to a success or failure code based on the contents of the body
• To conditionally remap a parameter based on its contents or the contents of some other parameter
• To iterate over the contents of a json body and remap key value pairs to headers or query strings
To create a mapping template override, use one or more of the following $context variables (p. 410)
in a mapping template (p. 377):
383
Amazon API Gateway Developer Guide
Data transformations
$context.requestOverride.header.header_name
$context.responseOverride.header.header_name
$context.requestOverride.path.path_name $context.responseOverride.status
$context.requestOverride.querystring.querystring_name
Note
Mapping template overrides cannot be used with proxy integration endpoints, which lack data
mappings. For more information about integration types, see Choose an API Gateway API
integration type (p. 326).
Important
Overrides are final. An override may only be applied to each parameter once. Trying to override
the same parameter multiple times will result in 5XX responses from Amazon API Gateway. If
you must override the same parameter multiple times throughout the template, we recommend
creating a variable and applying the override at the end of the template. Note that the template
is applied only after the entire template is parsed. See Tutorial: Override an API's request
parameters and headers with the API Gateway console (p. 385).
The following tutorials show how to create and test a mapping template override in the API Gateway
console. These tutorials use the PetStore sample API (p. 46) as a starting point. Both tutorials assume
that you have already created the PetStore sample API (p. 46).
Topics
• Tutorial: Override an API's response status code with the API Gateway console (p. 384)
• Tutorial: Override an API's request parameters and headers with the API Gateway console (p. 385)
• Examples: Override an API's request parameters and headers with the API Gateway CLI (p. 386)
• Example: Override an API's request parameters and headers using the SDK for JavaScript (p. 387)
Tutorial: Override an API's response status code with the API Gateway console
To retrieve a pet using the PetStore sample API, you use the API method request of GET /pets/
{petId}, where {petId} is a path parameter that can take a number at run time.
In this tutorial, you'll override this GET method's response code by creating a mapping template that
maps $context.responseOverride.status to 400 when an error condition is detected.
{
"errors": [
{
"key": "GetPetRequest.petId",
"message": "The value is out of range."
}
384
Amazon API Gateway Developer Guide
Data transformations
]
}
Second, the last line under Logs box ends with: Method completed with status: 200.
6. Go back to Method Execution. Choose Integration Response, and then choose the arrow next to
200.
7. In the Mapping Templates section, choose Add mapping template.
8. For Content Type, type application/json, and then choose the check mark icon to save the
choice.
9. Copy the following code into the template area:
#set($inputRoot = $input.path('$'))
$input.json("$")
#if($inputRoot.toString().contains("error"))
#set($context.responseOverride.status = 400)
#end
{
"errors": [
{
"key": "GetPetRequest.petId",
"message": "The value is out of range."
}
]
}
However, the last line under Logs box now ends with: Method completed with status: 400.
Tutorial: Override an API's request parameters and headers with the API Gateway console
In this tutorial, you'll override the GET method's request header code by creating a mapping template
that maps $context.requestOverride.header.header_name to a new header that combines two
other headers.
385
Amazon API Gateway Developer Guide
Data transformations
#set($header1Override = "foo")
#set($header3Value = "$input.params('header1')$input.params('header2')")
$input.json("$")
#set($context.requestOverride.header.header3 = $header3Value)
#set($context.requestOverride.header.header1 = $header1Override)
#set($context.requestOverride.header.multivalueheader=[$header1Override,
$header3Value])
header1:header1Val
header2:header2Val
In the Logs, you should see an entry that includes this text:
Examples: Override an API's request parameters and headers with the API Gateway CLI
The following CLI example shows how to use the put-integration command to override a response
code:
where <REQUEST_TEMPLATE_MAP> is a map from content type to a string of the template to apply. The
structure of that map is as follows:
Content_type1=template_string,Content_type2=template_string
{"content_type1": "template_string"
386
Amazon API Gateway Developer Guide
Data transformations
...}
The following example shows how to use the put-integration-response command to override an
API's response code:
Example: Override an API's request parameters and headers using the SDK for JavaScript
The following example shows how to use the put-integration command to override a response code:
Request:
var params = {
httpMethod: 'STRING_VALUE', /* required */
resourceId: 'STRING_VALUE', /* required */
restApiId: 'STRING_VALUE', /* required */
type: HTTP | AWS | MOCK | HTTP_PROXY | AWS_PROXY, /* required */
requestTemplates: {
'<Content_type>': 'TEMPLATE_STRING',
/* '<String>': ... */
},
};
apigateway.putIntegration(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Response:
var params = {
httpMethod: 'STRING_VALUE', /* required */
resourceId: 'STRING_VALUE', /* required */
restApiId: 'STRING_VALUE', /* required */
statusCode: 'STRING_VALUE', /* required */
responseTemplates: {
'<Content_type>': 'TEMPLATE_STRING',
/* '<String>': ... */
},
};
apigateway.putIntegrationResponse(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
387
Amazon API Gateway Developer Guide
Data transformations
1. With the method selected in the Resources pane, in the Method Execution pane, choose
Integration Request.
2. 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 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:
Alternatively, you can set a literal string value (enclosed by a pair of single quotes) to an
integration header.
• method.request.multivalueheader.parameter-name for a multi-valued header
parameter named parameter-name as defined in the Method Request page.
d. 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.)
3. In the 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 backend 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 backend 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
388
Amazon API Gateway Developer Guide
Data transformations
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. 409).
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 Working with
models and mapping templates (p. 377).
5. You can map an integration response from the backend 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 backend, transforming the data format of the backend 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
API Gateway uses Java pattern-style regexes for response mapping. For more
information, see Pattern in the Oracle documentation.
The error patterns are matched against the entire string of the errorMessage
property in the Lambda response, which is populated by callback(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 one
of the following formats:
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 a Timestamp entry, and the
associated Mapping value should be set to integration.response.multivalueheaders.Date.
389
Amazon API Gateway Developer Guide
Data transformations
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 a 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.
Topics
• Photos example (API Gateway models and mapping templates) (p. 390)
• News article example (API Gateway models and mapping templates) (p. 393)
• Sales invoice example (API Gateway models and mapping templates) (p. 396)
• Employee record example (API Gateway models and mapping templates) (p. 401)
Topics
• Original data (photos example) (p. 390)
• Input model (photos example) (p. 391)
• Input mapping template (photos example) (p. 392)
• Transformed data (photos example) (p. 392)
• Output model (photos example) (p. 392)
• Output mapping template (photos example) (p. 393)
The following is the original JSON data for the photos example:
{
"photos": {
"page": 1,
"pages": "1234",
"perpage": 100,
390
Amazon API Gateway Developer Guide
Data transformations
"total": "123398",
"photo": [
{
"id": "12345678901",
"owner": "23456789@A12",
"secret": "abc123d456",
"server": "1234",
"farm": 1,
"title": "Sample photo 1",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
{
"id": "23456789012",
"owner": "34567890@B23",
"secret": "bcd234e567",
"server": "2345",
"farm": 2,
"title": "Sample photo 2",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
}
}
The following is the input model that corresponds to the original JSON data for the photos example:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PhotosInputModel",
"type": "object",
"properties": {
"photos": {
"type": "object",
"properties": {
"page": { "type": "integer" },
"pages": { "type": "string" },
"perpage": { "type": "integer" },
"total": { "type": "string" },
"photo": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "string" },
"owner": { "type": "string" },
"secret": { "type": "string" },
"server": { "type": "string" },
"farm": { "type": "integer" },
"title": { "type": "string" },
"ispublic": { "type": "integer" },
"isfriend": { "type": "integer" },
"isfamily": { "type": "integer" }
}
}
}
}
}
}
391
Amazon API Gateway Developer Guide
Data transformations
The following is the input mapping template that corresponds to the original JSON data for the photos
example:
#set($inputRoot = $input.path('$'))
{
"photos": {
"page": $inputRoot.photos.page,
"pages": "$inputRoot.photos.pages",
"perpage": $inputRoot.photos.perpage,
"total": "$inputRoot.photos.total",
"photo": [
#foreach($elem in $inputRoot.photos.photo)
{
"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
]
}
}
The following is one example of how the original photos example JSON data could be transformed for
output:
{
"photos": [
{
"id": "12345678901",
"owner": "23456789@A12",
"title": "Sample photo 1",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
{
"id": "23456789012",
"owner": "34567890@B23",
"title": "Sample photo 2",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
}
The following is the output model that corresponds to the transformed JSON data format:
392
Amazon API Gateway Developer Guide
Data transformations
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PhotosOutputModel",
"type": "object",
"properties": {
"photos": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "string" },
"owner": { "type": "string" },
"title": { "type": "string" },
"ispublic": { "type": "integer" },
"isfriend": { "type": "integer" },
"isfamily": { "type": "integer" }
}
}
}
}
}
The following is the output mapping template that corresponds to the transformed JSON data format.
The template variables here are based on the original, not transformed, JSON data format:
#set($inputRoot = $input.path('$'))
{
"photos": [
#foreach($elem in $inputRoot.photos.photo)
{
"id": "$elem.id",
"owner": "$elem.owner",
"title": "$elem.title",
"ispublic": $elem.ispublic,
"isfriend": $elem.isfriend,
"isfamily": $elem.isfamily
}#if($foreach.hasNext),#end
#end
]
}
Topics
• Original data (news article example) (p. 394)
• Input model (news article example) (p. 394)
• Input mapping template (news article example) (p. 395)
• Transformed data (news article example) (p. 395)
• Output model (news article example) (p. 396)
• Output mapping template (news article example) (p. 396)
393
Amazon API Gateway Developer Guide
Data transformations
The following is the original JSON data for the news article example:
{
"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
}
The following is the input model that corresponds to the original JSON data for the news article
example:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "NewsArticleInputModel",
"type": "object",
"properties": {
"count": { "type": "integer" },
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"last_updated_date": { "type": "string" },
"expire_date": { "type": "string" },
"author_first_name": { "type": "string" },
"description": { "type": "string" },
"creation_date": { "type": "string" },
"title": { "type": "string" },
"allow_comment": { "type": "string" },
"author": {
"type": "object",
"properties": {
"last_name": { "type": "string" },
"email": { "type": "string" },
"first_name": { "type": "string" }
}
},
"body": { "type": "string" },
394
Amazon API Gateway Developer Guide
Data transformations
The following is the input mapping template that corresponds to the original JSON data for the news
article example:
#set($inputRoot = $input.path('$'))
{
"count": $inputRoot.count,
"items": [
#foreach($elem in $inputRoot.items)
{
"last_updated_date": "$elem.last_updated_date",
"expire_date": "$elem.expire_date",
"author_first_name": "$elem.author_first_name",
"description": "$elem.description",
"creation_date": "$elem.creation_date",
"title": "$elem.title",
"allow_comment": "$elem.allow_comment",
"author": {
"last_name": "$elem.author.last_name",
"email": "$elem.author.email",
"first_name": "$elem.author.first_name"
},
"body": "$elem.body",
"publish_date": "$elem.publish_date",
"version": "$elem.version",
"author_last_name": "$elem.author_last_name",
"parent_id": $elem.parent_id,
"article_url": "$elem.article_url"
}#if($foreach.hasNext),#end
#end
],
"version": $inputRoot.version
}
The following is one example of how the original news article example JSON data could be transformed
for output:
{
"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"
395
Amazon API Gateway Developer Guide
Data transformations
}
],
"version": 1
}
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "NewsArticleOutputModel",
"type": "object",
"properties": {
"count": { "type": "integer" },
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"creation_date": { "type": "string" },
"title": { "type": "string" },
"author": { "type": "string" },
"body": { "type": "string" },
"publish_date": { "type": "string" },
"article_url": { "type": "string" }
}
}
},
"version": { "type": "integer" }
}
}
#set($inputRoot = $input.path('$'))
{
"count": $inputRoot.count,
"items": [
#foreach($elem in $inputRoot.items)
{
"creation_date": "$elem.creation_date",
"title": "$elem.title",
"author": "$elem.author.first_name $elem.author.last_name",
"body": "$elem.body",
"publish_date": "$elem.publish_date",
"article_url": "$elem.article_url"
}#if($foreach.hasNext),#end
#end
],
"version": $inputRoot.version
}
396
Amazon API Gateway Developer Guide
Data transformations
Topics
• Original data (sales invoice example) (p. 397)
• Input model (sales invoice example) (p. 397)
• Input mapping template (sales invoice example) (p. 398)
• Transformed data (sales invoice example) (p. 399)
• Output model (sales invoice example) (p. 400)
• Output mapping template (sales invoice example) (p. 400)
The following is the original JSON data for the sales invoice example:
{
"DueDate": "2013-02-15",
"Balance": 1990.19,
"DocNumber": "SAMP001",
"Status": "Payable",
"Line": [
{
"Description": "Sample Expense",
"Amount": 500,
"DetailType": "ExpenseDetail",
"ExpenseDetail": {
"Customer": {
"value": "ABC123",
"name": "Sample Customer"
},
"Ref": {
"value": "DEF234",
"name": "Sample Construction"
},
"Account": {
"value": "EFG345",
"name": "Fuel"
},
"LineStatus": "Billable"
}
}
],
"Vendor": {
"value": "GHI456",
"name": "Sample Bank"
},
"APRef": {
"value": "HIJ567",
"name": "Accounts Payable"
},
"TotalAmt": 1990.19
}
The following is the input model that corresponds to the original JSON data for the sales invoice
example:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "InvoiceInputModel",
"type": "object",
397
Amazon API Gateway Developer Guide
Data transformations
"properties": {
"DueDate": { "type": "string" },
"Balance": { "type": "number" },
"DocNumber": { "type": "string" },
"Status": { "type": "string" },
"Line": {
"type": "array",
"items": {
"type": "object",
"properties": {
"Description": { "type": "string" },
"Amount": { "type": "integer" },
"DetailType": { "type": "string" },
"ExpenseDetail": {
"type": "object",
"properties": {
"Customer": {
"type": "object",
"properties": {
"value": { "type": "string" },
"name": { "type": "string" }
}
},
"Ref": {
"type": "object",
"properties": {
"value": { "type": "string" },
"name": { "type": "string" }
}
},
"Account": {
"type": "object",
"properties": {
"value": { "type": "string" },
"name": { "type": "string" }
}
},
"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" }
}
}
398
Amazon API Gateway Developer Guide
Data transformations
#set($inputRoot = $input.path('$'))
{
"DueDate": "$inputRoot.DueDate",
"Balance": $inputRoot.Balance,
"DocNumber": "$inputRoot.DocNumber",
"Status": "$inputRoot.Status",
"Line": [
#foreach($elem in $inputRoot.Line)
{
"Description": "$elem.Description",
"Amount": $elem.Amount,
"DetailType": "$elem.DetailType",
"ExpenseDetail": {
"Customer": {
"value": "$elem.ExpenseDetail.Customer.value",
"name": "$elem.ExpenseDetail.Customer.name"
},
"Ref": {
"value": "$elem.ExpenseDetail.Ref.value",
"name": "$elem.ExpenseDetail.Ref.name"
},
"Account": {
"value": "$elem.ExpenseDetail.Account.value",
"name": "$elem.ExpenseDetail.Account.name"
},
"LineStatus": "$elem.ExpenseDetail.LineStatus"
}
}#if($foreach.hasNext),#end
#end
],
"Vendor": {
"value": "$inputRoot.Vendor.value",
"name": "$inputRoot.Vendor.name"
},
"APRef": {
"value": "$inputRoot.APRef.value",
"name": "$inputRoot.APRef.name"
},
"TotalAmt": $inputRoot.TotalAmt
}
{
"DueDate": "2013-02-15",
"Balance": 1990.19,
"DocNumber": "SAMP001",
"Status": "Payable",
"Line": [
{
"Description": "Sample Expense",
"Amount": 500,
"DetailType": "ExpenseDetail",
"Customer": "ABC123 (Sample Customer)",
"Ref": "DEF234 (Sample Construction)",
"Account": "EFG345 (Fuel)",
"LineStatus": "Billable"
}
],
"TotalAmt": 1990.19
399
Amazon API Gateway Developer Guide
Data transformations
The following is the output model that corresponds to the transformed JSON data format:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "InvoiceOutputModel",
"type": "object",
"properties": {
"DueDate": { "type": "string" },
"Balance": { "type": "number" },
"DocNumber": { "type": "string" },
"Status": { "type": "string" },
"Line": {
"type": "array",
"items": {
"type": "object",
"properties": {
"Description": { "type": "string" },
"Amount": { "type": "integer" },
"DetailType": { "type": "string" },
"Customer": { "type": "string" },
"Ref": { "type": "string" },
"Account": { "type": "string" },
"LineStatus": { "type": "string" }
}
}
},
"TotalAmt": { "type": "number" }
}
}
The following is the output mapping template that corresponds to the transformed JSON data format.
The template variables here are based on the original, not transformed, JSON data format:
#set($inputRoot = $input.path('$'))
{
"DueDate": "$inputRoot.DueDate",
"Balance": $inputRoot.Balance,
"DocNumber": "$inputRoot.DocNumber",
"Status": "$inputRoot.Status",
"Line": [
#foreach($elem in $inputRoot.Line)
{
"Description": "$elem.Description",
"Amount": $elem.Amount,
"DetailType": "$elem.DetailType",
"Customer": "$elem.ExpenseDetail.Customer.value ($elem.ExpenseDetail.Customer.name)",
"Ref": "$elem.ExpenseDetail.Ref.value ($elem.ExpenseDetail.Ref.name)",
"Account": "$elem.ExpenseDetail.Account.value ($elem.ExpenseDetail.Account.name)",
"LineStatus": "$elem.ExpenseDetail.LineStatus"
}#if($foreach.hasNext),#end
#end
],
"TotalAmt": $inputRoot.TotalAmt
}
400
Amazon API Gateway Developer Guide
Data transformations
Topics
• Original data (employee record example) (p. 401)
• Input model (employee record example) (p. 401)
• Input mapping template (employee record example) (p. 402)
• Transformed data (employee record example) (p. 403)
• Output model (employee record example) (p. 404)
• Output mapping template (employee record example) (p. 405)
{
"QueryResponse": {
"maxResults": "1",
"startPosition": "1",
"Employee": {
"Organization": "false",
"Title": "Mrs.",
"GivenName": "Jane",
"MiddleName": "Lane",
"FamilyName": "Doe",
"DisplayName": "Jane Lane Doe",
"PrintOnCheckName": "Jane Lane Doe",
"Active": "true",
"PrimaryPhone": { "FreeFormNumber": "505.555.9999" },
"PrimaryEmailAddr": { "Address": "[email protected]" },
"EmployeeType": "Regular",
"status": "Synchronized",
"Id": "ABC123",
"SyncToken": "1",
"MetaData": {
"CreateTime": "2015-04-26T19:45:03Z",
"LastUpdatedTime": "2015-04-27T21:48:23Z"
},
"PrimaryAddr": {
"Line1": "123 Any Street",
"City": "Any City",
"CountrySubDivisionCode": "WA",
"PostalCode": "01234"
}
}
},
"time": "2015-04-27T22:12:32.012Z"
}
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "EmployeeInputModel",
401
Amazon API Gateway Developer Guide
Data transformations
"type": "object",
"properties": {
"QueryResponse": {
"type": "object",
"properties": {
"maxResults": { "type": "string" },
"startPosition": { "type": "string" },
"Employee": {
"type": "object",
"properties": {
"Organization": { "type": "string" },
"Title": { "type": "string" },
"GivenName": { "type": "string" },
"MiddleName": { "type": "string" },
"FamilyName": { "type": "string" },
"DisplayName": { "type": "string" },
"PrintOnCheckName": { "type": "string" },
"Active": { "type": "string" },
"PrimaryPhone": {
"type": "object",
"properties": {
"FreeFormNumber": { "type": "string" }
}
},
"PrimaryEmailAddr": {
"type": "object",
"properties": {
"Address": { "type": "string" }
}
},
"EmployeeType": { "type": "string" },
"status": { "type": "string" },
"Id": { "type": "string" },
"SyncToken": { "type": "string" },
"MetaData": {
"type": "object",
"properties": {
"CreateTime": { "type": "string" },
"LastUpdatedTime": { "type": "string" }
}
},
"PrimaryAddr": {
"type": "object",
"properties": {
"Line1": { "type": "string" },
"City": { "type": "string" },
"CountrySubDivisionCode": { "type": "string" },
"PostalCode": { "type": "string" }
}
}
}
}
}
},
"time": { "type": "string" }
}
}
The following is the input mapping template that corresponds to the original JSON data for the
employee record example:
#set($inputRoot = $input.path('$'))
402
Amazon API Gateway Developer Guide
Data transformations
{
"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"
}
The following is one example of how the original employee record example JSON data could be
transformed for output:
{
"QueryResponse": {
"maxResults": "1",
"startPosition": "1",
"Employees": [
{
"Title": "Mrs.",
"GivenName": "Jane",
"MiddleName": "Lane",
"FamilyName": "Doe",
"DisplayName": "Jane Lane Doe",
"PrintOnCheckName": "Jane Lane Doe",
"Active": "true",
"PrimaryPhone": "505.555.9999",
"Email": [
{
"type": "primary",
"Address": "[email protected]"
}
],
"EmployeeType": "Regular",
"PrimaryAddr": {
403
Amazon API Gateway Developer Guide
Data transformations
The following is the output model that corresponds to the transformed JSON data format:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "EmployeeOutputModel",
"type": "object",
"properties": {
"QueryResponse": {
"type": "object",
"properties": {
"maxResults": { "type": "string" },
"startPosition": { "type": "string" },
"Employees": {
"type": "array",
"items": {
"type": "object",
"properties": {
"Title": { "type": "string" },
"GivenName": { "type": "string" },
"MiddleName": { "type": "string" },
"FamilyName": { "type": "string" },
"DisplayName": { "type": "string" },
"PrintOnCheckName": { "type": "string" },
"Active": { "type": "string" },
"PrimaryPhone": { "type": "string" },
"Email": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "type": "string" },
"Address": { "type": "string" }
}
}
},
"EmployeeType": { "type": "string" },
"PrimaryAddr": {
"type": "object",
"properties": {
"Line1": {"type": "string" },
"City": { "type": "string" },
"CountrySubDivisionCode": { "type": "string" },
"PostalCode": { "type": "string" }
}
}
}
}
}
}
},
"time": { "type": "string" }
404
Amazon API Gateway Developer Guide
Data transformations
}
}
The following is the output mapping template that corresponds to the transformed JSON data format.
The template variables here are based on the original, not transformed, JSON data format:
#set($inputRoot = $input.path('$'))
{
"QueryResponse": {
"maxResults": "$inputRoot.QueryResponse.maxResults",
"startPosition": "$inputRoot.QueryResponse.startPosition",
"Employees": [
{
"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": "$inputRoot.QueryResponse.Employee.PrimaryPhone.FreeFormNumber",
"Email" : [
{
"type": "primary",
"Address": "$inputRoot.QueryResponse.Employee.PrimaryEmailAddr.Address"
}
],
"EmployeeType": "$inputRoot.QueryResponse.Employee.EmployeeType",
"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"
}
Topics
• Map method request data to integration request parameters (p. 406)
• Map integration response data to method response headers (p. 407)
• Map request and response payloads between method and integration (p. 408)
• Integration passthrough behaviors (p. 409)
405
Amazon API Gateway Developer Guide
Data transformations
In the following table, PARAM_NAME is the name of a method request parameter of the given parameter
type. It must match the regular expression '^[a-zA-Z0-9._$-]+$]'. 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.
Note
The "$" prefix is omitted in this syntax.
• the method request's header, named methodRequestHeaderParam, into the integration request path
parameter, named integrationPathParam
• the multi-value method request query string, named methodRequestQueryParam, into the
integration request query string, named integrationQueryParam
...
"requestParameters" : {
"integration.request.path.integrationPathParam" :
"method.request.header.methodRequestHeaderParam",
"integration.request.querystring.integrationQueryParam" :
"method.request.multivaluequerystring.methodRequestQueryParam"
}
...
406
Amazon API Gateway Developer Guide
Data transformations
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",
}
...
...
"responseParameters" : {
407
Amazon API Gateway Developer Guide
Data transformations
"method.response.header.location" : "integration.response.body.redirect.url",
"method.response.header.id" : "integration.response.header.x-app-id",
"method.response.header.items" : "integration.response.multivalueheader.item",
}
...
The VTL templates use JSONPath expressions, other parameters such as calling contexts and stage
variables, and utility functions to process the JSON data.
If a model is defined to describe the data structure of a payload, API Gateway can use the model to
generate a skeletal mapping template for an integration request or integration response. You can use the
skeletal template as an aid to customize and expand the mapping VTL script. However, you can create a
mapping template from scratch without defining a model for the payload's data structure.
For a request payload, API Gateway uses the request’s Content-Type header value as the key to select
the mapping template for the request payload. For a response payload, API Gateway uses the incoming
request’s Accept header value as the key to select the mapping template.
When the Content-Type header is absent in the request, API Gateway assumes that its default value
is application/json. For such a request, API Gateway uses application/json as the default key
to select the mapping template, if one is defined. When no template matches this key, API Gateway
passes the payload through unmapped if the passthroughBehavior property is set to WHEN_NO_MATCH or
WHEN_NO_TEMPLATES.
When the Accept header is not specified in the request, API Gateway assumes that its default value is
application/json. In this case, API Gateway selects an existing mapping template for application/
json to map the response payload. If no template is defined for application/json, API Gateway
selects the first existing template and uses it as the default to map the response payload. Similarly,
API Gateway uses the first existing template when the specified Accept header value does not match
any existing template key. If no template is defined, API Gateway simply passes the response payload
through unmapped.
For example, suppose that an API has a application/json template defined for a request payload and
has a application/xml template defined for the response payload. If the client sets the "Content-
Type : application/json", and "Accept : application/xml" headers in the request, both
the request and response payloads will be processed with the corresponding mapping templates. If the
Accept:application/xml header is absent, the application/xml mapping template will be used
to map the response payload. To return the response payload unmapped instead, you must set up an
empty template for application/json.
Only the MIME type is used from the Accept and Content-Type headers when selecting a mapping
template. For example, a header of "Content-Type: application/json; charset=UTF-8" will
have a request template with the application/json key selected.
408
Amazon API Gateway Developer Guide
Data transformations
For proxy integrations (p. 327), API Gateway passes the entire request through to your backend, and
you do not have the option to modify the passthrough behaviors.
The actual passthrough behavior of an incoming request is determined by the option you choose for a
specified mapping template, during integration request set-up (p. 387), and the Content Type header
that a client set in the incoming request. The following examples illustrate the possible passthrough
behaviors.
Example 1: One mapping template is defined in the integration request for the application/json
content type.
None (default to The request payload is The request payload is The request payload is
application/json) transformed using the transformed using the transformed using the
template. template. template.
application/json The request payload is The request payload is The request payload is
transformed using the transformed using the transformed using the
template. template. template.
application/xml The request payload is The request is rejected The request is rejected
not transformed and is with an HTTP 415 with an HTTP 415
sent to the backend as- Unsupported Media Unsupported Media
is. Type response. Type response.
Example 2: One mapping template is defined in the integration request for the application/xml
content type.
None (default to The request payload is The request is rejected The request is rejected
application/json) not transformed and is with an HTTP 415 with an HTTP 415
sent to the backend as- Unsupported Media Unsupported Media
is. Type response. Type response.
application/json The request payload is The request is rejected The request is rejected
not transformed and is with an HTTP 415 with an HTTP 415
sent to the backend as- Unsupported Media Unsupported Media
is. Type response. Type response.
application/xml The request payload is The request payload is The request payload is
transformed using the transformed using the transformed using the
template. template. template.
409
Amazon API Gateway Developer Guide
Data transformations
Topics
• $context Variables for data models, authorizers, mapping templates, and CloudWatch access
logging (p. 410)
• $context Variable template example (p. 415)
• $context Variables for access logging only (p. 416)
• $input Variables (p. 417)
• $input Variable template examples (p. 418)
• $stageVariables (p. 420)
• $util Variables (p. 421)
Note
For $method and $integration variables, see the section called “Request and response data
mapping reference” (p. 405).
For $context variables that can be used only in CloudWatch access logging, see the section called
“$context Variables for access logging only” (p. 416).
Parameter Description
410
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
"context" : {
"key": "value",
"numKey": 1,
"boolKey": true
}
calling $context.authorizer.key
returns the "value" string, calling
$context.authorizer.numKey
returns the "1" string, and calling
$context.authorizer.boolKey returns the
"true" string.
$context.domainName The full domain name used to invoke the API. This
should be the same as the incoming Host header.
411
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
412
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
413
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
414
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
The following example shows a mapping template that maps incoming $context variables to backend
variables with slightly different names in an integration request payload:
Note
Note that one of the variables is an API key. This example assumes that the method has "require
API key" enabled.
{
"stage" : "$context.stage",
"request_id" : "$context.requestId",
"api_id" : "$context.apiId",
"resource_path" : "$context.resourcePath",
"resource_id" : "$context.resourceId",
"http_method" : "$context.httpMethod",
"source_ip" : "$context.identity.sourceIp",
"user-agent" : "$context.identity.userAgent",
"account_id" : "$context.identity.accountId",
"api_key" : "$context.identity.apiKey",
"caller" : "$context.identity.caller",
415
Amazon API Gateway Developer Guide
Data transformations
"user" : "$context.identity.user",
"user_arn" : "$context.identity.userArn"
}
Parameter Description
416
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
$input Variables
The $input variable represents the method request payload and parameters to be processed by a
mapping template. It provides four functions:
417
Amazon API Gateway Developer Guide
Data transformations
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
$input.path('$.pets').count() would
return "3".
#set($allParams = $input.params())
{
"params" : {
418
Amazon API Gateway Developer Guide
Data transformations
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
}
}
In effect, this mapping template outputs all the request parameters in the payload as outlined as follows:
{
"params" : {
"path" : {
"path_name" : "path_value",
...
}
"header" : {
"header_name" : "header_value",
...
}
"querystring" : {
"querystring_name" : "querystring_value",
...
}
}
}
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 Lambda function. The following examples show how to do this.
The following example shows how to use a mapping to read a name from the query string and then
include the entire POST body in an element:
{
"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.
The following example shows how to pass a JSONPath expression to the json() method. You could also
read a specific property of your request body object by using a period (.), followed by your property
name:
{
"name" : "$input.params('name')",
"body" : $input.json('$.mykey')
}
419
Amazon API Gateway Developer Guide
Data transformations
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'))
}
Request template:
Resource: /things/{id}
POST /things/abc
{
"things" : {
"1" : {},
"2" : {},
"3" : {}
}
}
Response:
{
"id": "abc",
"count": "3",
"things": {
"1": {},
"2": {},
"3": {}
}
}
For more mapping examples, see Working with models and mapping templates (p. 377).
$stageVariables
Stage variables can be used in parameter mapping and mapping templates and as placeholders in
ARNs and URLs used in method integrations. For more information, see the section called “Set up stage
variables” (p. 499).
Syntax Description
420
Amazon API Gateway Developer Guide
Data transformations
Syntax Description
$util Variables
The $util variable contains utility functions for use in mapping templates.
Note
Unless otherwise specified, the default character set is UTF-8.
Function Description
$util.escapeJavaScript(data).replaceAll("\
\'","'")
{"errorMessage":"{\"key1\":\"var1\",
\"key2\":{\"arr\":[1,2,3]}}"}
#set ($errorMessageObj =
$util.parseJson($input.path('$.errorMessage')))
{
"errorMessageObjKey2ArrVal" :
$errorMessageObj.key2.arr[0]
}
{
"errorMessageObjKey2ArrVal" : 1
}
421
Amazon API Gateway Developer Guide
Gateway responses
Function Description
In the API Gateway REST API, a gateway response is represented by the GatewayResponse. In
OpenAPI, a GatewayResponse instance is described by the x-amazon-apigateway-gateway-
responses.gatewayResponse (p. 757) extension.
To enable a gateway response, you set up a gateway response for a supported response type (p. 425) at
the API level. Whenever API Gateway returns a response of this type, the header mappings and payload
mapping templates defined in the gateway response are applied to return the mapped results to the API
caller.
In the following section, we show how to set up gateway responses by using the API Gateway console
and the API Gateway REST API.
For some of the error responses, API Gateway allows customization by API developers to return the
responses in different formats. For the Missing Authentication Token example, you can add a hint
to the original response payload with the possible cause, as in this example: {"message":"Missing
Authentication Token", "hint":"The HTTP method or resources may not be
supported."}.
When your API mediates between an external exchange and the AWS Cloud, you use VTL mapping
templates for integration request or integration response to map the payload from one format to
another. However, the VTL mapping templates work only for valid requests with successful responses.
For invalid requests, API Gateway bypasses the integration altogether and returns an error response. You
must use the customization to render the error responses in an exchange-compliant format. Here, the
customization is rendered in a non-VTL mapping template supporting only simple variable substitutions.
Generalizing the API Gateway-generated error response to any responses generated by API Gateway,
we refer to them as gateway responses. This distinguishes API Gateway-generated responses from
the integration responses. A gateway response mapping template can access $context variable
422
Amazon API Gateway Developer Guide
Gateway responses
values and $stageVariables property values, as well as method request parameters, in the form of
method.request.param-position.param-name.
For more information about $context variables, see $context Variables for data models, authorizers,
mapping templates, and CloudWatch access logging (p. 410). For more information about
$stageVariables, see $stageVariables (p. 420). For more information about method request
parameters, see the section called “$input Variables” (p. 417).
Topics
• Set up a gateway response for a REST API using the API Gateway console (p. 423)
• Set up a gateway response using the API Gateway REST API (p. 424)
• Set up gateway response customization in OpenAPI (p. 425)
• Gateway response types (p. 425)
Access-Control-Allow-Origin:'a.b.c'
x-request-id:method.request.header.x-amzn-RequestId
x-request-path:method.request.path.petId
x-request-query:method.request.querystring.q
In the preceding header mappings, a static domain name ('a.b.c') is mapped to the Allow-
Control-Allow-Origin header to allow CORS access to the API; the input request header of
x-amzn-RequestId is mapped to request-id in the response; the petId path variable of
the incoming request is mapped to the request-path header in the response; and the q query
parameter of the original request is mapped to the request-query header of the response.
7. Under Mapping Templates, keep application/json for Content Type and enter the following
body mapping template in the Body Mapping Template editor:
{
"message":"$context.error.messageString",
"type": "$context.error.responseType",
"statusCode": "'404'",
"stage": "$context.stage",
"resourcePath": "$context.resourcePath",
"stageVariables.a": "$stageVariables.a"
}
423
Amazon API Gateway Developer Guide
Gateway responses
This example shows how to map $context and $stageVariables properties to properties of the
gateway response body.
8. Choose Save.
9. Deploy the API to a new or existing stage.
10. Test it by calling the following CURL command, assuming the corresponding API method's invoke
URL is https://o81lxisefl.execute-api.us-east-1.amazonaws.com/custErr/pets/
{petId}:
Because the extra query string parameter q=1 isn't compatible with the API, an error is returned to
trigger the specified gateway response. You should get a gateway response similar to the following:
{
"message":"Missing Authentication Token",
"type": MISSING_AUTHENTICATION_TOKEN,
"statusCode": '404',
"stage": custErr,
"resourcePath": /pets/{petId},
"stageVariables.a": a
}
The preceding example assumes that the API backend is Pet Store and the API has a stage variable,
a, defined.
424
Amazon API Gateway Developer Guide
Gateway responses
"x-amazon-apigateway-gateway-responses": {
"MISSING_AUTHENTICATION_TOKEN": {
"statusCode": 404,
"responseParameters": {
"gatewayresponse.header.x-request-path": "method.input.params.petId",
"gatewayresponse.header.x-request-query": "method.input.params.q",
"gatewayresponse.header.Access-Control-Allow-Origin": "'a.b.c'",
"gatewayresponse.header.x-request-header": "method.input.params.Accept"
},
"responseTemplates": {
"application/json": "{\n \"message\": $context.error.messageString,\n
\"type\": \"$context.error.responseType\",\n \"stage\": \"$context.stage
\",\n \"resourcePath\": \"$context.resourcePath\",\n \"stageVariables.a\":
\"$stageVariables.a\",\n \"statusCode\": \"'404'\"\n}"
}
}
In this example, the customization changes the status code from the default (403) to 404. It also adds to
the gateway response four header parameters and one body mapping template for the application/
json media type.
425
Amazon API Gateway Developer Guide
Gateway responses
AUTHORIZER_CONFIGURATION_ERROR
500 The gateway response for
failing to connect to a custom or
Amazon Cognito authorizer. If
the response type is unspecified,
this response defaults to the
DEFAULT_5XX type.
426
Amazon API Gateway Developer Guide
Gateway responses
MISSING_AUTHENTICATION_TOKEN
403 The gateway response for a
missing authentication token
error, including the cases when
the client attempts to invoke
an unsupported API method or
resource. If the response type
is unspecified, this response
defaults to the DEFAULT_4XX
type.
427
Amazon API Gateway Developer Guide
Gateway responses
428
Amazon API Gateway Developer Guide
CORS
Cross-origin HTTP requests can be divided into two types: simple requests and non-simple requests.
• It is issued against an API resource that allows only GET, HEAD, and POST requests.
• If it is a POST method request, it must include an Origin header.
• The request payload content type is text/plain, multipart/form-data, or application/x-
www-form-urlencoded.
• The request does not contain custom headers.
• Any additional requirements that are listed in the Mozilla CORS documentation for simple requests.
For simple cross-origin POST method requests, the response from your resource needs to include the
header Access-Control-Allow-Origin, where the value of the header key is set to '*'(any origin)
or is set to the origins allowed to access that resource.
All other cross-origin HTTP requests are non-simple requests. If your API's resources receive non-simple
requests, you need to enable CORS support.
429
Amazon API Gateway Developer Guide
CORS
To support CORS, therefore, a REST API resource needs to implement an OPTIONS method that can
respond to the OPTIONS preflight request with at least the following response headers mandated by the
Fetch standard:
• Access-Control-Allow-Methods
• Access-Control-Allow-Headers
• Access-Control-Allow-Origin
How you enable CORS support depends on your API's integration type.
Enabling CORS support for Lambda or HTTP non-proxy integrations and AWS
service integrations
For a Lambda custom (non-proxy) integration, HTTP custom (non-proxy) integration, or AWS service
integration, you can set up the required headers by using API Gateway method response and integration
response settings. When you enable CORS by using the AWS Management Console, API Gateway creates
an OPTIONS method and attempts to add the Access-Control-Allow-Origin header to your
existing method integration responses. This doesn’t always work, and sometimes you need to manually
modify the integration response to properly enable CORS. Usually this just means manually modifying
the integration response to return the Access-Control-Allow-Origin header.
The following example Lambda functions return the required CORS headers:
Node.js
430
Amazon API Gateway Developer Guide
CORS
Python 3
import json
Topics
• Enable CORS on a resource using the API Gateway console (p. 431)
• Enable CORS on a resource using the API Gateway import API (p. 433)
• Testing CORS (p. 436)
Alternatively, you could choose a method under the resource to enable CORS for just this method.
4. Choose Enable CORS from the Actions drop-down menu.
431
Amazon API Gateway Developer Guide
CORS
432
Amazon API Gateway Developer Guide
CORS
Important
When applying the above instructions to the ANY method in a proxy integration, any
applicable CORS headers will not be set. Instead, your backend must return the applicable
CORS headers, such as Access-Control-Allow-Origin.
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 origins, if you do not want to return the
Cross-origin access error.
After you enable CORS support on your resource, you must deploy or redeploy the API for the
new settings to take effect. For more information, see the section called “Deploy a REST API
(console)” (p. 492).
OpenAPI 3.0
/users:
options:
summary: CORS support
description: |
Enable CORS by returning correct headers
433
Amazon API Gateway Developer Guide
CORS
tags:
- CORS
responses:
200:
description: Default response for CORS method
headers:
Access-Control-Allow-Origin:
schema:
type: string
Access-Control-Allow-Methods:
schema:
type: string
Access-Control-Allow-Headers:
schema:
type: string
content: {}
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: |
{}
OpenAPI 2.0
/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: |
434
Amazon API Gateway Developer Guide
CORS
{}
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.
OpenAPI 3.0
responses:
200:
description: Default response for CORS method
headers:
Access-Control-Allow-Origin:
schema:
type: string
Access-Control-Allow-Methods:
schema:
type: string
Access-Control-Allow-Headers:
schema:
type: string
content: {}
OpenAPI 2.0
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"
2. In the x-amazon-apigateway-integration tag, set up the mapping for those headers to your
static values:
OpenAPI 3.0
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:
435
Amazon API Gateway Developer Guide
Binary media types
application/json: |
{}
OpenAPI 2.0
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 : "'*'"
Testing CORS
You can test your API's CORS configuration by invoking your API, and checking the CORS headers in the
response. The following curl command sends an OPTIONS request to a deployed API.
For example code, see the section called “Return binary media from a Lambda proxy
integration” (p. 447).
436
Amazon API Gateway Developer Guide
Binary media types
Non-proxy integrations
To handle binary payloads for non-proxy integrations, you add the media types to the binaryMediaTypes
list of the RestApi resource. Your API's binaryMediaTypes configuration is a list of content
types that your API treats as binary data. Alternatively, you can set the contentHandling properties
on the Integration and the IntegrationResponse resources. The contentHandling value can be
CONVERT_TO_BINARY, CONVERT_TO_TEXT, or undefined.
Depending on the contentHandling value, and whether the Content-Type header of the response
or the Accept header of the incoming request matches an entry in the binaryMediaTypes list, API
Gateway can encode the raw binary bytes as a base64-encoded string, decode a base64-encoded string
back to its raw bytes, or pass the body through without modification.
You must configure the API as follows to support binary payloads for your API in API Gateway:
• Add the desired binary media types to the binaryMediaTypes list on the RestApi resource. If this
property and the contentHandling property are not defined, the payloads are handled as UTF-8
encoded JSON strings.
• Address the contentHandling property of the Integration resource.
• To have the request payload converted from a base64-encoded string to its binary blob, set the
property to CONVERT_TO_BINARY.
• To have the request payload converted from a binary blob to a base64-encoded string, set the
property to CONVERT_TO_TEXT.
• To pass the payload through without modification, leave the property undefined. To pass a binary
payload through without modification, you must also ensure that the Content-Type matches one
of the binaryMediaTypes entries, and that passthrough behaviors (p. 409) are enabled for the
API.
• Set the contentHandling property of the IntegrationResponse resource. The contentHandling
property, Accept header in client requests, and your API's binaryMediaTypes combined determine
how API Gateway handles content type conversions. For details, see the section called “Content type
conversions in API Gateway” (p. 437).
Important
When a request contains multiple media types in its Accept header, API Gateway honors only
the first Accept media type. If you can't control the order of the Accept media types and the
media type of your binary content isn't the first in the list, add the first Accept media type in
the binaryMediaTypes list of your API. API Gateway handles all content types in this list as
binary.
For example, to send a JPEG file using an <img> element in a browser, the browser might send
Accept:image/webp,image/*,*/*;q=0.8 in a request. By adding image/webp to the
binaryMediaTypes list, the endpoint receives the JPEG file as binary.
For detailed information about how API Gateway handles the text and binary payloads, see Content type
conversions in API Gateway (p. 437).
The following table shows how API Gateway converts the request payload for specific configurations
of a request's Content-Type header, the binaryMediaTypes list of a RestApi resource, and the
contentHandling property value of the Integration resource.
437
Amazon API Gateway Developer Guide
Binary media types
Text data A text data type Set with matching Undefined Text data
media types
Text data A text data type Set with matching CONVERT_TO_TEXT Text data
media types
Binary data A binary data type Set with matching Undefined Binary data
media types
Binary data A binary data type Set with matching Binary data
CONVERT_TO_BINARY
media types
Binary data A binary data type Set with matching CONVERT_TO_TEXT Base64-encoded
media types string
The following table shows how API Gateway converts the response payload for specific configurations
of a request's Accept header, the binaryMediaTypes list of a RestApi resource, and the
contentHandling property value of the IntegrationResponse resource.
Important
When a request contains multiple media types in its Accept header, API Gateway honors only
the first Accept media type. If you can't control the order of the Accept media types and the
media type of your binary content isn't the first in the list, add the first Accept media type in
the binaryMediaTypes list of your API. API Gateway handles all content types in this list as
binary.
For example, to send a JPEG file using an <img> element in a browser, the browser might send
Accept:image/webp,image/*,*/*;q=0.8 in a request. By adding image/webp to the
binaryMediaTypes list, the endpoint receives the JPEG file as binary.
438
Amazon API Gateway Developer Guide
Binary media types
Text data A text type Set with matching Undefined Text data
media types
Binary data A binary type Set with matching Undefined Binary data
media types
When converting a text payload to a binary blob, API Gateway assumes that the text data is a base64-
encoded string and outputs the binary data as a base64-decoded blob. If the conversion fails, it returns a
500 response, which indicates an API configuration error. You don't provide a mapping template for such
a conversion, although you must enable the passthrough behaviors (p. 409) on the API.
When converting a binary payload to a text string, API Gateway always applies a base64 encoding on
the binary data. You can define a mapping template for such a payload, but can only access the base64-
encoded string in the mapping template through $input.body, as shown in the following excerpt of an
example mapping template.
{
"data": "$input.body"
}
To have the binary payload passed through without modification, you must enable the passthrough
behaviors (p. 409) on the API.
439
Amazon API Gateway Developer Guide
Binary media types
a. Create a new API or choose an existing API. For this example, we name the API FileMan.
b. Under the selected API in the primary navigation panel, choose Settings.
c. In the Settings pane, choose Add Binary Media Type in the Binary Media Types section.
d. Type a required media type, for example, image/png, in the input text field. If needed, repeat
this step to add more media types. To support all binary media types, specify */*.
e. Choose Save Changes.
2. Set how message payloads are handled for the API method:
a. Create a new or choose an existing resource in the API. For this example, we use the /
{folder}/{item} resource.
b. Create a new or choose an existing method on the resource. As an example, we use the GET /
{folder}/{item} method integrated with the Object GET action in Amazon S3.
c. In Content Handling, choose an option.
440
Amazon API Gateway Developer Guide
Binary media types
Choose Passthrough if you don't want to convert the body when the client and backend accepts
the same binary format. Choose Convert to text (if needed) to convert the binary body to a
base64-encoded string when, for example, the backend requires that a binary request payload
is passed in as a JSON property. And choose Convert to binary (if needed) when the client
submits a base64-encoded string and the backend requires the original binary format, or when
the endpoint returns a base64-encoded string and the client accepts only the binary output.
d. Preserve the incoming request's Accept header in the integration request. You should do this if
you've set contentHandling to passthrough and want to override that setting at runtime.
441
Amazon API Gateway Developer Guide
Binary media types
f. For conversion to text, define a mapping template to put the base64-encoded binary data into
the required format.
442
Amazon API Gateway Developer Guide
Binary media types
The format of this mapping template depends on the endpoint requirements of the input.
Topics
• Add and update supported binary media types to an API (p. 443)
• Configure request payload conversions (p. 444)
• Configure response payload conversions (p. 444)
• Convert binary data to text data (p. 445)
• Convert text data to a binary payload (p. 445)
• Pass through a binary payload (p. 446)
443
Amazon API Gateway Developer Guide
Binary media types
PATCH /restapis/<restapi_id>
{
"patchOperations" : [ {
"op" : "add",
"path" : "/binaryMediaTypes/image~1jpeg"
}
]
}
The MIME type specification of image/jpeg that is part of the path property value is escaped as
image~1jpeg.
To update the supported binary media types, replace or remove the media type from the
binaryMediaTypes list of the RestApi resource. For example, to change binary support from JPEG
files to raw bytes, submit a PATCH request to the RestApi resource, as follows:
PATCH /restapis/<restapi_id>
{
"patchOperations" : [{
"op" : "replace",
"path" : "/binaryMediaTypes/image~1jpeg",
"value" : "application/octet-stream"
},
{
"op" : "remove",
"path" : "/binaryMediaTypes/image~1jpeg"
}]
}
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration
{
"patchOperations" : [ {
"op" : "replace",
"path" : "/contentHandling",
"value" : "CONVERT_TO_BINARY"
}]
}
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration/
responses/<status_code>
{
"patchOperations" : [ {
"op" : "replace",
"path" : "/contentHandling",
"value" : "CONVERT_TO_BINARY"
}]
444
Amazon API Gateway Developer Guide
Binary media types
1. Enable the binary payload support of the API by adding the new binary media type of application/
octet-stream to the API's binaryMediaTypes list.
PATCH /restapis/<restapi_id>
{
"patchOperations" : [ {
"op" : "add",
"path" : "/binaryMediaTypes/application~1octet-stream"
}
]
}
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration
{
"patchOperations" : [
{
"op" : "replace",
"path" : "/contentHandling",
"value" : "CONVERT_TO_TEXT"
},
{
"op" : "add",
"path" : "/requestTemplates/application~1octet-stream",
"value" : "{\"body\": \"$input.body\"}"
}
]
}
1. Update the API's binaryMediaTypes list by adding the binary media type of application/octet-
stream, if it is not already in the list.
PATCH /restapis/<restapi_id>
{
"patchOperations" : [ {
"op" : "add",
"path" : "/binaryMediaTypes/application~1octet-stream",
}]
}
445
Amazon API Gateway Developer Guide
Binary media types
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration/
responses/<status_code>
{
"patchOperations" : [
{
"op" : "replace",
"path" : "/contentHandling",
"value" : "CONVERT_TO_BINARY"
}
]
}
1. Update the API's binaryMediaTypes list by adding the binary media type of application/octet-
stream, if it isn't already in the list.
PATCH /restapis/<restapi_id>
{
"patchOperations" : [ {
"op" : "add",
"path" : "/binaryMediaTypes/application~1octet-stream"
}
]
}
PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration
{
"patchOperations" : [
{
"op" : "replace",
"path" : "/contentHandling",
"value" : "CONVERT_TO_BINARY"
},
{
"op" : "replace",
"path" : "/passthroughBehaviors",
"value" : "WHEN_NO_MATCH"
}
]
}
446
Amazon API Gateway Developer Guide
Binary media types
Topics
• Return binary media from a Lambda proxy integration (p. 447)
• Access binary files in Amazon S3 through an API Gateway API (p. 448)
• Access binary files in Lambda using an API Gateway API (p. 453)
The following example Python 3 Lambda function can return a binary image from Amazon S3 or text
to clients. The function's response includes a Content-Type header to indicate to the client the type
of data that it returns. The function conditionally sets the isBase64Encoded property in its response,
depending on the type of data that it returns.
import base64
import boto3
import json
import random
s3 = boto3.client('s3')
447
Amazon API Gateway Developer Guide
Binary media types
'statusCode': 200,
'body': base64.b64encode(image).decode('utf-8'),
'isBase64Encoded': True
}
else:
return {
'headers': { "Content-type": "text/html" },
'statusCode': 200,
'body': "<h1>This is text</h1>",
}
To learn more about binary media types, see Working with binary media types for REST APIs (p. 436).
Topics
• OpenAPI file of a sample API to access images in Amazon S3 (p. 448)
• Download an image from Amazon S3 (p. 452)
• Upload an image to Amazon S3 (p. 453)
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"version": "2016-10-21T17:26:28Z",
"title": "ApiName"
},
"paths": {
"/s3": {
"get": {
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
448
Amazon API Gateway Developer Guide
Binary media types
}
}
},
"500": {
"description": "500 response"
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.path.key": "method.request.querystring.key"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "aws"
}
},
"put": {
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
},
"application/octet-stream": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
},
"500": {
"description": "500 response"
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200"
}
449
Amazon API Gateway Developer Guide
Binary media types
},
"requestParameters": {
"integration.request.path.key": "method.request.querystring.key"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
"passthroughBehavior": "when_no_match",
"httpMethod": "PUT",
"type": "aws",
"contentHandling": "CONVERT_TO_BINARY"
}
}
}
},
"x-amazon-apigateway-binary-media-types": [
"application/octet-stream",
"image/jpeg"
],
"servers": [
{
"url": "https://abcdefghi.execute-api.us-east-1.amazonaws.com/{basePath}",
"variables": {
"basePath": {
"default": "/v1"
}
}
}
],
"components": {
"schemas": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
}
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-10-21T17:26:28Z",
"title": "ApiName"
},
"host": "abcdefghi.execute-api.us-east-1.amazonaws.com",
"basePath": "/v1",
"schemes": [
"https"
],
"paths": {
"/s3": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"type": "string"
}
],
"responses": {
450
Amazon API Gateway Developer Guide
Binary media types
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
},
"500": {
"description": "500 response"
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200" }
},
"requestParameters": {
"integration.request.path.key": "method.request.querystring.key"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "aws"
}
},
"put": {
"produces": [
"application/json", "application/octet-stream"
],
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
},
"500": {
"description": "500 response"
}
},
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.path.key": "method.request.querystring.key"
},
"uri": "arn:aws:apigateway:us-west-2:s3:path/{key}",
"passthroughBehavior": "when_no_match",
451
Amazon API Gateway Developer Guide
Binary media types
"httpMethod": "PUT",
"type": "aws",
"contentHandling" : "CONVERT_TO_BINARY"
}
}
}
},
"x-amazon-apigateway-binary-media-types" : ["application/octet-stream", "image/
jpeg"],
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
200 OK HTTP/1.1
[raw bytes]
The raw bytes are returned because the Accept header is set to a binary media type of application/
octet-stream and binary support is enabled for the API.
"x-amazon-apigateway-integration": {
"credentials": "arn:aws:iam::123456789012:role/binarySupportRole",
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200",
"responseTemplates": {
"application/json": "{\n \"image\": \"$input.body\"\n}"
}
}
},
The request to download the image file looks like the following:
452
Amazon API Gateway Developer Guide
Binary media types
200 OK HTTP/1.1
{
"image": "W3JhdyBieXRlc10="
}
[raw bytes]
200 OK HTTP/1.1
W3JhdyBieXRlc10=
The input payload must be a base64-encoded string because the Content-Type header value is set to
application/json. The successful response looks like the following:
200 OK HTTP/1.1
Topics
• OpenAPI file of a sample API to access images in Lambda (p. 453)
• Download an image from Lambda (p. 457)
• Upload an image to Lambda (p. 458)
OpenAPI 3.0
{
"openapi": "3.0.0",
453
Amazon API Gateway Developer Guide
Binary media types
"info": {
"version": "2016-10-21T17:26:28Z",
"title": "ApiName"
},
"paths": {
"/lambda": {
"get": {
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
},
"500": {
"description": "500 response"
}
},
"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:image/invocations",
"type": "AWS",
"credentials": "arn:aws:iam::123456789012:role/Lambda",
"httpMethod": "POST",
"requestTemplates": {
"application/json": "{\n \"imageKey\": \"$input.params('key')\"\n}"
},
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200",
"responseTemplates": {
"application/json": "{\n \"image\": \"$input.body\"\n}"
}
}
}
}
},
"put": {
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
454
Amazon API Gateway Developer Guide
Binary media types
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
},
"application/octet-stream": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
},
"500": {
"description": "500 response"
}
},
"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:image/invocations",
"type": "AWS",
"credentials": "arn:aws:iam::123456789012:role/Lambda",
"httpMethod": "POST",
"contentHandling": "CONVERT_TO_TEXT",
"requestTemplates": {
"application/json": "{\n \"imageKey\": \"$input.params('key')\",
\"image\": \"$input.body\"\n}"
},
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200"
}
}
}
}
}
},
"x-amazon-apigateway-binary-media-types": [
"application/octet-stream",
"image/jpeg"
],
"servers": [
{
"url": "https://abcdefghi.execute-api.us-east-1.amazonaws.com/{basePath}",
"variables": {
"basePath": {
"default": "/v1"
}
}
}
],
"components": {
"schemas": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
}
455
Amazon API Gateway Developer Guide
Binary media types
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-10-21T17:26:28Z",
"title": "ApiName"
},
"host": "abcdefghi.execute-api.us-east-1.amazonaws.com",
"basePath": "/v1",
"schemes": [
"https"
],
"paths": {
"/lambda": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "key",
"in": "query",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
},
"500": {
"description": "500 response"
}
},
"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:image/invocations",
"type": "AWS",
"credentials": "arn:aws:iam::123456789012:role/Lambda",
"httpMethod": "POST",
"requestTemplates": {
"application/json": "{\n \"imageKey\": \"$input.params('key')\"\n}"
},
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200",
"responseTemplates": {
"application/json": "{\n \"image\": \"$input.body\"\n}"
}
}
}
}
},
"put": {
"produces": [
"application/json", "application/octet-stream"
],
"parameters": [
456
Amazon API Gateway Developer Guide
Binary media types
{
"name": "key",
"in": "query",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
},
"500": {
"description": "500 response"
}
},
"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:image/invocations",
"type": "AWS",
"credentials": "arn:aws:iam::123456789012:role/Lambda",
"httpMethod": "POST",
"contentHandling" : "CONVERT_TO_TEXT",
"requestTemplates": {
"application/json": "{\n \"imageKey\": \"$input.params('key')\", \"image
\": \"$input.body\"\n}"
},
"responses": {
"default": {
"statusCode": "500"
},
"2\\d{2}": {
"statusCode": "200"
}
}
}
}
}
},
"x-amazon-apigateway-binary-media-types" : ["application/octet-stream", "image/
jpeg"],
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
457
Amazon API Gateway Developer Guide
Invoke
200 OK HTTP/1.1
[raw bytes]
200 OK HTTP/1.1
{
"image": "W3JhdyBieXRlc10="
}
[raw bytes]
200 OK
W3JhdyBieXRlc10=
200 OK
https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/
458
Amazon API Gateway Developer Guide
Invoke
where {restapi_id} is the API identifier, {region} is the Region, and {stage_name} is the stage
name of the API deployment.
Important
Before you can invoke an API, you must deploy it in API Gateway. To do that, follow the
instructions in Deploying a REST API in Amazon API Gateway (p. 490).
Topics
• Obtain an API's invoke URL in the API Gateway console (p. 459)
• Use the API Gateway console to test a REST API method (p. 459)
• Call REST API through generated SDKs (p. 460)
• How to invoke a private API (p. 478)
If an API permits anonymous access, you can use any web browser to invoke any GET method calls by
copying and pasting an appropriate invocation URL to the browser's address bar. For other methods or
any authentication-required calls, the invocation are 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 application
using one of the AWS SDKs.
For testing, you can use the API Gateway console to call an API by 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 application to test a successfully deployed API, without writing a script or a
client.
Note
Query string parameter values in an invocation URL cannot contain %%.
Topics
• Prerequisites (p. 459)
• Test a method with the API Gateway console (p. 459)
Prerequisites
• You must specify the settings for the methods you want to test. Follow the instructions in Set up
REST API methods in API Gateway (p. 261).
459
Amazon API Gateway Developer Guide
Invoke
For additional options you may need to specify, contact the API owner.
5. Choose Test. The following information will be displayed:
• Request is the resource's path that was called for the method.
• Status is the response's HTTP status code.
• Latency is the time between the receipt of the request from the caller and the returned response.
• Response Body is the HTTP response body.
• Response Headers are the HTTP response headers.
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.
In addition to using the API Gateway console, you can use AWS CLI or an AWS SDK for API Gateway to
test invoking a method. To do so using AWS CLI, see test-invoke-method.
Topics
• Use a Java SDK generated by API Gateway for a REST API (p. 460)
• Use an Android SDK generated by API Gateway for a REST API (p. 464)
• Use a JavaScript SDK generated by API Gateway for a REST API (p. 465)
• Use a Ruby SDK generated by API Gateway for a REST API (p. 467)
• Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift (p. 470)
1. Extract the contents of the API Gateway-generated .zip file that you downloaded earlier.
2. Download and install Apache Maven (must be version 3.5 or later).
460
Amazon API Gateway Developer Guide
Invoke
mvn -B archetype:generate \
-DarchetypeGroupdId=org.apache.maven.archetypes \
-DgroupId=examples.aws.apig.simpleCalc.sdk.app \
-DartifactId=SimpleCalc-sdkClient
Note
The separator \ in the preceding command is included for readability. The whole command
should be on a single line without the separator.
This command creates an application stub. The application stub contains a pom.xml file and an src
folder under the project's root directory (SimpleCalc-sdkClient in the preceding command).
Initially, there are two source files: src/main/java/{package-path}/App.java and src/test/
java/{package-path}/AppTest.java. In this example, {package-path} is examples/aws/
apig/simpleCalc/sdk/app. This package path is derived from the DarchetypeGroupdId value.
You can use the App.java file as a template for your client application, and you can add others
in the same folder if needed. You can use the AppTest.java file as a unit test template for your
application, and you can add other test code files to the same test folder as needed.
7. Update the package dependencies in the generated pom.xml file to the following, substituting your
project's groupId, artifactId, version, and name properties, if necessary:
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>1.11.94</version>
</dependency>
<dependency>
<groupId>my-apig-api-examples</groupId>
<artifactId>simple-calc-sdk</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
461
Amazon API Gateway Developer Guide
Invoke
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Note
When a newer version of dependent artifact of aws-java-sdk-core is incompatible with
the version specified above (1.11.94), you must update the <version> tag to the new
version.
8. Next, we show how to call the API using the SDK by calling the getABOp(GetABOpRequest
req), getApiRoot(GetApiRootRequest req), and postApiRoot(PostApiRootRequest
req) methods of the SDK. These methods correspond to the GET /{a}/{b}/{op}, GET /?
a={x}&b={y}&op={operator}, and POST / methods, with a payload of {"a": x, "b": y,
"op": "operator"} API requests, respectively.
package examples.aws.apig.simpleCalc.sdk.app;
import java.io.IOException;
import com.amazonaws.opensdk.config.ConnectionConfiguration;
import com.amazonaws.opensdk.config.TimeoutConfiguration;
import examples.aws.apig.simpleCalc.sdk.*;
import examples.aws.apig.simpleCalc.sdk.model.*;
import examples.aws.apig.simpleCalc.sdk.SimpleCalcSdk.*;
public App() {
initSdk();
}
// The configuration settings are for illustration purposes and may not be a
recommended best practice.
private void initSdk() {
sdkClient = SimpleCalcSdk.builder()
.connectionConfiguration(
new ConnectionConfiguration()
.maxConnections(100)
.connectionMaxIdleMillis(1000))
.timeoutConfiguration(
new TimeoutConfiguration()
.httpRequestTimeout(3000)
.totalExecutionTimeout(10000)
462
Amazon API Gateway Developer Guide
Invoke
.socketTimeout(2000))
.build();
}
// Calling shutdown is not necessary unless you want to exert explicit control of
this resource.
public void shutdown() {
sdkClient.shutdown();
}
}
}
In the preceding example, the configuration settings used to instantiate the SDK client are
for illustration purposes and are not necessarily recommended best practice. Also, calling
sdkClient.shutdown() is optional, especially if you need precise control on when to free up
resources.
We have shown the essential patterns to call an API using a Java SDK. You can extend the instructions to
calling other API methods.
463
Amazon API Gateway Developer Guide
Invoke
1. Extract the contents of the API Gateway-generated .zip file that you downloaded earlier.
2. Download and install Apache Maven (preferably version 3.x).
3. Download and install JDK 8.
4. Set the JAVA_HOME environment variable.
5. Run the mvn install command to install the compiled artifact files to your local Maven repository.
This creates a target folder containing the 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., simple-calcsdk-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 Android 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.
// Invoke a method:
// For the 'GET /?a=1&b=2&op=+' method exposed by the API, you can invoke it by
calling the following SDK method:
// where the Result class of the SDK corresponds to the Result model of the API.
//
// For the 'GET /{a}/{b}/{op}' method exposed by the API, you can call the following
SDK method to invoke the request,
464
Amazon API Gateway Developer Guide
Invoke
// where the Input class of the SDK corresponds to the Input model of the API.
String result=output.c;
8. To use an Amazon Cognito credentials provider to authorize calls to your API, use the
ApiClientFactory class to pass a set of AWS credentials by using the SDK generated by API
Gateway, as shown in the following example.
9. To set an API key by using the API Gateway- generated SDK, use code similar to the following.
To install, initiate and call a JavaScript SDK generated by API Gateway for a REST API
1. 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 SDK generated by API
Gateway will call. For instructions, see Enabling CORS for a REST API resource (p. 429).
3. In your web page, include references to the following scripts.
465
Amazon API Gateway Developer Guide
Invoke
4. In your code, initialize the SDK generated by API Gateway by using code similar to the following.
To initialize the SDK generated by API Gateway with AWS credentials, use code similar to the
following. If you use AWS credentials, all requests to the API will be signed.
To use an API key with the SDK generated by API Gateway, 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.
5. Call the API methods 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,
};
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: ''
}
466
Amazon API Gateway Developer Guide
Invoke
};
Here, the methodName is constructed from the method request's resource path and the HTTP verb.
For the SimpleCalc API, the SDK methods for the API methods of
1. GET /?a=...&b=...&op=...
2. POST /
Note
These instructions assume you already completed the instructions in Generate SDKs for an API
using the API Gateway console (p. 605).
To install, instantiate, and call a Ruby SDK generated by API Gateway for a REST API
1. Unzip the downloaded Ruby SDK file. The generated SDK source is shown as follows.
467
Amazon API Gateway Developer Guide
Invoke
2. Build a Ruby Gem from the generated SDK source, using the following shell commands in a terminal
window:
4. Create a client application. Instantiate and initialize the Ruby SDK client in the app:
require 'simplecalc-sdk'
client = SimpleCalc::Client.new(
http_wire_trace: true,
retry_limit: 5,
http_read_timeout: 50
)
If the API has authorization of the AWS_IAM type is configured, you can include the caller's AWS
credentials by supplying accessKey and secretKey during the initialization:
468
Amazon API Gateway Developer Guide
Invoke
require 'pet-sdk'
client = Pet::Client.new(
http_wire_trace: true,
retry_limit: 5,
http_read_timeout: 50,
access_key_id: 'ACCESS_KEY',
secret_access_key: 'SECRET_KEY'
)
This results in the following display, corresponding to the API methods of GET /?
a={.}&b={.}&op={.}, GET /{a}/{b}/{op}, and POST /, plus a payload of the {a:"…",
b:"…", op:"…"} format, respectively:
To invoke the GET /?a=1&b=2&op=+ API method, call the following the Ruby SDK method:
To invoke the POST / API method with a payload of {a: "1", b: "2", "op": "+"}, call the
following Ruby SDK method:
To invoke the GET /1/2/+ API method, call the following Ruby SDK method:
resp : {
result: {
input: {
a: 1,
b: 2,
op: "+"
},
output: {
c: 3
}
}
}
469
Amazon API Gateway Developer Guide
Invoke
Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift
In this tutorial, we will show how to use an iOS SDK generated by API Gateway for a REST API in an
Objective-C or Swift app to call the underlying API. We will use the SimpleCalc API (p. 611) as an
example to illustrate the following topics:
• How to install the required AWS Mobile SDK components into your Xcode project
• How to create the API client object before calling the API's methods
• How to call the API methods through the corresponding SDK methods on the API client object
• How to prepare a method input and parse its result using the corresponding model classes of the SDK
Topics
• Use generated iOS SDK (Objective-C) to call API (p. 470)
• Use generated iOS SDK (Swift) to call API (p. 474)
Before beginning the following procedure, you must complete the steps in Generate SDKs for an
API using the API Gateway console (p. 605) for iOS in Objective-C and download the .zip file of the
generated SDK.
Install the AWS mobile SDK and an iOS SDK generated by API Gateway in an Objective-C project
1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the
SimpleCalc API (p. 611), you may want to rename the unzipped SDK folder to something like
sdk_objc_simple_calc. In this SDK folder there is a README.md file and a Podfile file. The
README.md file contains the instructions to install and use the SDK. This tutorial provides details
about these instructions. The installation leverages CocoaPods to import required API Gateway
libraries and other dependent AWS Mobile SDK components. You must update the Podfile
to import the SDKs into your app's Xcode project. The unarchived SDK folder also contains a
generated-src folder that contains the source code of the generated SDK of your API.
2. Launch Xcode and create a new iOS Objective-C project. Make a note of the project's target. You will
need to set it in the Podfile.
3. To import the AWS Mobile SDK for iOS into the Xcode project by using CocoaPods, do the following:
470
Amazon API Gateway Developer Guide
Invoke
pod setup
b. Copy the Podfile file from the extracted SDK folder into the same directory containing your
Xcode project file. Replace the following block:
target '<YourXcodeTarget>' do
pod 'AWSAPIGateway', '~> 2.4.7'
end
target 'app_objc_simple_calc' do
pod 'AWSAPIGateway', '~> 2.4.7'
end
If your Xcode project already contains a file named Podfile, add the following line of code to
it:
pod install
This installs the API Gateway component and other dependent AWS Mobile SDK components.
d. Close the Xcode project and then open the .xcworkspace file to relaunch Xcode.
e. Add all of the .h and .m files from the extracted SDK's generated-src directory into your
Xcode project.
471
Amazon API Gateway Developer Guide
Invoke
To import the AWS Mobile SDK for iOS Objective-C into your project by explicitly downloading AWS
Mobile SDK or using Carthage, follow the instructions in the README.md file. Be sure to use only
one of these options to import the AWS Mobile SDK.
Call API methods using the iOS SDK generated by API Gateway in an Objective-C project
When you generated the SDK with the prefix of SIMPLE_CALC for this SimpleCalc API (p. 611)
with two models for input (Input) and output (Result) of the methods, in the SDK, the resulting
API client class becomes SIMPLE_CALCSimpleCalcClient and the corresponding data classes are
SIMPLE_CALCInput and SIMPLE_CALCResult, respectively. The API requests and responses are
mapped to the SDK methods as follows:
GET /?a=...&b=...&op=...
The AWSTask.result property is of the SIMPLE_CALCResult type if the Result model was added
to the method response. Otherwise, the property is of the NSDictionary type.
• This API request of
POST /
{
"a": "Number",
"b": "Number",
"op": "String"
}
GET /{a}/{b}/{op}
The following procedure describes how to call the API methods in Objective-C app source code; for
example, as part of the viewDidLoad delegate in a ViewController.m file.
To call the API through the iOS SDK generated by API Gateway
1. Import the API client class header file to make the API client class callable in the app:
472
Amazon API Gateway Developer Guide
Invoke
#import "SIMPLE_CALCSimpleCalc.h"
The #import statement also imports SIMPLE_CALCInput.h and SIMPLE_CALCResult.h for the
two model classes.
2. Instantiate the API client class:
To use Amazon Cognito with the API, set the defaultServiceConfiguration property on the
default AWSServiceManager object, as shown in the following, before calling the defaultClient
method to create the API client object (shown in the preceding example):
473
Amazon API Gateway Developer Guide
Invoke
The resulting display is 1 div 2 = 0.5. Here, div is used in place of / because the simple Lambda
function (p. 609) in the backend does not handle URL encoded path variables.
Before beginning the following procedure, you must complete the steps in Generate SDKs for an API
using the API Gateway console (p. 605) for iOS in Swift and download the .zip file of the generated
SDK.
Topics
• Install AWS mobile SDK and API Gateway-generated SDK in a Swift project (p. 474)
• Call API methods through the iOS SDK generated by API Gateway in a Swift project (p. 476)
Install AWS mobile SDK and API Gateway-generated SDK in a Swift project
1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the
SimpleCalc API (p. 611), you may want to rename the unzipped SDK folder to something like
sdk_swift_simple_calc. In this SDK folder there is a README.md file and a Podfile file. The
README.md file contains the instructions to install and use the SDK. This tutorial provides details
about these instructions. The installation leverages CocoaPods to import required AWS Mobile SDK
components. You must update the Podfile to import the SDKs into your Swift app's Xcode project.
The unarchived SDK folder also contains a generated-src folder that contains the source code of
the generated SDK of your API.
2. Launch Xcode and create a new iOS Swift project. Make a note of the project's target. You will need
to set it in the Podfile.
3. To import the required AWS Mobile SDK components into the Xcode project by using CocoaPods, do
the following:
474
Amazon API Gateway Developer Guide
Invoke
a. If it is not installed, install CocoaPods by running the following command in a terminal window:
b. Copy the Podfile file from the extracted SDK folder into the same directory containing your
Xcode project file. Replace the following block:
target '<YourXcodeTarget>' do
pod 'AWSAPIGateway', '~> 2.4.7'
end
target 'app_swift_simple_calc' do
pod 'AWSAPIGateway', '~> 2.4.7'
end
If your Xcode project already contains a Podfile with the correct target, you can simply add
the following line of code to the do ... end loop:
c. Open a terminal window and run the following command in the app directory:
pod install
This installs the API Gateway component and any dependent AWS Mobile SDK components into
the app's project.
d. Close the Xcode project and then open the *.xcworkspace file to relaunch Xcode.
e. Add all of the SDK's header files (.h) and Swift source code files (.swift) from the extracted
generated-src directory to your Xcode project.
f. To enable calling the Objective-C libraries of the AWS Mobile SDK from your Swift code project,
set the Bridging_Header.h file path on the Objective-C Bridging Header property under the
Swift Compiler - General setting of your Xcode project configuration:
475
Amazon API Gateway Developer Guide
Invoke
Tip
You can type bridging in the search box of Xcode to locate the Objective-C Bridging
Header property.
g. Build the Xcode project to verify that it is properly configured before proceeding further. If your
Xcode uses a more recent version of Swift than the one supported for the AWS Mobile SDK, you
will get Swift compiler errors. In this case, set the Use Legacy Swift Language Version property
to Yes under the Swift Compiler - Version setting:
To import the AWS Mobile SDK for iOS in Swift into your project by explicitly downloading the AWS
Mobile SDK or using Carthage, follow the instructions in the README.md file that comes with the
SDK package. Be sure to use only one of these options to import the AWS Mobile SDK.
Call API methods through the iOS SDK generated by API Gateway in a Swift project
When you generated the SDK with the prefix of SIMPLE_CALC for this SimpleCalc API (p. 611) with two
models to describe the input (Input) and output (Result) of the API's requests and responses, in the
SDK, the resulting API client class becomes SIMPLE_CALCSimpleCalcClient and the corresponding
data classes are SIMPLE_CALCInput and SIMPLE_CALCResult, respectively. The API requests and
responses are mapped to the SDK methods as follows:
GET /?a=...&b=...&op=...
476
Amazon API Gateway Developer Guide
Invoke
The AWSTask.result property is of the SIMPLE_CALCResult type if the Result model was added
to the method response. Otherwise, it is of the NSDictionary type.
• This API request of
POST /
{
"a": "Number",
"b": "Number",
"op": "String"
}
GET /{a}/{b}/{op}
The following procedure describes how to call the API methods in Swift app source code; for example, as
part of the viewDidLoad() delegate in a ViewController.m file.
To call the API through the iOS SDK generated by API Gateway
To use Amazon Cognito with the API, set a default AWS service configuration (shown following)
before getting the defaultClient method (shown previously):
let credentialsProvider =
AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityPoolId:
"my_pool_id")
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1,
credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
where the helper function self.showResult(task) prints the result or error to the console; for
example:
477
Amazon API Gateway Developer Guide
Invoke
In a production app, you can display the result or error in a text field. The resulting display is 1 + 2
= 3.
3. Call the POST / with a payload to perform 1-2:
The resulting display is 1 div 2 = 0.5. Here, div is used in place of / because the simple Lambda
function (p. 609) in the backend does not handle URL encoded path variables.
Once you have deployed a private API (p. 665), you can access it via private DNS (if you've enabled
private DNS naming) and via public DNS.
To get the DNS names for your private API, do the following:
1. Sign in to the AWS Management Console and open the Amazon VPC console at https://
console.aws.amazon.com/vpc/.
2. In the left navigation pane, choose Endpoints and then choose your interface VPC endpoint for API
Gateway.
478
Amazon API Gateway Developer Guide
Invoke
3. In the Details pane, you'll see 5 values in the DNS names field. The first 3 are the public DNS names
for your API. The other 2 are the private DNS names for it.
If you've enabled private DNS, you can access your private API using the private DNS names as follows:
{restapi-id}.execute-api.{region}.amazonaws.com
https://{restapi-id}.execute-api.{region}.amazonaws.com/{stage}
For example, assuming you set up the GET /pets and GET /pets/{petId} methods in this example,
and assuming that your rest API ID was 01234567ab and your region was us-west-2, you could test
your API by typing the following URLs in a browser:
https://01234567ab.execute-api.us-west-2.amazonaws.com/test/pets
and
https://01234567ab.execute-api.us-west-2.amazonaws.com/test/pets/1
and
You can also use private DNS names to access your private API from an on-premises network by setting
up an Amazon Route 53 Resolver inbound endpoint and forwarding it all DNS queries of the private DNS
from your remote network. For more information, see Forwarding inbound DNS queries to your VPCs in
the Amazon Route 53 Developer Guide.
479
Amazon API Gateway Developer Guide
OpenAPI
Once you associate your private API's REST API ID with the VPC endpoints you'll be calling your REST API
from, you can use the following format base URL to invoke the API using a Route53 alias.
https://{rest-api-id}-{vpce-id}.execute-api.{region}.amazonaws.com/{stage}
For example, assuming you set up the GET /pets and GET /pets/{petId} methods in this example, and
assuming that your API's API ID was 01234567ab, VPC Endpoint ID was vpce-01234567abcdef012, and
your region was us-west-2, you can invoke your API as:
curl -v https://01234567ab-vpce-01234567abcdef012.execute-api.us-west-2.amazonaws.com/test/
pets/
https://{public-dns-hostname}.execute-api.{region}.vpce.amazonaws.com/{stage}
For example, assuming you set up the GET /pets and GET /pets/{petId} methods in this
example, and assuming that your API's API ID was 01234567ab, its public DNS hostname was
vpce-01234567abcdef012-01234567, and your region was us-west-2, you could test your API via
its VPCE ID by using the Host header in a cURL command, as in the following example:
curl -v https://vpce-01234567abcdef012-01234567.execute-api.us-east-1.vpce.amazonaws.com/
test/pets -H 'Host: 01234567ab.execute-api.us-west-2.amazonaws.com'
Alternatively, you can access your private API via its API ID by using the x-apigw-api-id header in a
cURL command in the following format:
For a tutorial on using the Import API feature from the API Gateway console, see Tutorial: Create a REST
API by importing an example (p. 46).
Topics
• Import an edge-optimized API into API Gateway (p. 481)
• Import a regional API into API Gateway (p. 481)
• Import an OpenAPI file to update an existing API definition (p. 482)
• Set the OpenAPIbasePath property (p. 484)
480
Amazon API Gateway Developer Guide
OpenAPI
For a tutorial on using the Import API feature from the API Gateway console, see Tutorial: Create a REST
API by importing an example (p. 46).
Topics
• Import an edge-optimized API using the API Gateway console (p. 481)
• Import an edge-optimized API using the AWS CLI (p. 481)
481
Amazon API Gateway Developer Guide
OpenAPI
When you export an API, the API endpoint configuration is not included in the exported API definitions.
For a tutorial on using the Import API feature from the API Gateway console, see Tutorial: Create a REST
API by importing an example (p. 46).
Topics
• Import a regional API using the API Gateway console (p. 482)
• Import a regional API using the AWS CLI (p. 482)
When an API (A) is merged into another (B), the resulting API retains the definitions of both A and B if
the two APIs do not share any conflicting definitions. When conflicts arise, the method definitions of
the merging API (A) overrides the corresponding method definitions of the merged API (B). For example,
suppose B has declared the following methods to return 200 and 206 responses:
GET /a
POST /a
and A declares the following method to return 200 and 400 responses:
GET /a
When A is merged into B, the resulting API yields the following methods:
GET /a
482
Amazon API Gateway Developer Guide
OpenAPI
POST /a
Merging an API is useful when you have decomposed your external API definitions into multiple, smaller
parts and only want to apply changes from one of those parts at a time. For example, this might occur if
multiple teams are responsible for different parts of an API and have changes available at different rates.
In this mode, items from the existing API that aren't specifically defined in the imported definition are
left alone.
When an API (A) overwrites another API (B), the resulting API takes the definitions of the overwriting API
(A). Overwriting an API is useful when an external API definition contains the complete definition of an
API. In this mode, items from an existing API that aren't specifically defined in the imported definition
are deleted.
The following code snippet shows an example of the PUT request to merge an OpenAPI API definition in
JSON, as the payload, with the specified API already in API Gateway.
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.
The following code snippet shows an example of an overwriting request with the payload of a JSON-
formatted OpenAPI definition:
PUT /restapis/<restapi_id>?mode=overwrite
Host:apigateway.<region>.amazonaws.com
Content-Type: application/json
Content-Length: ...
483
Amazon API Gateway Developer Guide
OpenAPI
In OpenAPI 3.0, basePath is no longer a top-level property. Instead, API Gateway uses a server variable
as a convention. The Import API feature provides the same options for interpreting the base path during
import. The base path is identified as follows:
• If the API doesn't contain any basePath variables, the Import API feature checks the server.url
string to see if it contains a path beyond "/". If it does, that path is used as the base path.
• If the API contains only one basePath variable, the Import API feature uses it as the base path, even if
it's not referenced in the server.url.
• If the API contains multiple basePath variables, the Import API feature uses only the first one as the
base path.
Ignore
If the OpenAPI 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
• /
• /e
• /f
The effect is to treat the basePath as if it was not present, and all of the declared API resources are
served relative to the host. This can be used, for example, when you have a custom domain name with an
API mapping that doesn't include a Base Path and a Stage value that refers to your production stage.
Note
API Gateway automatically creates a root resource for you, even if it isn't explicitly declared in
your definition file.
Prepend
If the OpenAPI 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
PUT /restapis/api_id?basepath=prepend
484
Amazon API Gateway Developer Guide
OpenAPI
• /
• /a
• /a/b
• /a/b/c
• /a/b/c/e
• /a/b/c/f
The effect is to treat the basePath as specifying additional resources (without methods) and to add
them to the declared resource set. This can be used, for example, when different teams are responsible
for different parts of an API and the basePath could reference the path location for each team's API
part.
Note
API Gateway automatically creates intermediate resources for you, even if they aren't explicitly
declared in your definition.
Split
If the OpenAPI 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
• /
• /b
• /b/c
• /b/c/e
• /b/c/f
The effect is to treat top-most path part, /a, as the beginning of each resource's path, and to create
additional (no method) resources within the API itself. This could, for example, be used when a is a stage
name that you want to expose as part of your API.
AWS variables
485
Amazon API Gateway Developer Guide
OpenAPI
OpenAPI 3.0
openapi: "3.0.1"
info:
title: "tasks-api"
version: "v1.0"
paths:
/:
get:
summary: List tasks
description: Returns a list of tasks
responses:
200:
description: "OK"
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Task"
500:
description: "Internal Server Error"
content: {}
x-amazon-apigateway-integration:
uri:
arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/
functions/arn:${AWS::Partition}:lambda:${AWS::Region}:
${AWS::AccountId}:function:LambdaFunctionName/invocations
responses:
default:
statusCode: "200"
passthroughBehavior: "when_no_match"
httpMethod: "POST"
contentHandling: "CONVERT_TO_TEXT"
type: "aws_proxy"
components:
schemas:
Task:
type: object
properties:
id:
type: integer
name:
type: string
description:
type: string
486
Amazon API Gateway Developer Guide
OpenAPI
You cannot export an API if its payloads are not of the application/json type. If you try, you will get
an error response stating that JSON body models are not found.
OpenAPI 3.0
https://<host>/restapis/<restapi_id>/stages/<stage_name>/exports/oas30
OpenAPI 2.0
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.
487
Amazon API Gateway Developer Guide
OpenAPI
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.
Models must contain properties or be defined as a particular JSONSchema type.
OpenAPI 3.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30
Host: apigateway.<region>.amazonaws.com
Accept: application/json
OpenAPI 2.0
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
OpenAPI 3.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
OpenAPI 2.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
488
Amazon API Gateway Developer Guide
OpenAPI
OpenAPI 3.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30?extensions=postman
Host: apigateway.<region>.amazonaws.com
Accept: application/json
OpenAPI 2.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?extensions=postman
Host: apigateway.<region>.amazonaws.com
Accept: application/json
Download REST API OpenAPI definition with API Gateway integration in YAML
To export and download a REST API in OpenAPI definitions with API Gateway integration in YAML
format:
OpenAPI 3.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30?extensions=integrations
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
OpenAPI 2.0
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?extensions=integrations
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
From the stage configuration page in the API Gateway console, choose the Export tab and then one of
the available options (Export as OpenAPI, Export as OpenAPI + API Gateway Integrations and Export
as Postman) to download your API's OpenAPI definition.
489
Amazon API Gateway Developer Guide
Publish
In this section, you can learn how to deploy your API and customize the URL that you provide to users to
access it.
Topics
• Deploying a REST API in Amazon API Gateway (p. 490)
• Setting up custom domain names for REST APIs (p. 518)
To deploy an API, you create an API deployment and associate it with a stage. A stage is a logical
reference to a lifecycle state of your API (for example, dev, prod, beta, v2). API stages are identified by
the API ID and stage name. They're included in the URL that you use to invoke the API. Each stage is a
named reference to a deployment of the API and is made available for client applications to call.
Important
Every time you update an API, you must redeploy the API to an existing stage or to a new stage.
Updating an API includes modifying routes, methods, integrations, authorizers, and anything
else other than stage settings.
As your API evolves, you can continue to deploy it to different stages as different versions of the API. You
can also deploy your API updates as a canary release deployment (p. 507). This enables your API clients
to access, on the same stage, the production version through the production release, and the updated
version through the canary release.
To call a deployed API, the client submits a request against an API's URL. The URL is determined by
an API's protocol (HTTP(S) or (WSS)), hostname, stage name, and (for REST APIs) resource path. The
hostname and the stage name determine the API's base URL.
Using the API's default domain name, the base URL of a REST API (for example) in a given stage
({stageName}) is in the following format:
https://{restapi-id}.execute-api.{region}.amazonaws.com/{stageName}
490
Amazon API Gateway Developer Guide
Deploying a REST API
To make the API's default base URL more user-friendly, you can create a custom domain name (for
example, api.example.com) to replace the default hostname of the API. To support multiple APIs
under the custom domain name, you must map an API stage to a base path.
With a custom domain name of {api.example.com} and the API stage mapped to a base path of
({basePath}) under the custom domain name, the base URL of a REST API becomes the following:
https://{api.example.com}/{basePath}
For each stage, you can optimize API performance by adjusting the default account-level request
throttling limits and enabling API caching. You can also enable logging for API calls to CloudTrail or
CloudWatch, and can select a client certificate for the backend to authenticate the API requests. In
addition, you can override stage-level settings for individual methods and define stage variables to pass
stage-specific environment contexts to the API integration at runtime.
Stages enable robust version control of your API. For example, you can deploy an API to a test stage
and a prod stage, and use the test stage as a test build and use the prod stage as a stable build. After
the updates pass the test, you can promote the test stage to the prod stage. The promotion can be
done by redeploying the API to the prod stage or updating a stage variable (p. 493) value from the
stage name of test to that of prod.
In this section, we discuss how to deploy an API by using the API Gateway console or calling the API
Gateway REST API. To use other tools, see the documentation of the AWS CLI or an AWS SDK.
Topics
• Deploy a REST API in API Gateway (p. 491)
• Setting up a stage for a REST API (p. 493)
• Set up an API Gateway canary release deployment (p. 507)
• Updates to a REST API that require redeployment (p. 517)
For the client to call your API, you must create a deployment and associate a stage with it. A stage is
represented by a Stage resource. It represents a snapshot of the API, including methods, integrations,
models, mapping templates, and Lambda authorizers (formerly known as custom authorizers). When you
update the API, you can redeploy the API by associating a new stage with the existing deployment. We
discuss creating a stage in the section called “Set up a stage” (p. 493).
Topics
• Create a deployment using the AWS CLI (p. 491)
• Deploying a REST API from the API Gateway console (p. 492)
491
Amazon API Gateway Developer Guide
Deploying a REST API
The API is not callable until you associate this deployment with a stage. With an existing stage, you
can do this by updating the stage's deploymentId property with the newly created deployment ID
(<deployment-id>).
When deploying an API the first time, you can combine the stage creation and deployment creation at
the same time:
This is what is done behind the scenes in the API Gateway console when you deploy an API the first time,
or when you redeploy the API to a new stage.
Topics
• Deploy a REST API to a stage (p. 492)
• Redeploy a REST API to a stage (p. 492)
• Update the stage configuration of a REST API deployment (p. 493)
• Set stage variables for a REST API deployment (p. 493)
• Associate a stage with a different REST API deployment (p. 493)
The API Gateway console lets you deploy an API by creating a deployment and associating it with a new
or existing stage.
Note
To associate a stage in API Gateway with a different deployment, see Associate a stage with a
different REST API deployment (p. 493) instead.
To redeploy an API, perform the same steps as in the section called “Deploy a REST API to a
stage” (p. 492). You can reuse the same stage as many times as desired.
492
Amazon API Gateway Developer Guide
Deploying a REST API
The following procedure shows how to do this using the Stage Editor in the API Gateway console. It is
assumed that you must have deployed an API more than once.
1. If you're not already in Stage Editor, choose the stage that you want to update the deployment from
an API's Stages option in the APIs main navigation pane.
2. On the Deployment History tab, choose the option button next to the deployment you want the
stage to use.
3. Choose Change Deployment.
Topics
• Setting up a stage using the API Gateway console (p. 493)
• Setting up tags for an API stage in API Gateway (p. 497)
• Setting up stage variables for a REST API deployment (p. 499)
493
Amazon API Gateway Developer Guide
Deploying a REST API
After the initial deployment, you can add more stages and associate them with existing deployments.
You can use the API Gateway console to create a new stage, or you can choose an existing stage while
deploying an API. In general, you can add a new stage to an API deployment before redeploying the API.
To create a new stage using the API Gateway console, follow these steps:.
After a successful deployment of an API, the stage is populated with default settings. You can use the
console or the API Gateway REST API to change the stage settings, including API caching and logging.
The following steps show you how to do so using the Stage Editor of the API Gateway console.
These steps assume that you've already deployed the API to a stage.
For more information about stage-level cache settings, see Enabling API caching to enhance
responsiveness (p. 539).
Important
If you enable API caching for an API stage, your AWS account might be charged for API
caching. Caching isn't eligible for the AWS Free Tier.
Tip
You can also override enabled stage-level cache settings for individual methods. To do so,
expand the stage under the Stages secondary navigation pane, and choose a method. Then,
in the stage editor, choose the Override for this method option for Settings. In the Cache
Settings area, you can set or clear Enable Method Cache, or customize any other desired
options. For more information about the method-level cache settings, see Enabling API
caching to enhance responsiveness (p. 539).
6. To enable Amazon CloudWatch Logs for all of the methods associated with this stage of this API
Gateway API, do the following:
a. Under the CloudWatch Settings section, select the Enable CloudWatch Logs option.
494
Amazon API Gateway Developer Guide
Deploying a REST API
Tip
To enable method-level CloudWatch settings, expand the stage under the Stages
secondary navigation pane, and choose each method of interest. Back in the stage
editor, choose Override for this method for Settings. In the CloudWatch Settings
area, make sure to select Log to CloudWatch Logs and any other desired options
before choosing Save Changes.
Important
Your account is charged for accessing method-level CloudWatch metrics, but not the
API-level or stage-level metrics.
b. 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.
c. To log full API call request and response information, select Log full requests/responses data.
No sensitive data is logged unless the Log full requests/responses data option is selected.
Important
Setting logs to ERROR and then choosing Log full requests/responses data results in
every request being logged in detail. This is the intended behavior.
d. To have API Gateway report to CloudWatch the API metrics of API calls, Latency,
Integration latency, 400 errors, and 500 errors, choose the Enable Detailed
CloudWatch Metrics option. For more information about CloudWatch, see the Amazon
CloudWatch User Guide.
e. Choose Save Changes. The new settings take effect after a new deployment.
Important
To 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 so, choose Settings from the APIs main
navigation pane. Then enter the ARN of an IAM role in the CloudWatch log role ARN
text field.
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": [
{
495
Amazon API Gateway Developer Guide
Deploying a REST API
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
For more information about CloudWatch, see the Amazon CloudWatch User Guide.
7. To enable access logging to a Kinesis Data Firehose delivery stream:
496
Amazon API Gateway Developer Guide
Deploying a REST API
c. To set sampling rules in the X-Ray console, choose Set X-Ray Sampling Rules.
d. If desired, choose Set X-Ray Sampling Rules and go to the X-Ray console to configure sampling
rules.
For more information, see Tracing user requests to REST APIs using X-Ray (p. 682).
13. Choose Save Changes. The new settings take effect after you redeploy the API to the stage.
Delete a stage
When you no longer need a stage, you can delete it to avoid paying for unused resources. The following
steps show you how to use the API Gateway console to delete a stage.
Warning
Deleting a stage might cause part or all of the corresponding API to be unusable by API callers.
Deleting a stage cannot be undone, but you can recreate the stage and associate it with the
same deployment.
A stage can also inherit tags from its parent REST API. For more information, see the section called “Tag
inheritance in the Amazon API Gateway V1 API” (p. 807).
For more information about tagging API Gateway resources, see Tagging (p. 806).
Topics
• Set up tags for an API stage using the API Gateway console (p. 497)
• Set up tags for an API stage using the API Gateway REST API (p. 498)
Set up tags for an API stage using the API Gateway console
The following procedure describes how to set up tags for an API stage.
To set up tags for an API stage by using the API Gateway console
497
Amazon API Gateway Developer Guide
Deploying a REST API
6. If needed, repeat step 5 to add more tags to the API stage. The maximum number of tags per stage
is 50.
7. To remove an existing tag from the stage, choose the trash bin icon next to the tag.
8. Choose Save Changes to finish setting up the stage tags.
If the API has been deployed previously in the API Gateway console, you need to redeploy it for the
changes to take effect.
Set up tags for an API stage using the API Gateway REST API
You can set up tags for an API stage using the API Gateway REST API by doing one of the following:
After you deploy an API (m5zr3vnks7) to a stage (test), tag the stage by calling tags:tag. The
required stage Amazon Resource Name (ARN) (arn:aws:apigateway:us-east-1::/restapis/
m5zr3vnks7/stages/test) must be URL encoded (arn%3Aaws%3Aapigateway%3Aus-east-1%3A
%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftest).
PUT /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftest
{
"tags" : {
"Department" : "Sales"
}
}
You can also use the previous request to update an existing tag to a new value.
You can add tags to a stage when calling stage:create to create the stage:
POST /restapis/<restapi_id>/stages
{
"stageName" : "test",
"deploymentId" : "adr134",
"description" : "test deployment",
"cacheClusterEnabled" : "true",
"cacheClusterSize" : "500",
"variables" : {
"sv1" : "val1"
},
"documentationVersion" : "test",
"tags" : {
"Department" : "Sales",
"Division" : "Retail"
}
}
498
Amazon API Gateway Developer Guide
Deploying a REST API
DELETE /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages
%2Ftest?tagKeys=Department
Host: apigateway.us-east-1.amazonaws.com
Authorization: ...
To remove more than one tag, use a comma-separated list of tag keys in the query expression—for
example, ?tagKeys=Department,Division,….
GET /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftags
Host: apigateway.us-east-1.amazonaws.com
Authorization: ...
200 OK
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
tags-{rel}.html",
"name": "tags",
"templated": true
},
"tags:tag": {
"href": "/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis
%2Fm5zr3vnks7%2Fstages%2Ftags"
},
"tags:untag": {
"href": "/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis
%2Fm5zr3vnks7%2Fstages%2Ftags{?tagKeys}",
"templated": true
}
},
"tags": {
"Department": "Sales"
}
}
For example, you can define a stage variable in a stage configuration, and then set its value as the URL
string of an HTTP integration for a method in your REST API. Later, you can reference the URL string by
using the associated stage variable name from the API setup. By doing this, you can use the same API
setup with a different endpoint at each stage by resetting the stage variable value to the corresponding
URLs.
You can also access stage variables in the mapping templates, or pass configuration parameters to your
AWS Lambda or HTTP backend.
499
Amazon API Gateway Developer Guide
Deploying a REST API
For more information about mapping templates, see API Gateway mapping template and access logging
variable reference (p. 410).
Note
Stage variables are not intended to be used for sensitive data, such as credentials. To pass
sensitive data to integrations, use an AWS Lambda authorizer. You can pass sensitive data
to integrations in the output of the Lambda authorizer. To learn more, see the section called
“Output from an Amazon API Gateway Lambda authorizer” (p. 309).
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 backend endpoints.
For example, your API can pass a GET request as an HTTP proxy to the backend web host (for example,
http://example.com). In this case, the backend 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 might want to reuse 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 (for example, url), and then assign it a value, (for example,
example.com). Next, from your method configuration, set up an HTTP proxy integration. Instead
of entering the endpoint's URL, 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 (AWS CLI) to do this.
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
500
Amazon API Gateway Developer Guide
Deploying a REST API
In this tutorial, you learn how to set stage variables for two deployment stages of a sample API by using
the Amazon API Gateway console. Before you begin, make sure the following prerequisites are met:
• You must have an API available in API Gateway. Follow the instructions in Creating a REST API in
Amazon API Gateway (p. 242).
• You must have deployed the API at least once. Follow the instructions in Deploying a REST API in
Amazon API Gateway (p. 490).
• You must have created the first stage for a deployed API. Follow the instructions in Create a new
stage (p. 494).
You can use API Gateway stage variables to access the HTTP and Lambda backends for different API
deployment stages. You can also use stage variables to pass stage-specific configuration metadata into
an HTTP backend as a query parameter and into a Lambda function as a payload that is generated in an
input mapping template.
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 Setting stage variables using the Amazon API Gateway
console (p. 501).
501
Amazon API Gateway Developer Guide
Deploying a REST API
1. 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.
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 returns 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.
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.
Pass stage-specific metadata to an HTTP backend through a stage variable in a query parameter
expression
This procedure describes how to use a stage variable value in a query parameter expression to pass
stage-specific metadata into an HTTP backend. We will use the version stage variable declared in
Setting stage variables using the Amazon API Gateway console (p. 501).
1. 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. Enter version for the parameter
name.
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.
4. The response is shown next. Notice that v-beta, assigned to the version stage variable, is passed
in the backend as the version argument.
502
Amazon API Gateway Developer Guide
Deploying a REST API
This procedure describes how to use a stage variable to call a Lambda function as a backend of your
API. We will use the function stage variable declared earlier. For more information, see Setting stage
variables using the Amazon API Gateway console (p. 501).
1. 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, enter ${stageVariables.function}. Choose Save.
Tip
When prompted with Add Permission to Lambda Function, make a note of the AWS CLI
command before choosing OK. You must run the command on each Lambda function 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:
503
Amazon API Gateway Developer Guide
Deploying a REST API
Failing to do so results in a 500 Internal Server Error response when invoking the
method. Make sure to replace ${stageVariables.function} with the Lambda function
name that is assigned to the stage variable.
This procedure describes how to use a stage variable to pass stage-specific configuration metadata into a
Lambda function. We will use a POST method and an input mapping template to generate payload using
the version stage variable declared earlier.
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 enter
${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 a Lambda function through an API with a stage variable (p. 503).
504
Amazon API Gateway Developer Guide
Deploying a REST API
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}"). In other places, it
must be referenced without quotes (as in ${stageVariables.function}).
3. Deploy the API to available stages.
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.
You can use API Gateway stage variables in the following cases.
505
Amazon API Gateway Developer Guide
Deploying a REST API
A stage variable can be used in a parameter mapping expression for an API method's request or response
header parameter, without any partial substitution. In the following example, the stage variable is
referenced without the $ and the enclosing {...}.
• stageVariables.<variable_name>
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>}"}
A stage variable can be used as part of an HTTP integration URL, as shown in the following examples:
A stage variable can be used as part of AWS URI action or path components, as shown in the following
example.
• arn:aws:apigateway:<region>:<service>:${stageVariables.<variable_name>}
A stage variable can be used in place of a Lambda function name, or version/alias, as shown in the
following examples.
• arn:aws:apigateway:<region>:lambda:path/2015-03-31/
functions/arn:aws:lambda:<region>:<account_id>:function:
${stageVariables.<function_variable_name>}/invocations
• arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/
arn:aws:lambda:<region>:<account_id>:function:<function_name>:
${stageVariables.<version_variable_name>}/invocations
Note
To use a stage variable for a Lambda function, the function must be in the same account as the
API. Stage variables don't support cross-account Lambda functions.
A stage variable can be used as part of AWS user/role credential ARN, as shown in the following example.
• arn:aws:iam::<account_id>:${stageVariables.<variable_name>}
506
Amazon API Gateway Developer Guide
Deploying a REST API
In a canary release deployment, total API traffic is separated at random into a production release and
a canary release with a pre-configured ratio. Typically, the canary release receives a small percentage
of API traffic and the production release takes up the rest. The updated API features are only visible to
API traffic through the canary. You can adjust the canary traffic percentage to optimize test coverage or
performance.
By keeping canary traffic small and the selection random, most users are not adversely affected at any
time by potential bugs in the new version, and no single user is adversely affected all the time.
After the test metrics pass your requirements, you can promote the canary release to the production
release and disable the canary from the deployment. This makes the new features available in the
production stage.
Topics
• Canary release deployment in API Gateway (p. 507)
• Create a canary release deployment (p. 508)
• Update a canary release (p. 512)
• Promote a canary release (p. 514)
• Disable a canary release (p. 516)
To deploy an API with a canary release, you create a canary release deployment by adding canary
settings to the stage of a regular deployment. The canary settings describe the underlying canary
release and the stage represents the production release of the API within this deployment. To add canary
settings, set canarySettings on the deployment stage and specify the following:
• A deployment ID, initially identical to the ID of the base version deployment set on the stage.
• A percentage of API traffic, between 0.0 and 100.0 inclusive, for the canary release.
• Stage variables for the canary release that can override production release stage variables.
• The use of the stage cache for canary requests, if the useStageCache is set and API caching is enabled
on the stage.
After a canary release is enabled, the deployment stage cannot be associated with another non-canary
release deployment until the canary release is disabled and the canary settings removed from the stage.
When you enable API execution logging, the canary release has its own logs and metrics generated for all
canary requests. They are reported to a production stage CloudWatch Logs log group as well as a canary-
specific CloudWatch Logs log group. The same applies to access logging. The separate canary-specific
507
Amazon API Gateway Developer Guide
Deploying a REST API
logs are helpful to validate new API changes and decide whether to accept the changes and promote the
canary release to the production stage, or to discard the changes and revert the canary release from the
production stage.
A canary release can use the stage cache, if enabled, to store responses and use cached entries to return
results to the next canary requests, within a pre-configured time-to-live (TTL) period.
In a canary release deployment, the production release and canary release of the API can be associated
with the same version or with different versions. When they are associated with different versions,
responses for production and canary requests are cached separately and the stage cache returns
corresponding results for production and canary requests. When the production release and canary
release are associated with the same deployment, the stage cache uses a single cache key for both types
of requests and returns the same response for the same requests from the production release and canary
release.
You can also create a canary release deployment from an existing non-canary deployment by making a
stage:update request to add the canary settings on the stage.
When creating a non-canary release deployment, you can specify a non-existing stage name. API
Gateway creates one if the specified stage does not exist. However, you cannot specify any non-existing
stage name when creating a canary release deployment. You will get an error and API Gateway will not
create any canary release deployment.
You can create a canary release deployment in API Gateway using the API Gateway console, the AWS CLI,
or an AWS SDK.
Topics
• Create a canary deployment using the API Gateway console (p. 508)
• Create a canary deployment using the AWS CLI (p. 509)
To use the API Gateway console to create a canary release deployment, follow the instructions below:
So far, you have deployed the API to a production release stage. Next, you configure canary settings
on the stage and, if needed, also enable caching, set stage variables, or configure API execution or
access logs.
508
Amazon API Gateway Developer Guide
Deploying a REST API
5. To enable API caching, choose the Settings tab in Stage Editor and follow the on-screen
instructions. For more information, see the section called “Cache settings” (p. 539).
6. To set stage variables, choose the Stage Variables tab in Stage Editor and follow the on-screen
instructions to add or modify stage variables. For more information, see the section called “Set up
stage variables” (p. 499).
7. To configure execution or access logging, choose the Logs tab in Stage Editor and follow the on-
screen instructions. For more information, see Setting up CloudWatch logging for a REST API in API
Gateway (p. 678).
8. In Stage Editor, choose the Canary tab and then choose Create Canary.
9. Under the Stage's Request Distribution section, choose the pencil icon next to Percentage of
requests to Canary and type a number (for example, 5.0) in the input text field. Choose the check
mark icon to save the setting.
10. To associate an AWS WAF web ACL with the stage, choose a web ACL from the Web ACL dropdown
list.
Note
If needed, choose Create Web ACL to open the AWS WAF console in a new browser tab,
create the web ACL, and return to the API Gateway console to associate the web ACL with
the stage.
11. If desired, choose Block API Request if WebACL cannot be evaluated (Fail- Close).
12. If needed, choose Add Stage Variables to add them under the Canary Stage Variables section to
override existing stage variables or add new stage variables for the canary release.
13. If desired, choose Enable use of stage cache to enable caching for the canary release and save your
choice. The cache is not available for the canary release until API caching is enabled.
After the canary release is initialized on the deployment stage, you change the API and want to test the
changes. You can redeploy the API to the same stage so that both the updated version and the base
version are accessible through the same stage. The following steps describe how to do that.
1. With each update of the API, choose Deploy API from the Actions drop-down menu next to the
Resources list.
2. In Deploy API, choose the now canary-enabled stage from the Deployment stage drop-down list.
3. Optionally, type a description in Deployment description.
4. Choose Deploy to push the latest API version to the canary release.
5. If desired, reconfigure the stage settings, logs, or canary settings, as describe in To create the initial
canary release deployment (p. 508).
As a result, the canary release points to the latest version while the production release still points to the
initial version of the API. The canarySettings now has a new deploymentId value, whereas the stage still
has the initial deploymentId value. Behind the scenes, the console calls stage:update.
First create a baseline deployment with two stage variables, but without any canary:
509
Amazon API Gateway Developer Guide
Deploying a REST API
The command returns a representation of the resulting Deployment, similar to the following:
{
"id": "du4ot1",
"createdDate": 1511379050
}
If the specified stage (prod) does not exist, the preceding command returns an error. Otherwise, it
returns the newly created deployment resource representation similar to the following:
{
"id": "a6rox0",
"createdDate": 1511379433
}
The resulting deployment id identifies the test version of the API for the canary release. As a result, the
associated stage is canary-enabled. You can view this stage representation by calling the get-stage
command, similar to the following:
The following shows a representation of the Stage as the output of the command:
{
"stageName": "prod",
"variables": {
"sv0": "val0",
"sv1": "val1"
},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": "du4ot1",
"lastUpdatedDate": 1511379433,
"createdDate": 1511379050,
"canarySettings": {
"percentTraffic": 10.5,
"deploymentId": "a6rox0",
"useStageCache": false,
"stageVariableOverrides": {
"sv2": "val3",
"sv1": "val2"
}
510
Amazon API Gateway Developer Guide
Deploying a REST API
},
"methodSettings": {}
}
In this example, the base version of the API will use the stage variables of {"sv0":val0",
"sv1":val1"}, while the test version uses the stage variables of {"sv1":val2", "sv2":val3"}.
Both the production release and canary release use the same stage variable of sv1, but with different
values, val1 and val2, respectively. The stage variable of sv0 is used solely in the production release
and the stage variable of sv2 is used in the canary release only.
You can create a canary release deployment from an existing regular deployment by updating the stage
to enable a canary. To demonstrate this, create a regular deployment first:
{
"id": "cifeiw",
"createdDate": 1511380879
}
The associated beta stage does not have any canary settings:
{
"stageName": "beta",
"variables": {
"sv0": "val0",
"sv1": "val1"
},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": "cifeiw",
"lastUpdatedDate": 1511380879,
"createdDate": 1511380879,
"methodSettings": {}
}
Now, create a new canary release deployment by attaching a canary on the stage:
511
Amazon API Gateway Developer Guide
Deploying a REST API
}]' \
--rest-api-id 4wk1k4onj3 \
--stage-name beta
{
"stageName": "beta",
"variables": {
"sv0": "val0",
"sv1": "val1"
},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": "cifeiw",
"lastUpdatedDate": 1511381930,
"createdDate": 1511380879,
"canarySettings": {
"percentTraffic": 10.5,
"deploymentId": "cifeiw",
"useStageCache": false,
"stageVariableOverrides": {
"sv2": "val3",
"sv1": "val2"
}
},
"methodSettings": {}
}
Because we just enabled a canary on an existing version of the API, both the production release
(Stage) and canary release (canarySettings) point to the same deployment, i.e., the same version
(deploymentId) of the API. After you change the API and deploy it to this stage again, the new version
will be in the canary release, while the base version remains in the production release. This is manifested
in the stage evolution when the deploymentId in the canary release is updated to the new deployment
id and the deploymentId in the production release remains unchanged.
You can update a canary release using the API Gateway console, the AWS CLI update-stage command or
an AWS SDK.
Topics
• Update a canary release using the API Gateway console (p. 512)
• Update a canary release using the AWS CLI (p. 513)
To use the API Gateway console to update existing canary settings on a stage, do the following:
1. Sign in to the API Gateway console and choose an existing API in the primary navigation pane.
2. Choose Stages under the API and then choose an existing stage under the Stages list to open the
Stage Editor.
3. Choose the Canary tab in the Stage Editor.
512
Amazon API Gateway Developer Guide
Deploying a REST API
To use the AWS CLI to update a canary, call the update-stage command.
To enable or disable the use of a stage cache for the canary, call the update-stage command as
follows:
To adjust the canary traffic percentage, call update-stage to replace the /canarySettings/
percentTraffic value on the stage.
To update canary stage variables, including adding, replacing, or removing a canary stage variable:
You can update all of the above by combining the operations into a single patch-operations value:
513
Amazon API Gateway Developer Guide
Deploying a REST API
"op": "remove", \
"path": "/canarySettings/stageVariableOverrides/var1" \
}, { \
"op": "replace", \
"path": "/canarySettings/stageVariableOverrides/newVar", \
"value": "newVal" \
}, { \
"op": "replace", \
"path": "/canarySettings/stageVariableOverrides/val2", \
"value": "val4" \
}]'
• Reset the deployment ID of the stage with the deployment ID settings of the canary. This updates the
API snapshot of the stage with the snapshot of the canary, making the test version the production
release as well.
• Update stage variables with canary stage variables, if any. This updates the API execution context of
the stage with that of the canary. Without this update, the new API version may produce unexpected
results if the test version uses different stage variables or different values of existing stage variables.
• Set the percentage of canary traffic to 0.0%.
Promoting a canary release does not disable the canary on the stage. To disable a canary, you must
remove the canary settings on the stage.
Topics
• Promote a canary release using the API Gateway console (p. 514)
• Promote a canary release using the AWS CLI (p. 514)
To use the API Gateway console to promote a canary release deployment, do the following:
1. Sign in to the API Gateway console and choose an existing API in the primary navigation pane.
2. Choose Stages under the API and then choose an existing stage under the Stages list to open the
Stage Editor.
3. Choose the Canary tab in the Stage Editor.
4. Choose Promote Canary.
5. Confirm changes to be made and choose Update.
After the promotion, the production release references the same API version (deploymentId) as the
canary release. You can verify this using the AWS CLI. For example, see the section called “Promote a
canary release using the AWS CLI” (p. 514).
To promote a canary release to the production release using the AWS CLI commands, call the update-
stage command to copy the canary-associated deploymentId to the stage-associated deploymentId,
to reset the canary traffic percentage to zero (0.0), and, to copy any canary-bound stage variables to the
corresponding stage-bound ones.
514
Amazon API Gateway Developer Guide
Deploying a REST API
Suppose we have a canary release deployment, described by a stage similar to the following:
{
"_links": {
...
},
"accessLogSettings": {
...
},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"canarySettings": {
"deploymentId": "eh1sby",
"useStageCache": false,
"stageVariableOverrides": {
"sv2": "val3",
"sv1": "val2"
},
"percentTraffic": 10.5
},
"createdDate": "2017-11-20T04:42:19Z",
"deploymentId": "nfcn0x",
"lastUpdatedDate": "2017-11-22T00:54:28Z",
"methodSettings": {
...
},
"stageName": "prod",
"variables": {
"sv1": "val1"
}
}
{
"_links": {
...
},
"accessLogSettings": {
...
},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"canarySettings": {
515
Amazon API Gateway Developer Guide
Deploying a REST API
"deploymentId": "eh1sby",
"useStageCache": false,
"stageVariableOverrides": {
"sv2": "val3",
"sv1": "val2"
},
"percentTraffic": 0
},
"createdDate": "2017-11-20T04:42:19Z",
"deploymentId": "eh1sby",
"lastUpdatedDate": "2017-11-22T05:29:47Z",
"methodSettings": {
...
},
"stageName": "prod",
"variables": {
"sv2": "val3",
"sv1": "val2"
}
}
As you can see, promoting a canary release to the stage does not disable the canary and the deployment
remains to be a canary release deployment. To make it a regular production release deployment,
you must disable the canary settings. For more information about how to disable a canary release
deployment, see the section called “Disable a canary release” (p. 516).
You can disable a canary release deployment using the API Gateway console, the AWS CLI, or an AWS
SDK.
Topics
• Disable a canary release using the API Gateway console (p. 516)
• Disable a canary release using the AWS CLI (p. 516)
To use the API Gateway console to disable a canary release deployment, use the following steps:
1. Sign in to the API Gateway console and choose an existing API in the primary navigation pane.
2. Choose Stages under the API and then choose an existing stage under the Stages list to open the
Stage Editor.
3. Choose the Canary tab in the Stage Editor.
4. Choose Delete Canary.
5. Confirm you want to delete the canary by choosing Delete.
As a result, the canarySettings property becomes null and is removed from the deployment stage.
You can verify this using the AWS CLI. For example, see the section called “Disable a canary release using
the AWS CLI” (p. 516).
To use the AWS CLI to disable a canary release deployment, call the update-stage command as
follows:
516
Amazon API Gateway Developer Guide
Deploying a REST API
{
"stageName": "prod",
"accessLogSettings": {
...
},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": "nfcn0x",
"lastUpdatedDate": 1511309280,
"createdDate": 1511152939,
"methodSettings": {
...
}
}
As shown in the output, the canarySettings property is no longer present in the stage of a canary-
disabled deployment.
API resources that can be updated are detailed in the following table.
Resource Remarks
ApiKey For applicable properties and supported operations, see apikey:update. The update
requires redeploying the API.
Authorizer For applicable properties and supported operations, see authorizer:update. The
update requires redeploying the API.
DocumentationVersion
For applicable properties and supported operations, see
documentationversion:update. The update requires redeploying the API.
Integration For applicable properties and supported operations, see integration:update. The
update requires redeploying the API.
517
Amazon API Gateway Developer Guide
Custom domain names
Resource Remarks
Method For applicable properties and supported operations, see method:update. The
update requires redeploying the API.
Model For applicable properties and supported operations, see model:update. The update
requires redeploying the API.
Resource For applicable properties and supported operations, see resource:update. The
update requires redeploying the API.
RestApi For applicable properties and supported operations, see restapi:update. The
update requires redeploying the API.
VpcLink For applicable properties and supported operations, see vpclink:update. The
update requires redeploying the API.
API configurations that can be updated are detailed in the following table.
Configuration Remarks
Account For applicable properties and supported operations, see account:update. The
update does not require redeploying the API.
DomainName For applicable properties and supported operations, see domainname:update. The
update does not require redeploying the API.
Stage For applicable properties and supported operations, see stage:update. The update
does not require redeploying the API.
Usage For applicable properties and supported operations, see usage:update. The update
does not require redeploying the API.
UsagePlan For applicable properties and supported operations, see usageplan:update. The
update does not require redeploying the API.
After deploying your API, you (and your customers) can invoke the API using the default base URL of the
following format:
https://api-id.execute-api.region.amazonaws.com/stage
518
Amazon API Gateway Developer Guide
Custom domain names
where api-id is generated by API Gateway, region (AWS Region) is specified by you when creating the
API, and stage is specified by you when deploying the API.
With custom domain names, you can set up your API's hostname, and choose a base path (for example,
myservice) to map the alternative URL to your API. For example, a more user-friendly API base URL can
become:
https://api.example.com/myservice
If you don't set any base mapping under a custom domain name, the resulting API's base URL is the same
as the custom domain (for example, https://api.example.com). In this case, the custom domain
name can't support more than one API.
Note
A Regional custom domain can be associated with REST APIs and HTTP APIs. You can use API
Gateway Version 2 APIs to create and manage Regional custom domain names for REST APIs.
Custom domain names are not supported for private APIs (p. 665).
You can choose a minimum TLS version that your REST API supports. For REST APIs, you can
choose TLS 1.2 or TLS 1.0.
After a custom domain name is created in API Gateway, you must create or update your DNS provider's
resource record to map to your API endpoint. Without such a mapping, API requests bound for the
custom domain name cannot reach API Gateway.
Note
An edge-optimized custom domain name is created in a specific Region and owned by a specific
AWS account. Moving such a custom domain name between Regions or AWS accounts involves
deleting the existing CloudFront distribution and creating a new one. The process may take
approximately 30 minutes before the new custom domain name becomes available. For more
information, see Updating CloudFront Distributions.
When you create a custom domain name for an edge-optimized API, API Gateway sets up a CloudFront
distribution. But you must set up a DNS record to map the custom domain name to the CloudFront
distribution domain name. This mapping is for API requests that are bound for the custom domain name
to be routed to API Gateway through the mapped CloudFront distribution. You must also provide a
certificate for the custom domain name.
Note
The CloudFront distribution created by API Gateway is owned by a Region-specific account
affiliated with API Gateway. When tracing operations to create and update such a CloudFront
distribution in CloudWatch Logs, you must use this API Gateway account ID. For more
information, see Log custom domain name creation in CloudTrail (p. 528).
519
Amazon API Gateway Developer Guide
Custom domain names
To set up an edge-optimized custom domain name or to update its certificate, you must have a
permission to update CloudFront distributions. You can do so by attaching the following IAM policy
statement to an IAM user, group, or role in your account:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudFrontUpdateDistribution",
"Effect": "Allow",
"Action": [
"cloudfront:updateDistribution"
],
"Resource": [
"*"
]
}
]
}
API Gateway supports edge-optimized custom domain names by leveraging Server Name Indication (SNI)
on the CloudFront distribution. For more information on using custom domain names on a CloudFront
distribution, including the required certificate format and the maximum size of a certificate key length,
see Using Alternate Domain Names and HTTPS in the Amazon CloudFront Developer Guide.
To set up a custom domain name as your API's hostname, you, as the API owner, must provide an SSL/
TLS certificate for the custom domain name.
To provide a certificate for an edge-optimized custom domain name, you can request AWS Certificate
Manager (ACM) to generate a new certificate in ACM or to import into ACM one issued by a third-party
certificate authority in the us-east-1 Region (US East (N. Virginia)).
To create a wildcard custom domain name, specify a wildcard (*) as the first subdomain of a custom
domain that represents all possible subdomains of a root domain.
For example, the wildcard custom domain name *.example.com results in subdomains such as
a.example.com, b.example.com, and c.example.com, which all route to the same domain.
Wildcard custom domain names support distinct configurations from API Gateway's standard custom
domain names. For example, in a single AWS account, you can configure *.example.com and
a.example.com to behave differently.
To create a wildcard custom domain name, you must provide a certificate issued by ACM that has been
validated using either the DNS or the email validation method.
520
Amazon API Gateway Developer Guide
Custom domain names
Note
You can't create a wildcard custom domain name if a different AWS account has created a
custom domain name that conflicts with the wildcard custom domain name. For example,
if account A has created a.example.com, then account B can't create the wildcard custom
domain name *.example.com.
If account A and account B share an owner, you can contact the AWS Support Center to request
an exception.
To import an SSL/TLS certificate, you must provide the PEM-formatted SSL/TLS certificate body, its
private key, and the certificate chain for the custom domain name. Each certificate stored in ACM is
identified by its ARN. To use an AWS managed certificate for a domain name, you simply reference its
ARN.
ACM makes it straightforward to set up and use a custom domain name for an API. You create a
certificate for the given domain name (or import a certificate), set up the domain name in API Gateway
with the ARN of the certificate provided by ACM, and map a base path under the custom domain name
to a deployed stage of the API. With certificates issued by ACM, you do not have to worry about exposing
any sensitive certificate details, such as the private key.
Topics
• Getting certificates ready in AWS Certificate Manager (p. 521)
• Choosing a minimum TLS version for a custom domain in API Gateway (p. 523)
• Creating an edge-optimized custom domain name (p. 527)
• Setting up a regional custom domain name in API Gateway (p. 531)
• Migrating a custom domain name to a different API endpoint (p. 534)
• Working with API mappings for REST APIs (p. 537)
• Disabling the default endpoint for a REST API (p. 539)
First, register your internet domain, for example, example.com. You can use either Amazon Route 53 or
a third-party accredited domain registrar. For a list of such registrars, see Accredited Registrar Directory
at the ICANN website.
To create in or import into ACM an SSL/TLS certificate for a domain name, do one of the following:
521
Amazon API Gateway Developer Guide
Custom domain names
1. Get a PEM-encoded SSL/TLS certificate for your custom domain name from a certificate authority.
For a partial list of such CAs, see the Mozilla Included CA List
a. Generate a private key for the certificate and save the output to a file, using the OpenSSL
toolkit at the OpenSSL website:
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/TLS 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. The public key
size is determined by the certificate authority you use. Ask your certificate authority
to return keys of a size different from the default length. 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:
c. Submit the CSR to the certificate authority and save the resulting certificate.
d. Download the certificate chain from the certificate authority.
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
-----BEGIN CERTIFICATE-----
EXAMPLECA+KgAwIBAgIQJ1XxJ8Pl++gOfQtj0IBoqDANBgkqhkiG9w0BAQUFADBB
...
az8Cg1aicxLBQ7EaWIhhgEXAMPLE
522
Amazon API Gateway Developer Guide
Custom domain names
-----END CERTIFICATE-----
d. For Certificate private key, enter or paste your PEM-formatted certificate's private key. The
following shows an abbreviated example of such a key.
e. For Certificate chain, enter 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
...
8/ifBlIK3se2e4/hEfcEejX/arxbx1BJCHBvlEPNnsdw8EXAMPLE
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Intermediate certificate 2
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Intermediate certificate 1
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Optional: Root certificate
-----END CERTIFICATE-----
After the certificate is successfully created or imported, make note of the certificate ARN. You need it
when setting up the custom domain name.
A security policy is a predefined combination of minimum TLS version and cipher suite offered by
Amazon API Gateway. You can choose either a TLS version 1.2 or TLS version 1.0 security policy. The TLS
protocol addresses network security problems such as tampering and eavesdropping between a client
and server. When your clients establish a TLS handshake to your API through the custom domain, the
security policy enforces the TLS version and cipher suite options your clients can choose to use.
• The minimum TLS version that API Gateway uses to communicate with API clients
• The cipher that API Gateway uses to encrypt the content that it returns to API clients
523
Amazon API Gateway Developer Guide
Custom domain names
Topics
• How to specify a minimum TLS protocol version for custom domains in API Gateway (p. 524)
• Supported security policies, TLS protocol versions, and ciphers for edge-optimized API endpoints in
API Gateway (p. 524)
• Supported SSL/TLS protocols and ciphers for regional, private, and WebSocket API endpoints in API
Gateway (p. 525)
• OpenSSL and RFC cipher names (p. 526)
How to specify a minimum TLS protocol version for custom domains in API
Gateway
When you create a custom domain, you specify the security policy for it. For more information about
security policies, see the tables in the following sections.
The following sections describe how to create a custom domain name, including specifying the minimum
TLS version in the API Gateway console and CLI:
• the section called “Creating an edge-optimized custom domain name” (p. 527)
• the section called “Setting up a regional custom domain name” (p. 531)
You can change the security policy by updating the domain name settings. To change the minimum TLS
version, use one of the following commands, specifying the new TLS version (TLS_1_0 or TLS_1_2) in
the securityPolicy parameter. Allow up to 60 minutes for the update to be completed.
• domainname:update
• update-domain-name
• UpdateDomainName
Supported security policies, TLS protocol versions, and ciphers for edge-
optimized API endpoints in API Gateway
The following table lists the protocols and ciphers that API Gateway can use for each security policy for
edge-optimized APIs.
Security policy
TLS-1-0 TLS-1-2
TLSv1.3 ♦ ♦
TLSv1.2 ♦ ♦
TLSv1.1 ♦
TLSv1 ♦
SSLv3
Ciphers supported
ECDHE-RSA-AES128-GCM- ♦ ♦
SHA256
524
Amazon API Gateway Developer Guide
Custom domain names
Security policy
TLS-1-0 TLS-1-2
ECDHE-RSA-AES128-SHA256 ♦ ♦
ECDHE-RSA-AES128-SHA ♦
ECDHE-RSA-AES256-GCM- ♦ ♦
SHA384
ECDHE-RSA-AES256-SHA384 ♦ ♦
ECDHE-RSA-AES256-SHA ♦
AES128-GCM-SHA256 ♦ ♦
AES256-GCM-SHA384 ♦ ♦
AES128-SHA256 ♦ ♦
AES256-SHA ♦
AES128-SHA ♦
DES-CBC3-SHA ♦
RC4-MD5
Supported SSL/TLS protocols and ciphers for regional, private, and WebSocket
API endpoints in API Gateway
The following table describes the security policies that can be specified for Regional, private, and
WebSocket API endpoints.
Note
For private and WebSocket APIs, only TLS-1-2 can be specified.
TLS Protocols
Protocol-TLSv1 ♦
Protocol-TLSv1.1 ♦
Protocol-TLSv1.2 ♦ ♦
TLS Ciphers
ECDHE-ECDSA-AES128-GCM- ♦ ♦
SHA256
ECDHE-RSA-AES128-GCM- ♦ ♦
SHA256
ECDHE-ECDSA-AES128-SHA256 ♦ ♦
ECDHE-RSA-AES128-SHA256 ♦ ♦
525
Amazon API Gateway Developer Guide
Custom domain names
ECDHE-ECDSA-AES128-SHA ♦
ECDHE-RSA-AES128-SHA ♦
ECDHE-ECDSA-AES256-GCM- ♦ ♦
SHA384
ECDHE-RSA-AES256-GCM- ♦ ♦
SHA384
ECDHE-ECDSA-AES256-SHA384 ♦ ♦
ECDHE-RSA-AES256-SHA384 ♦ ♦
ECDHE-RSA-AES256-SHA ♦
ECDHE-ECDSA-AES256-SHA ♦
AES128-GCM-SHA256 ♦ ♦
AES128-SHA256 ♦ ♦
AES128-SHA ♦
AES256-GCM-SHA384 ♦ ♦
AES256-SHA256 ♦ ♦
AES256-SHA ♦
DES-CBC3-SHA ♦
ECDHE-RSA- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
AES128-GCM-
SHA256
ECDHE-RSA- TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
AES128-SHA256
ECDHE-RSA- TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
AES128-SHA
ECDHE-RSA- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
AES256-GCM-
SHA384
ECDHE-RSA- TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
AES256-SHA384
526
Amazon API Gateway Developer Guide
Custom domain names
ECDHE-RSA- TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
AES256-SHA
AES128-GCM- TLS_RSA_WITH_AES_128_GCM_SHA256
SHA256
AES256-GCM- TLS_RSA_WITH_AES_256_GCM_SHA384
SHA384
AES128-SHA256 TLS_RSA_WITH_AES_128_CBC_SHA256
AES256-SHA TLS_RSA_WITH_AES_256_CBC_SHA
AES128-SHA TLS_RSA_WITH_AES_128_CBC_SHA
DES-CBC3-SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA
RC4-MD5 TLS_RSA_WITH_RC4_128_MD5
527
Amazon API Gateway Developer Guide
Custom domain names
Note
The newly created custom domain name takes about 40 minutes to be ready. In the
meantime, you can configure the DNS record alias to map the custom domain name to the
associated CloudFront distribution domain name and to set up the base path mapping for
the custom domain name while the custom domain name is being initialized.
10. Next, you configure DNS records with your DNS provider to map the custom domain name to the
associated CloudFront distribution. For instructions for Amazon Route 53, see Routing traffic to an
Amazon API Gateway API by using your domain name in the Amazon Route 53 Developer Guide.
For most DNS providers, a 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 entered earlier in
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. For a zone apex you need to use an A-
record alias, provided that is supported by your DNS provider.
With Route 53 you can create an A record alias for your custom domain name and specify the
CloudFront distribution domain name as the alias target. This means that 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.
Use of A-record aliases also eliminates exposure of the underlying CloudFront distribution domain
name because the domain name mapping takes place solely within Route 53. For these reasons, we
recommend that you use Route 53 A-record alias whenever possible.
In addition to using the API Gateway console, you can use the API Gateway REST API, AWS CLI or one
of the AWS SDKs to set up the custom domain name for your APIs. As an illustration, the following
procedure outlines the steps to do so using the REST API calls.
To set up a custom domain name using the API Gateway REST API
1. Call domainname:create, specifying the custom domain name and the ARN of a certificate stored in
AWS Certificate Manager.
The successful API call returns a 201 Created response containing the certificate ARN as well as
the associated CloudFront distribution name in its payload.
2. Note the CloudFront distribution domain name shown in the output. You need it in the next step to
set the custom domain's CNAME value or A-record alias target in your DNS.
3. Follow the previous procedure to set up an A-record alias to map the custom domain name to its
CloudFront distribution name.
Region Account ID
us-east-1 392220576650
528
Amazon API Gateway Developer Guide
Custom domain names
Region Account ID
us-east-2 718770453195
us-west-1 968246515281
us-west-2 109351309407
ca-central-1 796887884028
eu-west-1 631144002099
eu-west-2 544388816663
eu-west-3 061510835048
eu-central-1 474240146802
eu-north-1 394634713161
ap-northeast-1 969236854626
ap-northeast-2 020402002396
ap-southeast-1 195145609632
ap-southeast-2 798376113853
ap-south-1 507069717855
ap-east-1 174803364771
sa-east-1 287228555773
me-south-1 855739686837
Configure base path mapping of an API with a custom domain name as its
hostname
You can use a single custom domain name as the hostname of multiple APIs. You achieve this by
configuring the base path mappings on the custom domain name. With the base path mappings, an API
under the custom domain is accessible through the combination of the custom domain name and the
associated base path.
For example, if you created an API named PetStore and another API named PetShop and set up a
custom domain name of api.example.com in API Gateway, you can set the PetStore API's URL as
https://api.example.com or https://api.example.com/myPetStore. The PetStore API is
associated with the base path of an empty string or myPetStore under the custom domain name of
api.example.com. Similarly, you can assign a base path of yourPetShop for the PetShop API. The
URL of https://api.example.com/yourPetShop is then the root URL of the PetShop API.
Before setting the base path for an API, complete the steps in Set up an edge-optimized custom domain
name for an API Gateway API (p. 527).
The following procedure sets up API mappings to map paths from your custom domain name to your API
stages.
529
Amazon API Gateway Developer Guide
Custom domain names
In addition, you can call the API Gateway REST API, AWS CLI, or one of the AWS SDKs to set up the base
path mapping of an API with a custom domain name as its hostname. As an illustration, the following
procedure outlines the steps to do so using the REST API calls.
To set up the base path mapping of an API using the API Gateway REST API
However, if you import a certificate into ACM and use it for a custom domain name, you must rotate
the certificate before it expires. This involves importing a new third-party certificate for the domain
name and rotate the existing certificate to the new one. You need to repeat the process when the
newly imported certificate expires. Alternatively, you can request ACM to issue a new certificate for the
domain name and rotate the existing one to the new ACM-issued certificate. After that, you can leave
ACM and CloudFront to handle the certificate rotation for you automatically. To create or import a new
ACM certificate, follow the steps to request or import a new ACM certificate (p. 521) for the specified
domain name.
To rotate a certificate for a domain name, you can use the API Gateway console, the API Gateway REST
API, AWS CLI, or one of the AWS SDKs.
To rotate an expiring certificate imported into ACM using the API Gateway console
To illustrate how to programmatically rotate an imported certificate for a custom domain name, we
outline the steps using the API Gateway REST API.
530
Amazon API Gateway Developer Guide
Custom domain names
• Call domainname:update action, specifying the ARN of the new ACM certificate for the specified
domain name.
The following examples compare and contrast a set of default URLs and corresponding custom URLs of
two APIs (udxjef and qf3duz) in a specified Region (us-east-1), and of a given custom domain name
(api.example.com).
API Gateway supports custom domain names for an API by using Server Name Indication (SNI). You can
invoke the API with a custom domain name using a browser or a client library that supports SNI.
API Gateway enforces SNI on the CloudFront distribution. For information on how CloudFront uses
custom domain names, see Amazon CloudFront Custom SSL.
531
Amazon API Gateway Developer Guide
Custom domain names
Important
For an API Gateway Regional custom domain name, you must request or import the certificate
in the same Region as your API.
When you create a Regional custom domain name (or migrate one) with an ACM certificate, API
Gateway creates a service-linked role in your account if the role doesn't exist already. The service-
linked role is required to attach your ACM certificate to your Regional endpoint. The role is named
AWSServiceRoleForAPIGateway and will have the APIGatewayServiceRolePolicy managed policy
attached to it. For more information about use of the service-linked role, see Using Service-Linked Roles.
Important
You must create a DNS record to point the custom domain name to the Regional domain name.
This enables the traffic that is bound to the custom domain name to be routed to the API's
Regional hostname. The DNS record can be the CNAME or "A" type.
Topics
• Set up a regional custom domain name with an ACM certificate using the API Gateway
console (p. 532)
• Set up a regional custom domain name with an ACM certificate using AWS CLI (p. 533)
Set up a regional custom domain name with an ACM certificate using the API
Gateway console
To use the API Gateway console to set up a Regional custom domain name, use the following procedure.
To set up a regional custom domain name using the API Gateway console
The following procedure sets up API mappings to map paths from your custom domain name to your API
stages.
To learn about setting basepath mappings for the custom domain, see Configure base path mapping of
an API with a custom domain name as its hostname (p. 529).
532
Amazon API Gateway Developer Guide
Custom domain names
Set up a regional custom domain name with an ACM certificate using AWS CLI
To use the AWS CLI to set up a custom domain name for a Regional API, use the following procedure.
1. Call create-domain-name, specifying a custom domain name and the ARN of a Regional
certificate.
Note that the specified certificate is from the us-west-2 Region and for this example, we assume
that the underlying API is from the same Region.
{
"ApiMappingSelectionExpression": "$request.basepath",
"DomainName": "regional.example.com",
"DomainNameConfigurations": [
{
"ApiGatewayDomainName": "d-id.execute-api.us-west-2.amazonaws.com",
"CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/id",
"DomainNameStatus": "AVAILABLE",
"EndpointType": "REGIONAL",
"HostedZoneId": "id",
"SecurityPolicy": "TLS_1_2"
}
]
}
The DomainNameConfigurations property value returns the Regional API's hostname. You must
create a DNS record to point your custom domain name to this Regional domain name. This enables
the traffic that is bound to the custom domain name to be routed to this Regional API's hostname.
2. Create a DNS record to associate the custom domain name and the Regional domain name. This
enables requests that are bound to the custom domain name to be routed to the API's Regional
hostname.
3. Add a base path mapping to expose the specified API (for example, 0qzs2sy7bh) in a
deployment stage (for example, test) under the specified custom domain name (for example,
regional.example.com).
As a result, the base URL using the custom domain name for the API that is deployed in the stage
becomes https://regional.example.com/myAPI.
4. Configure your DNS records to map the Regional custom domain name to its hostname of the
given hosted zone ID. First create a JSON file that contains the configuration for setting up a DNS
record for the Regional domain name. The following example shows how to create a DNS A record
to map a Regional custom domain name (regional.example.com) to its Regional hostname (d-
numh1z56v6.execute-api.us-west-2.amazonaws.com) provisioned as part of the custom
domain name creation. The DNSName and HostedZoneId properties of AliasTarget can take the
regionalDomainName and regionalHostedZoneId values, respectively, of the custom domain
533
Amazon API Gateway Developer Guide
Custom domain names
name. You can also get the Regional Route 53 Hosted Zone IDs in Amazon API Gateway Endpoints
and Quotas.
{
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "regional.example.com",
"Type": "A",
"AliasTarget": {
"DNSName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com",
"HostedZoneId": "Z2OJLYMUO9EFXC",
"EvaluateTargetHealth": false
}
}
}
]
}
where {your-hosted-zone-id} is the Route 53 Hosted Zone ID of the DNS record set in your
account. The change-batch parameter value points to a JSON file (setup-dns-record.json) in
a folder (path/to/your).
When planning the migration, remember that for an edge-optimized API's custom domain name, the
required certificate provided by ACM must be from the US East (N. Virginia) Region (us-east-1). This
certificate is distributed to all the geographic locations. However, for a Regional API, the ACM certificate
for the Regional domain name must be from the same Region hosting the API. You can migrate an edge-
optimized custom domain name that is not in the us-east-1 Region to a Regional custom domain
name by first requesting a new ACM certificate from the Region that is local to the API.
It may take up to 60 seconds to complete a migration between an edge-optimized custom domain name
and a Regional custom domain name in API Gateway. For the newly created endpoint to become ready to
accept traffic, the migration time also depends on when you update your DNS records.
Topics
• Migrate custom domain names using the AWS CLI (p. 534)
534
Amazon API Gateway Developer Guide
Custom domain names
Topics
• Migrate an edge-optimized custom domain name to regional (p. 535)
• Migrate a regional custom domain name to edge-optimized (p. 535)
To migrate an edge-optimized custom domain name to a Regional custom domain name, call the
update-domain-name CLI command, as follows:
The Regional certificate must be of the same Region as the Regional API.
The success response has a 200 OK status code and a body similar to the following:
{
"certificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/34a95aa1-77fa-427c-
aa07-3a88bd9f3c0a",
"certificateName": "edge-cert",
"certificateUploadDate": "2017-10-16T23:22:57Z",
"distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
"domainName": "api.example.com",
"endpointConfiguration": {
"types": [
"EDGE",
"REGIONAL"
]
},
"regionalCertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/
cd833b28-58d2-407e-83e9-dce3fd852149",
"regionalDomainName": "d-fdisjghyn6.execute-api.us-west-2.amazonaws.com"
}
For the migrated Regional custom domain name, the resulting regionalDomainName property returns
the Regional API hostname. You must set up a DNS record to point the Regional custom domain name to
this Regional hostname. This enables the traffic that is bound to the custom domain name to be routed
to the Regional host.
After the DNS record is set, you can remove the edge-optimized custom domain name by calling the
update-domain-name command of AWS CLI:
To migrate a Regional custom domain name to an edge-optimized custom domain name, call the
update-domain-name command of the AWS CLI, as follows:
535
Amazon API Gateway Developer Guide
Custom domain names
The success response has a 200 OK status code and a body similar to the following:
{
"certificateArn": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-
aa07-3a88bd9f3c0a",
"certificateName": "edge-cert",
"certificateUploadDate": "2017-10-16T23:22:57Z",
"distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
"domainName": "api.example.com",
"endpointConfiguration": {
"types": [
"EDGE",
"REGIONAL"
]
},
"regionalCertificateArn": "arn:aws:acm:us-
east-1:123456789012:certificate/3d881b54-851a-478a-a887-f6502760461d",
"regionalDomainName": "d-cgkq2qwgzf.execute-api.us-east-1.amazonaws.com"
}
For the specified custom domain name, API Gateway returns the edge-optimized API hostname as the
distributionDomainName property value. You must set a DNS record to point the edge-optimized
custom domain name to this distribution domain name. This enables traffic that is bound to the edge-
optimized custom domain name to be routed to the edge-optimized API hostname.
After the DNS record is set, you can remove the REGION endpoint type of the custom domain name:
The result of this command is similar to the following output, with only edge-optimized domain name
configuration data:
{
"certificateArn": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-
aa07-3a88bd9f3c0a",
"certificateName": "edge-cert",
"certificateUploadDate": "2017-10-16T23:22:57Z",
"distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
"domainName": "regional.haymuto.com",
"endpointConfiguration": {
"types": "EDGE"
}
}
536
Amazon API Gateway Developer Guide
Custom domain names
An API mapping specifies an API, a stage, and optionally a path to use for the mapping. For example, you
can map the production stage of an API to https://api.example.com/orders.
You can map HTTP and REST API stages to the same custom domain name.
Before you create an API mapping, you must have an API, a stage, and a custom domain name. To
learn more about creating a custom domain name, see the section called “Setting up a regional custom
domain name” (p. 531).
API Gateway routes requests to the API mapping that has the longest matching path. API Gateway
considers only the paths configured for API mappings, and not API routes, to select the API to invoke.
If no path matches the request, API Gateway sends the request to the API that you've mapped to the
empty path (none).
For example, consider a custom domain name https://api.example.com with the following API
mappings:
537
Amazon API Gateway Developer Guide
Custom domain names
Restrictions
• In an API mapping, the custom domain name and mapped APIs must be in the same AWS account.
• API mappings must contain only letters, numbers, and the following characters: $-_.+!*'()/.
• The maximum length for the path in an API mapping is 300 characters.
• You can only map HTTP APIs to a regional custom domain name with the TLS 1.2 security policy.
• You can't map WebSocket APIs to the same custom domain name as an HTTP API or REST API.
For example AWS Serverless Application Model templates that create all resources, see Sessions With
SAM on GitHub.
AWS CLI
The following AWS CLI command creates an API mapping. In this example, API Gateway sends
requests to api.example.com/v1/orders to the specified API and stage.
Note
To create API mappings with multiple levels, you must use apigatewayv2.
AWS CloudFormation
MyApiMapping:
Type: 'AWS::ApiGatewayV2::ApiMapping'
Properties:
DomainName: api.example.com
538
Amazon API Gateway Developer Guide
Optimize
ApiMappingKey: 'orders/v2/items'
ApiId: !Ref MyApi
Stage: !Ref MyStage
The following AWS CLI command disables the default endpoint for a REST API.
After you disable the default endpoint, you must deploy your API for the change to take effect.
Topics
• Enabling API caching to enhance responsiveness (p. 539)
• Enabling payload compression for an API (p. 544)
When you enable caching for a stage, API Gateway caches responses from your endpoint for a specified
time-to-live (TTL) period, in seconds. API Gateway then responds to the request by looking up the
endpoint response from the cache instead of making a request to your endpoint. The default TTL value
for API caching is 300 seconds. The maximum TTL value is 3600 seconds. TTL=0 means caching is
disabled.
The maximum size of a response that can be cached is 1048576 bytes. Cache data encryption may
increase the size of the response when it is being cached.
539
Amazon API Gateway Developer Guide
Cache settings
This is a HIPAA Eligible Service. For more information about AWS, U.S. Health Insurance Portability and
Accountability Act of 1996 (HIPAA), and using AWS services to process, store, and transmit protected
health information (PHI), see HIPAA Overview.
Important
When you enable caching for a stage, only GET methods have caching enabled by default.
This helps to ensure the safety and availability of your API. You can enable caching for other
methods by overriding method settings (p. 541).
Important
Caching is charged by the hour and is not eligible for the AWS Free Tier.
When you enable caching, you must choose a cache capacity. In general, a larger capacity gives a better
performance, but also costs more.
API Gateway enables caching by creating a dedicated cache instance. This process can take up to 4
minutes.
API Gateway changes caching capacity by removing the existing cache instance and creating a new one
with a modified capacity. All existing cached data is deleted.
Note
The cache capacity affects the CPU, memory, and network bandwidth of the cache instance. As a
result, the cache capacity can affect the performance of your cache.
API Gateway recommends that you run a 10-minute load test to verify that your cache capacity
is appropriate for your workload. Ensure that traffic during the load test mirrors production
traffic. For example, include ramp up, constant traffic, and traffic spikes. The load test should
include responses that can be served from the cache, as well as unique responses that add items
to the cache. Monitor the latency, 4xx, 5xx, cache hit, and cache miss metrics during the load
test. Adjust your cache capacity as needed based on these metrics.
In the API Gateway console, you configure caching in the Settings tab of a named Stage Editor.
Note
Creating or deleting a cache takes about 4 minutes for API Gateway to complete. When a 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, only GET methods are cached. To ensure the
safety and availability of your API, we recommend that you don't change this setting. However, you can
enable caching for other methods by overriding method settings (p. 541).
If you would like to verify if caching is functioning as expected, you have two general options:
540
Amazon API Gateway Developer Guide
Cache settings
• 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.
If you anticipate that a method that you are caching will receive sensitive data in its responses, in Cache
Settings, choose Encrypt cache data.
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 are 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:
541
Amazon API Gateway Developer Guide
Cache settings
...
The response from this request is cached and is 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.
To flush the API stage cache, you can choose the Flush entire cache button under the Cache Settings
section in the Settings tab in a stage editor of the API Gateway console. The cache-flushing operation
takes a couple of minutes, after which the cache status is AVAILABLE immediately after flushing.
Note
After the cache is flushed, responses are serviced from the integration endpoint until the cache
is built up again. During this period, the number of requests sent to the integration endpoint
may increase. This may temporarily increase the overall latency of your API.
542
Amazon API Gateway Developer Guide
Cache settings
To grant permission for a client, attach a policy of the following format to an IAM execution role for the
user.
Note
Cross-account cache invalidation is not supported.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:InvalidateCache"
],
"Resource": [
"arn:aws:execute-api:region:account-id:api-id/stage-name/GET/resource-path-
specifier"
]
}
]
}
This policy allows the API Gateway execution service to invalidate the 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 Control access to an API with IAM
permissions (p. 290).
If you don't impose an InvalidateCache policy (or choose the Require authorization check box in the
console), any client can invalidate the API cache. If most or all of the clients invalidate the API cache, this
could significantly increase the latency of 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.
543
Amazon API Gateway Developer Guide
Content encoding
• Fail the request with 403 status code: returns a 403 Unauthorized response.
544
Amazon API Gateway Developer Guide
Content encoding
If you want the compression applied on a payload of any size, set the minimumCompressionSize
value to zero. However, compressing data of a small size might actually increase the final data size.
Furthermore, compression in API Gateway and decompression in the client might increase overall latency
and require more computing times. You should run test cases against your API to determine an optimal
value.
The client can submit an API request with a compressed payload and an appropriate Content-
Encoding header for API Gateway to decompress the method request payload and apply applicable
mapping templates, before passing the request to the integration endpoint. After the compression is
enabled and the API is deployed, the client can receive an API response with a compressed payload if it
specifies an appropriate Accept-Encoding header in the method request.
When the integration endpoint expects and returns uncompressed JSON payloads, any mapping
template that's configured for an uncompressed JSON payload is applicable to the compressed payload.
For a compressed method request payload, API Gateway decompresses the payload, applies the mapping
template, and passes the mapped request to the integration endpoint. For an uncompressed integration
response payload, API Gateway applies the mapping template, compresses the mapped payload, and
returns the compressed payload to the client.
Topics
• Enable payload compression for an API (p. 545)
• Call an API method with a compressed payload (p. 547)
• Receive an API response with a compressed payload (p. 547)
For an existing API, you must deploy the API after enabling the compression in order for the change to
take effect. For a new API, you can deploy the API after the API setup is complete.
Note
The highest-priority content encoding must be one supported by API Gateway. If it is not,
compression is not applied to the response payload.
Topics
• Enable payload compression for an API using the API Gateway console (p. 545)
• Enable payload compression for an API using AWS CLI (p. 546)
• Content codings supported by API Gateway (p. 546)
Enable payload compression for an API using the API Gateway console
The following procedure describes how to enable payload compression for an API.
545
Amazon API Gateway Developer Guide
Content encoding
3. In the primary navigation pane, choose Settings under the API you chose or the one you created.
4. Under the Content Encoding section in the Settings pane, select the Content Encoding enabled
option to enable payload compression. Enter a number for the minimum compression size (in
bytes) next to Minimum body size required for compression. To disable the compression, clear the
Content Encoding enabled option.
5. Choose Save Changes.
To use the AWS CLI to create a new API and enable compression, call the create-rest-api command
as follows:
To use the AWS CLI to enable compression on an existing API, call the update-rest-api command as
follows:
The minimumCompressionSize property has a non-negative integer value between 0 and 10485760
(10M bytes). It measures the compression threshold. If the payload size is smaller than this value,
compression or decompression are not applied on the payload. Setting it to zero allows compression for
any payload size.
To use the AWS CLI to disable compression, call the update-rest-api command as follows:
You can also set value to an empty string "" or omit the value property altogether in the preceding
call.
• deflate
• gzip
• identity
API Gateway also supports the following Accept-Encoding header format, according to the RFC 7231
specification:
• Accept-Encoding:deflate,gzip
• Accept-Encoding:
• Accept-Encoding:*
• Accept-Encoding:deflate;q=0.5,gzip;q=1.0
546
Amazon API Gateway Developer Guide
Content encoding
• Accept-Encoding:gzip;q=1.0,identity;q=0.5,*;q=0
Suppose that you're an API client and want to call the PetStore API method (POST /pets). Don't call the
method by using the following JSON output:
POST /pets
Host: {petstore-api-id}.execute-api.{region}.amazonaws.com
Content-Length: ...
{
"type": "dog",
"price": 249.99
}
Instead, you can call the method with the same payload compressed by using the GZIP coding:
POST /pets
Host: {petstore-api-id}.execute-api.{region}.amazonaws.com
Content-Encoding:gzip
Content-Length: ...
###RPP*#,HU#RPJ#OW##e&###L,#,-y#j
When API Gateway receives the request, it verifies if the specified content coding is supported. Then,
it attempts to decompress the payload with the specified content coding. If the decompression
is successful, it dispatches the request to the integration endpoint. If the specified coding isn't
supported or the supplied payload isn't compressed with specified coding, API Gateway returns the 415
Unsupported Media Type error response. The error is not logged to CloudWatch Logs, if it occurs in
the early phase of decompression before your API and stage are identified.
API Gateway only compresses the response payload when the following conditions are satisfied:
• The incoming request has the Accept-Encoding header with a supported content coding and
format.
Note
If the header is not set, the default value is * as defined in RFC 7231. In such a case, API
Gateway does not compress the payload. Some browser or client may add Accept-Encoding
(for example, Accept-Encoding:gzip, deflate, br) automatically to compression-
enabled requests. This can trigger the payload compression in API Gateway. Without an
explicit specification of supported Accept-Encoding header values, API Gateway does not
compress the payload.
• The minimumCompressionSize is set on the API to enable compression.
• The integration response doesn't have a Content-Encoding header.
• The size of an integration response payload, after the applicable mapping template is applied, is
greater than or equal to the specified minimumCompressionSize value.
547
Amazon API Gateway Developer Guide
Distribute
API Gateway applies any mapping template that's configured for the integration response before
compressing the payload. If the integration response contains a Content-Encoding header,
API Gateway assumes that the integration response payload is already compressed and skips the
compression processing.
GET /pets
Host: {petstore-api-id}.execute-api.{region}.amazonaws.com
Accept: application/json
The backend responds to the request with an uncompressed JSON payload that's similar to the
following:
200 OK
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
To receive this output as a compressed payload, your API client can submit a request as follows:
GET /pets
Host: {petstore-api-id}.execute-api.{region}.amazonaws.com
Accept-Encoding:gzip
The client receives the response with a Content-Encoding header and GZIP-encoded payload that are
similar to the following:
200 OK
Content-Encoding:gzip
...
###RP#
J#)JV
#:P^IeA*######+(#L #X#YZ#ku0L0B7!9##C##&####Y##a###^#X
When the response payload is compressed, only the compressed data size is billed for data transfer.
548
Amazon API Gateway Developer Guide
Usage plans
applications, documenting your API so customers know how to call it from their client applications,
making your API discoverable in a developer portal, and making your API available as part of product
offerings.
Topics
• Creating and using usage plans with API keys (p. 549)
• Documenting REST APIs (p. 562)
• Generating an SDK for a REST API in API Gateway (p. 604)
• Use the serverless developer portal to catalog your API Gateway APIs (p. 620)
• Sell your API Gateway APIs through AWS Marketplace (p. 627)
API keys are alphanumeric string values that you distribute to application developer customers to
grant access to your API. You can use API keys together with Lambda authorizers (p. 299), IAM
roles (p. 290), or Amazon Cognito (p. 315) to control access to your APIs. API Gateway can generate
API keys on your behalf, or you can import them from a CSV file (p. 562). You can generate an API key
in API Gateway, or import it into API Gateway from an external source. For more information, see the
section called “Set up API keys using the API Gateway console” (p. 552).
An API key has a name and a value. (The terms "API key" and "API key value" are often used
interchangeably.) The value is an alphanumeric string between 30 and 128 characters, for example,
apikey1234abcdefghij0123456789.
Important
API key values must be unique. If you try to create two API keys with different names and the
same value, API Gateway considers them to be the same API key.
An API key can be associated with more than one usage plan. A usage plan can be associated
with more than one stage. However, a given API key can only be associated with one usage plan
for each stage of your API.
A throttling limit sets the target point at which request throttling should start. This can be set at the API
or API method level.
A quota limit sets the target maximum number of requests with a given API key that can be submitted
within a specified time interval. You can configure individual API methods to require API key
authorization based on usage plan configuration.
Throttling and quota limits apply to requests for individual API keys that are aggregated across all API
stages within a usage plan.
Note
Usage plan throttling and quotas are not hard limits, and are applied on a best-effort basis.
In some cases, clients can exceed the quotas that you set. Don’t rely on usage plan quotas or
549
Amazon API Gateway Developer Guide
Usage plans
throttling to control costs or block access to an API. Consider using AWS Budgets to monitor
costs and AWS WAF to manage API requests.
• Don't rely on API keys as your only means of authentication and authorization for your APIs. If you
have multiple APIs in a usage plan, a user with a valid API key for one API in that usage plan can access
all APIs in that usage plan. Instead, use an IAM role, a Lambda authorizer (p. 299), or an Amazon
Cognito user pool (p. 315).
• If you're using a developer portal (p. 620) to publish your APIs, note that all APIs in a given usage
plan are subscribable, even if you haven't made them visible to your customers.
• In some cases, clients can exceed the quotas that you set. Don’t rely on usage plans to control costs.
Consider using AWS Budgets to monitor costs and AWS WAF to manage API requests.
1. Create one or more APIs, configure the methods to require an API key, and deploy the APIs to stages.
2. Generate or import API keys to distribute to application developers (your customers) who will be
using your API.
3. Create the usage plan with the desired throttle and quota limits.
4. Associate API stages and API keys with 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 include API methods in a usage plan, you must configure individual API methods to require
an API key (p. 552). For user authentication and authorization, don't use API keys. Use an IAM
role, a Lambda authorizer (p. 299), or an Amazon Cognito user pool (p. 315).
Your API Gateway API can receive API keys from one of two sources:
HEADER
You distribute API keys to your customers and require them to pass the API key as the X-API-Key
header of each incoming request.
AUTHORIZER
You have a Lambda authorizer return the API key as part of the authorization response. For more
information on the authorization response, see the section called “Output from an Amazon API
Gateway Lambda authorizer” (p. 309).
550
Amazon API Gateway Developer Guide
Usage plans
To choose an API key source for an API by using the API Gateway console:
To choose an API key source for an API by using the AWS CLI, call the update-rest-api command as
follows:
To have the client submit an API key, set the value to HEADER in the preceding CLI command.
To choose an API key source for an API by using the API Gateway REST API, call restapi:update as
follows:
{
"patchOperations" : [
{
"op" : "replace",
"path" : "/apiKeySource",
"value" : "HEADER"
}
]
}
To have an authorizer return an API key, set the value to AUTHORIZER in the previous
patchOperations input.
Depending on the API key source type you choose, use one of the following procedures to use header-
sourced API keys or authorizer-returned API keys in method invocation:
1. Create an API with desired API methods. And deploy the API to a stage.
2. Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan.
Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API
key value.
3. Set up API methods to require an API key.
4. Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the
usage plan to attach the new API stage.
The client can now call the API methods while supplying the x-api-key header with the chosen API key
as the header value.
551
Amazon API Gateway Developer Guide
Usage plans
1. Create an API with desired API methods. And deploy the API to a stage.
2. Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan.
Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API
key value.
3. Create a custom Lambda authorizer of the token type. Include, as a root-level property of the
authorization response, usageIdentifierKey:{api-key}, where {api-key} stands for the API
key value mentioned in the previous step.
4. Set up API methods to require an API key and enable the Lambda authorizer on the methods as well.
5. Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the
usage plan to attach the new API stage.
The client can now call the API key-required methods without explicitly supplying any API key. The
authorizer-returned API key is used automatically.
Before setting up API keys, you must have created an API and deployed it to a stage.
For instructions on how to create and deploy an API by using the API Gateway console, see Creating a
REST API in Amazon API Gateway (p. 242) and Deploying a REST API in Amazon API Gateway (p. 490),
respectively.
Topics
• Require API key on a method (p. 552)
• Create an API key (p. 553)
• Import API keys (p. 554)
1. Sign in to the AWS Management Console and open the API Gateway console at https://
console.aws.amazon.com/apigateway/.
2. Choose a REST API.
3. In the API Gateway main navigation pane, choose Resources.
4. Under Resources, create a new method or choose an existing one.
5. Choose Method Request.
6. Under the Settings section, choose true for API Key Required.
7. Select the checkmark icon to save the settings.
8. Deploy or redeploy the API for the requirement to take effect.
552
Amazon API Gateway Developer Guide
Usage plans
If the API Key Required option is set to false and you don't execute the previous steps, any API key
that's associated with an API stage isn't used for the method.
1. Sign in to the AWS Management Console and open the API Gateway console at https://
console.aws.amazon.com/apigateway/.
2. Choose a REST API.
3. In the API Gateway main navigation pane, choose API Keys.
4. From the Actions drop-down menu, choose Create API key.
a. Enter an API key name (for example, MyFirstKey) in the Name input field.
b. Choose Auto Generate to have API Gateway generate the key value, or choose Custom to enter
the key manually.
c. Choose Save.
553
Amazon API Gateway Developer Guide
Usage plans
1. Sign in to the AWS Management Console and open the API Gateway console at https://
console.aws.amazon.com/apigateway/.
2. Choose a REST API.
3. In the main navigation pane, choose API Keys.
4. From the Actions drop-down menu, choose Import API keys.
5. To load a comma-separated key file, choose Select CSV File. You can also enter the keys
manually. For information about the file format, see the section called “API Gateway API key file
format” (p. 562).
6. Choose Fail on warnings to stop the import when there's an error, or choose Ignore warnings to
continue to import valid key entries when there's an error.
7. To start importing the selected API keys, choose Import.
Now that you've set up the API key, you can proceed to create and use a usage plan (p. 554).
Create, configure, and test usage plans with the API Gateway
console
Before creating a usage plan, make sure that you've set up the desired API keys. For more information,
see Set up API keys using the API Gateway console (p. 552).
This section describes how to create and use a usage plan by using the API Gateway console.
554
Amazon API Gateway Developer Guide
Usage plans
Topics
• Migrate your API to default usage plans (if needed) (p. 555)
• Create a usage plan (p. 555)
• Test a usage plan (p. 557)
• Maintain a usage plan (p. 557)
If you started to use API Gateway before that date, you might need to migrate to default usage plans.
You'll be prompted with the Enable Usage Plans option before using usage plans for the first time in the
selected Region. When you enable this option, you have default usage plans created for every unique
API stage that's associated with existing API keys. In the default usage plan, no throttle or quota limits
are set initially, and the associations between the API keys and API stages are copied to the usage plans.
The API behaves the same as before. However, you must use the UsagePlan apiStages property to
associate specified API stage values (apiId and stage) with included API keys (via UsagePlanKey),
instead of using the ApiKey stageKeys property.
To check whether you've already migrated to default usage plans, use the get-account CLI command.
In the command output, the features list includes an entry of "UsagePlans" when usage plans are
enabled.
You can also migrate your APIs to default usage plans by using the AWS CLI as follows:
[
{
"op": "add",
"path": "/features",
"value": "UsagePlans"
}
]
1. In the Amazon API Gateway main navigation pane, choose Usage Plans, and then choose Create.
2. Under Create Usage Plan, do the following:
a. For Name, enter a name for your plan (for example, Plan_A).
b. For Description, enter a description for your plan.
c. Select Enable throttling, and set Rate (for example, 100) and Burst (for example, 200).
d. Choose Enable quota, and set specify a value (for example, 5000) for a selected time interval
(for example, Month).
e. Choose Next.
555
Amazon API Gateway Developer Guide
Usage plans
3. To add a stage to the plan, do the following in the Associated API Stages pane:
556
Amazon API Gateway Developer Guide
Usage plans
e. Set Rate (requests per second) (for example, 100) and Burst (for example, 200).
f. Choose the checkmark icon to save.
g. Choose Close.
5. To add a key to the plan, do the following in the API Keys tab:
Note
Alternatively, to create a new API key and add it to the usage plan, choose Create API Key
and add to Usage Plan and follow the instructions.
Note
An API key can be associated with more than one usage plan. A usage plan can be
associated with more than one stage. However, a given API key can only be associated with
one usage plan for each stage of your API.
6. To finish creating the usage plan, choose Done.
7. If you want to add more API stages to the usage plan, choose Add API Stage to repeat the preceding
steps.
557
Amazon API Gateway Developer Guide
Usage plans
{
"thisPeriod": {
"px1KW6...qBazOJH": [
[
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 hasn't used any allotted quotas
yet, and the API owner or administrator has reduced the remaining quota from 5000 to 10 on the
third day.
Before setting up API keys, you must have created an API and deployed it to a stage.
558
Amazon API Gateway Developer Guide
Usage plans
For the REST API calls to create and deploy an API, see restapi:create and deployment:create,
respectively.
Topics
• Require an API key on a method (p. 559)
• Create or import API keys (p. 559)
• Call method:put to create a method. Set apiKeyRequired to true in the request payload.
• Call method:update to set apiKeyRequired to true.
With the API key created, you can now proceed to Create, configure, and test usage plans using the API
Gateway CLI and REST API (p. 559).
Create, configure, and test usage plans using the API Gateway
CLI and REST API
Before configuring a usage plan, you must have already done the following: set up methods of a selected
API to require API keys, deployed or redeployed the API to a stage, and created or imported one or more
API keys. For more information, see Set up API keys using the API Gateway REST API (p. 558).
To configure a usage plan by using the API Gateway REST API, use the following instructions, assuming
that you've already created the APIs to be added to the usage plan.
Topics
• Migrate to default usage plans (p. 559)
• Create a usage plan (p. 560)
• Manage a usage plan by using the AWS CLI (p. 560)
• Test usage plans (p. 561)
{
"patchOperations" : [ {
"op" : "add",
"path" : "/features",
"value" : "UsagePlans"
} ]
}
559
Amazon API Gateway Developer Guide
Usage plans
For more information about migrating API stages associated with API keys, see Migrate to Default Usage
Plans in the API Gateway Console (p. 555).
1. Call usageplan:create to create a usage plan. In the payload, specify the name and description of
the plan, associated API stages, rate limits, and quotas.
Make note of the resultant usage plan identifier. You need it in the next step.
2. Do one of the following:
a. Call usageplankey:create to add an API key to the usage plan. Specify keyId and keyType
in the payload.
To add more API keys to the usage plan, repeat the previous call, one API key at a time.
b. 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 that the keys are enabled for the usage plan, and, possibly, the API key names
and descriptions.
The following example of the apikey:import request adds three API keys (as identified by
key, name, and description) to one usage plan (as identified by usageplanIds):
As a result, three UsagePlanKey resources are 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').
Note
An API key can be associated with more than one usage plan. A usage plan can be
associated with more than one stage. However, a given API key can only be associated
with one usage plan for each stage of your API.
To add or replace a rate limit for throttling an individual resource and method:
560
Amazon API Gateway Developer Guide
Usage plans
To add or replace a burst limit for throttling an individual resource and method:
To remove the method-level throttling settings for an individual resource and method:
• Make a GET request on the Pets resource (/pets), with the ?type=...&page=... query
parameters, of the API (for example, xbvxlpijch) in a usage plan:
Note
You must submit this request to the execute-api component of API Gateway and provide
the required API key (for example, Hiorr45VR...c4GJc) in the required x-api-key
header.
The successful response returns a 200 OK status code and a payload that contains the requested
results from the backend. If you forget to set the x-api-key header or set it with an incorrect key,
561
Amazon API Gateway Developer Guide
API documentation
you get a 403 Forbidden response. However, if you didn't configure the method to require an API
key, you will likely 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.
Occasionally, when an internal error occurs where API Gateway is unable to enforce usage plan
throttling limits or quotas for the request, API Gateway serves the request without applying the
throttling limits or quotas as specified in the usage plan. But, it logs an error message of Usage
Plan check failed due to an internal error in CloudWatch. You can ignore such
occasional errors.
Key,name
apikey1234abcdefghij0123456789,MyFirstApiKey
An API key file can also have the Description, Enabled, or UsagePlanIds column, as shown in the
following example:
Name,key,description,Enabled,usageplanIds
MyFirstApiKey,apikey1234abcdefghij0123456789,An imported key,TRUE,c7y23b
When a key is associated with more than one usage plan, the UsagePlanIds value is a comma-
separated 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 are 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.
To document your API, you can call the API Gateway REST API, use one of the AWS SDKs or AWS CLIs for
API Gateway, or use the API Gateway console. In addition, you can import or export the documentation
parts that are defined in an external OpenAPI file. Before explaining how to document your API, we show
how API documentation is represented in API Gateway.
Topics
562
Amazon API Gateway Developer Guide
API documentation
Topics
• Documentation parts (p. 563)
• Documentation versions (p. 570)
Documentation parts
A DocumentationPart resource is a JSON object that stores the documentation content applicable to an
individual API entity. Its properties field contains the documentation content as a map of key-value
pairs. Its location property identifies the associated API entity.
The shape of a content map is determined by you, the API developer. The value of a key-value pair
can be a string, number, boolean, object, or array. The shape of the location object depends on the
targeted entity type.
The location property of a DocumentationPart instance identifies an API entity to which the associated
content applies. The API entity can be an API Gateway REST API resource, such as RestApi, Resource,
Method, MethodResponse, Authorizer, or Model. The entity can also be a message parameter, such as
a URL path parameter, a query string parameter, a request or response header parameter, a request or
response body, or response status code.
To specify an API entity, set the type attribute of the location object to be one of API,
AUTHORIZER, MODEL, RESOURCE, METHOD, PATH_PARAMETER, QUERY_PARAMETER, REQUEST_HEADER,
REQUEST_BODY, RESPONSE, RESPONSE_HEADER, or RESPONSE_BODY.
Depending on the type of an API entity, you might specify other location attributes, including
method, name, path, and statusCode. Not all of these attributes are valid for a given API entity. For
example, type, path, name, and statusCode are valid attributes of the RESPONSE entity; only type
563
Amazon API Gateway Developer Guide
API documentation
and path are valid location attributes of the RESOURCE entity. It is an error to include an invalid field in
the location of a DocumentationPart for a given API entity.
Not all valid location fields are required. For example, type is both the valid and required location
field of all API entities. However, method, path, and statusCode are valid but not required attributes
for the RESPONSE entity. When not explicitly specified, a valid location field assumes its default
value. The default path value is /, i.e., the root resource of an API. The default value of method, or
statusCode is *, meaning any method, or status code values, respectively.
{
"info": {
"description": "My first API with Amazon API Gateway."
},
"x-custom-info" : "My custom info, recognized by OpenAPI.",
"my-info" : "My custom info not recognized by OpenAPI."
}
Although API Gateway accepts any valid JSON string as the content map, the content attributes are
treated as two categories: those that can be recognized by OpenAPI and those that cannot. In the
preceding example, info, description, and x-custom-info are recognized by OpenAPI as a standard
OpenAPI object, property, or extension. In contrast, my-info is not compliant with the OpenAPI
specification. API Gateway propagates OpenAPI-compliant content attributes into the API entity
definitions from the associated DocumentationPart instances. API Gateway does not propagate the
non-compliant content attributes into the API entity definitions.
{
"location" : {
"type" : "RESOURCE",
"path": "/pets"
},
"properties" : {
"summary" : "The /pets resource represents a collection of pets in PetStore.",
"description": "... a child resource under the root...",
}
}
Here, both type and path are valid fields to identify the target of the RESOURCE type. For the root
resource (/), you can omit the path field.
{
"location" : {
"type" : "RESOURCE"
},
"properties" : {
"description" : "The root resource with the default path specification."
}
}
{
"location" : {
564
Amazon API Gateway Developer Guide
API documentation
"type" : "RESOURCE",
"path": "/"
},
"properties" : {
"description" : "The root resource with an explicit path specification"
}
}
The default value of an optional location field provides a patterned description of an API entity. Using
the default value in the location object, you can add a general description in the properties map
to a DocumentationPart instance with this type of location pattern. API Gateway extracts the
applicable OpenAPI documentation attributes from the DocumentationPart of the generic API entity
and injects them into a specific API entity with the location fields matching the general location
pattern, or matching the exact value, unless the specific entity already has a DocumentationPart
instance associated with it. This behavior is also known as content inheritance from an API entity of more
general specifications.
Content inheritance does not apply to certain API entity types. See the table below for details.
When an API entity matches more than one DocumentationPart's location pattern, the entity will
inherit the documentation part with the location fields of the highest precedence and specificities. The
order of precedence is path > statusCode. For matching with the path field, API Gateway chooses the
entity with the most specific path value. The following table shows this with a few examples.
1 /pets * id Documentation
associated
with
this
location
pattern
will
be
inherited
by
entities
matching
the
location
pattern.
565
Amazon API Gateway Developer Guide
API documentation
3 /pets/ * id Documentation
petId associated
with
this
location
pattern
will
be
inherited
by
entities
matching
the
location
pattern
when
Cases
1, 2,
and
3 are
matched,
because
Case
3
has a
higher
precedence
than
Case
2 and
is
more
specific
than
Case
1.
566
Amazon API Gateway Developer Guide
API documentation
Here is another example to contrast a more generic DocumentationPart instance to a more specific
one. The following general error message of "Invalid request error" is injected into the OpenAPI
definitions of the 400 error responses, unless overridden.
{
"location" : {
"type" : "RESPONSE",
"statusCode": "400"
},
"properties" : {
"description" : "Invalid request error."
}"
}
With the following overwrite, the 400 responses to any methods on the /pets resource has a
description of "Invalid petId specified" instead.
{
"location" : {
"type" : "RESPONSE",
"path": "/pets",
"statusCode": "400"
},
"properties" : "{
"description" : "Invalid petId specified."
}"
}
567
Amazon API Gateway Developer Guide
API documentation
568
Amazon API Gateway Developer Guide
API documentation
569
Amazon API Gateway Developer Guide
API documentation
Documentation versions
A documentation version is a snapshot of the DocumentationParts collection of an API and is tagged
with a version identifier. Publishing the documentation of an API involves creating a documentation
version, associating it with an API stage, and exporting that stage-specific version of the API
documentation to an external OpenAPI file. In API Gateway, a documentation snapshot is represented as
a DocumentationVersion resource.
As you update an API, you create new versions of the API. In API Gateway, you maintain all the
documentation versions using the DocumentationVersions collection.
A prerequisite for creating and editing the documentation of an API is that you must have already
created the API. In this section, we use the PetStore API as an example. To create an API using the API
Gateway console, follow the instructions in Tutorial: Create a REST API by importing an example (p. 46).
Topics
• Document the API entity (p. 571)
• Document a RESOURCE entity (p. 573)
• Document a METHOD entity (p. 573)
• Document a QUERY_PARAMETER entity (p. 574)
• Document a PATH_PARAMETER entity (p. 575)
• Document a REQUEST_HEADER entity (p. 575)
• Document a REQUEST_BODY entity (p. 576)
• Document a RESPONSE entity (p. 576)
• Document a RESPONSE_HEADER entity (p. 576)
• Document a RESPONSE_BODY entity (p. 577)
570
Amazon API Gateway Developer Guide
API documentation
If a documentation part was not created for the API, you get the documentation part's properties
map editor. Type the following properties map in the text editor and then choose Save to create the
documentation part.
{
"info": {
"description": "Your first API Gateway API.",
"contact": {
"name": "John Doe",
"email": "[email protected]"
}
}
}
Note
You do not need to encode the properties map into a JSON string. The API Gateway console
stringifies the JSON object for you.
571
Amazon API Gateway Developer Guide
API documentation
If a documentation part has already been created, you first get the properties map viewer, as shown in
the following.
572
Amazon API Gateway Developer Guide
API documentation
If no documentation part was created for this entity, you get the Documentation window. Type a valid
properties map in the editor. Then choose Save and Close.
{
"description": "The PetStore's root resource."
}
If a documentation part has already been defined for the RESOURCE entity, you get the documentation
viewer. Choose Edit to open the Documentation editor. Modify the existing properties map. Choose
Save and then choose Close.
If necessary, repeat these steps to add a documentation part to other RESOURCE entities.
573
Amazon API Gateway Developer Guide
API documentation
For the new documentation part, type the following properties map in the Documentation editor in
the Documentation window. Then choose Save and Close.
{
"tags" : [ "pets" ],
"description" : "PetStore HTML web page containing API usage information"
}
For the existing documentation, choose Edit from the Documentation viewer. Edit the documentation
content in the Documentation editor and choose Save. Choose Close.
From the Documentation viewer, you can also delete the documentation part.
Alternatively, you can choose Documentation under the PetStore API from the main navigation pane.
Then choose Query Parameter for Type. For the PetStore example API, this shows the documentation
parts for the page and type query parameters.
574
Amazon API Gateway Developer Guide
API documentation
For an API with query parameters defined for other methods, you can filter your selection by specifying
the path of the affected resource for Path, choosing the desired HTTP method from Method, or typing
the query parameter name in Name.
For example, choose the page query parameter. Choose Edit to modify the existing documentation.
Choose Save to save the change.
To add a new documentation part for a QUERY_PARAMETER entity, choose Create Documentation Part.
Choose Query Parameter for Type. Type a resource path (e.g., /pets) in Path. Choose an HTTP verb
(e.g., GET) for Method. Type a properties description in the text editor. Then choose Save.
If necessary, repeat these steps to add a documentation part to other request query parameters.
Alternatively, choose Documentation under the PetStore API from the main navigation pane. Choose
Path Parameter for Type. Choose Edit on a path parameter from the list. Modify the content and then
choose Save.
To add documentation for a path parameter not listed, choose Create Documentation Part. Choose
Path Parameter for Type. Set a resource path in Path, choose a method from Method, and set a path
parameter name in Name. Add the documentation's properties and choose Save.
If required, repeat these steps to add or edit a documentation part to other path parameters.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose
Request Header for Type. Choose Edit on a listed request header to change the documentation. To
add documentation for an unlisted request header, choose Create Documentation Part. Choose Request
575
Amazon API Gateway Developer Guide
API documentation
Header for Type. Specify a resource path in Path. Choose a method for Method. Type a header name in
Name. Then add and save a properties map.
If required, repeat these steps to add or edit a documentation part to other request headers.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose
Request Body for Type. Choose Edit on a listed request body to change the documentation. To add
documentation for an unlisted request body, choose Create Documentation Part. Choose Request
Body for Type. Set a resource path in Path. Choose an HTTP verb for Method. Then add and save a
properties map.
If required, repeat these steps to add or edit a documentation part to other request bodies.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose
Response (status code) for Type. Choose Edit on a listed response of a specified HTTP status code
to change the documentation. To add documentation for an unlisted response body, choose Create
Documentation Part. Choose Response (status code) for Type. Set a resource path in Path. Choose an
HTTP verb for Method. Type an HTTP status code in Status Code. Then add and save the documentation
part properties.
If required, repeat these steps to add or edit a documentation part to other responses.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose
Response Header for Type. Choose Edit on a listed response header to change the documentation.
To add documentation for an unlisted response header, choose Create Documentation Part. Choose
Response Header for Type. Set a resource path in Path. Choose an HTTP verb for Method. Type an
HTTP status code in Status Code. Type the response header name in Name. Then add and save the
documentation part properties.
576
Amazon API Gateway Developer Guide
API documentation
If required, repeat these steps to add or edit a documentation part to other response headers.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose
Response Body for Type. Choose Edit on a listed response body to change the documentation. To add
documentation for an unlisted response body, choose Create Documentation Part. Choose Response
Body for Type. Set a resource path in Path. Choose an HTTP verb for Method. Type an HTTP status code
in Status Code. Then add and save the documentation part properties.
If required, repeat these steps to add or edit a documentation part to other response bodies.
{
"$schema" : "http://json-schema.org/draft-04/schema#",
"title" : "Error Schema",
"type" : "object",
"properties" : {
"message" : { "type" : "string" }
}
}
and requires two DocumentationPart instances, one for the Model and the other for its message
property:
{
"location": {
"type": "MODEL",
"name": "Error"
},
"properties": {
"title": "Error Schema",
"description": "A description of the Error model"
}
}
and
{
"location": {
"type": "MODEL",
"name": "Error.message"
},
"properties": {
"description": "An error message."
}
}
When the API is exported, the DocumentationPart's properties will override the values in the original
schema.
577
Amazon API Gateway Developer Guide
API documentation
To add or edit documentation for a model, go to Models of the API in the main navigation pane. Choose
the book icon for the name of a listed model to open the Documentation viewer and then editor. Add or
modify the properties of the documentation part.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose Model
for Type. Choose Edit on a listed model to change the documentation. To add documentation for an
unlisted model, choose Create Documentation Part. Choose Model for Type. Give a name to the model
in Name. Then add and save the documentation part properties.
If required, repeat these steps to add or edit a documentation part to other models.
Alternatively, choose Documentation under the API from the main navigation pane. Then choose
Authorizer for Type. Choose Edit on a listed authorizer to change the documentation. To add
documentation for an unlisted authorizer, choose Create Documentation Part. Choose Authorizer for
Type. Give a name to the authorizer in Name. Then add and save the documentation part properties.
If required, repeat these steps to add or edit a documentation part to other authorizers.
To add a documentation part for an authorizer, choose Create Documentation Part. Choose Authorizer
for Type. Specify a value for the valid location field of Name for the authorizer.
Add and save the documentation content in the properties map editor.
1. Choose Documentation for the API from the main navigation pane in the API Gateway console.
2. Choose Publish Documentation in the Documentation pane.
3. Set up the publication:
You can now proceed to download the published documentation by exporting the documentation to an
external OpenAPI file. To learn more, see the section called “Export a REST API” (p. 487).
Before creating and editing the documentation of an API, first create the API. In this section, we use the
PetStore API as an example. To create an API using the API Gateway console, follow the instructions in
Tutorial: Create a REST API by importing an example (p. 46).
Topics
578
Amazon API Gateway Developer Guide
API documentation
{
"location" : {
"type" : "API"
},
"properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API
Gateway.\"\n\t}\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
...
"id": "s2e5xf",
"location": {
"path": null,
"method": null,
"name": null,
"statusCode": null,
"type": "API"
},
"properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API
Gateway.\"\n\t}\n}"
}
If the documentation part has already been added, a 409 Conflict response returns, containing the
error message of Documentation part already exists for the specified location: type
'API'." In this case, you must call the documentationpart:update operation.
579
Amazon API Gateway Developer Guide
API documentation
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
{
"patchOperations" : [ {
"op" : "replace",
"path" : "/properties",
"value" : "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API
Gateway.\"\n\t}\n}"
} ]
}
The successful response returns a 200 OK status code with the payload containing the updated
DocumentationPart instance in the payload.
{
"location" : {
"type" : "RESOURCE",
},
"properties" : "{\n\t\"description\" : \"The PetStore root resource.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo"
}
},
"id": "p76vqo",
"location": {
"path": "/",
580
Amazon API Gateway Developer Guide
API documentation
"method": null,
"name": null,
"statusCode": null,
"type": "RESOURCE"
},
"properties": "{\n\t\"description\" : \"The PetStore root resource.\"\n}"
}
When the resource path is not specified, the resource is assumed to be the root resource. You can add
"path": "/" to properties to make the specification explicit.
To create documentation for a child resource of an API, add a DocumentationPart resource targeted for
the corresponding Resource resource:
{
"location" : {
"type" : "RESOURCE",
"path" : "/pets"
},
"properties": "{\n\t\"description\" : \"A child resource under the root of PetStore.
\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/qcht86"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/qcht86"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/qcht86"
}
},
"id": "qcht86",
"location": {
"path": "/pets",
"method": null,
"name": null,
"statusCode": null,
"type": "RESOURCE"
},
"properties": "{\n\t\"description\" : \"A child resource under the root of PetStore.
\"\n}"
}
581
Amazon API Gateway Developer Guide
API documentation
To add documentation for a child resource specified by a path parameter, add a DocumentationPart
resource targeted for the Resource resource:
{
"location" : {
"type" : "RESOURCE",
"path" : "/pets/{petId}"
},
"properties": "{\n\t\"description\" : \"A child resource specified by the petId path
parameter.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb"
}
},
"id": "k6fpwb",
"location": {
"path": "/pets/{petId}",
"method": null,
"name": null,
"statusCode": null,
"type": "RESOURCE"
},
"properties": "{\n\t\"description\" : \"A child resource specified by the petId path
parameter.\"\n}"
}
Note
The DocumentationPart instance of a RESOURCE entity cannot be inherited by any of its child
resources.
582
Amazon API Gateway Developer Guide
API documentation
{
"location" : {
"type" : "METHOD",
"path" : "/pets",
"method" : "GET"
},
"properties": "{\n\t\"summary\" : \"List all pets.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
}
},
"id": "o64jbj",
"location": {
"path": "/pets",
"method": "GET",
"name": null,
"statusCode": null,
"type": "METHOD"
},
"properties": "{\n\t\"summary\" : \"List all pets.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
583
Amazon API Gateway Developer Guide
API documentation
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
}
},
"id": "o64jbj",
"location": {
"path": "/pets",
"method": "GET",
"name": null,
"statusCode": null,
"type": "METHOD"
},
"properties": "{\n\t\"summary\" : \"List all pets.\"\n}"
}
If the location.method field is not specified in the preceding request, it is assumed to be ANY method
that is represented by a wild card * character.
To update the documentation content of a METHOD entity, call the documentationpart:update operation,
supplying a new properties map:
{
"patchOperations" : [ {
"op" : "replace",
"path" : "/properties",
"value" : "{\n\t\"tags\" : [ \"pets\" ], \n\t\"summary\" : \"List all pets.\"\n}"
} ]
}
The successful response returns a 200 OK status code with the payload containing the updated
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
}
},
"id": "o64jbj",
584
Amazon API Gateway Developer Guide
API documentation
"location": {
"path": "/pets",
"method": "GET",
"name": null,
"statusCode": null,
"type": "METHOD"
},
"properties": "{\n\t\"tags\" : [ \"pets\" ], \n\t\"summary\" : \"List all pets.\"\n}"
}
{
"location" : {
"type" : "QUERY_PARAMETER",
"path" : "/pets",
"method" : "GET",
"name" : "page"
},
"properties": "{\n\t\"description\" : \"Page number of results to return.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w"
}
},
"id": "h9ht5w",
"location": {
"path": "/pets",
"method": "GET",
"name": "page",
"statusCode": null,
"type": "QUERY_PARAMETER"
},
"properties": "{\n\t\"description\" : \"Page number of results to return.\"\n}"
585
Amazon API Gateway Developer Guide
API documentation
The documentation part's properties map of a QUERY_PARAMETER entity can be inherited by one of
its child QUERY_PARAMETER entities. For example, if you add a treats resource after /pets/{petId},
enable the GET method on /pets/{petId}/treats, and expose the page query parameter, this child
query parameter inherits the DocumentationPart's properties map from the like-named query
parameter of the GET /pets method, unless you explicitly add a DocumentationPart resource to the
page query parameter of the GET /pets/{petId}/treats method.
{
"location" : {
"type" : "PATH_PARAMETER",
"path" : "/pets/{petId}",
"method" : "*",
"name" : "petId"
},
"properties": "{\n\t\"description\" : \"The id of the pet to retrieve.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog"
}
},
"id": "ckpgog",
"location": {
"path": "/pets/{petId}",
"method": "*",
"name": "petId",
"statusCode": null,
"type": "PATH_PARAMETER"
},
"properties": "{\n \"description\" : \"The id of the pet to retrieve\"\n}"
586
Amazon API Gateway Developer Guide
API documentation
{
"location" : {
"type" : "REQUEST_BODY",
"path" : "/pets",
"method" : "POST"
},
"properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1"
}
},
"id": "kgmfr1",
"location": {
"path": "/pets",
"method": "POST",
"name": null,
"statusCode": null,
"type": "REQUEST_BODY"
},
"properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}"
}
587
Amazon API Gateway Developer Guide
API documentation
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
{
"location" : {
"type" : "REQUEST_HEADER",
"path" : "/pets",
"method" : "GET",
"name" : "x-my-token"
},
"properties": "{\n\t\"description\" : \"A custom token used to authorization the method
invocation.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf"
}
},
"id": "h0m3uf",
"location": {
"path": "/pets",
"method": "GET",
"name": "x-my-token",
"statusCode": null,
"type": "REQUEST_HEADER"
},
"properties": "{\n\t\"description\" : \"A custom token used to authorization the method
invocation.\"\n}"
}
588
Amazon API Gateway Developer Guide
API documentation
{
"location": {
"path": "/",
"method": "*",
"name": null,
"statusCode": "200",
"type": "RESPONSE"
},
"properties": "{\n \"description\" : \"Successful operation.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/lattew"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/lattew"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/lattew"
}
},
"id": "lattew",
"location": {
"path": "/",
"method": "*",
"name": null,
"statusCode": "200",
"type": "RESPONSE"
},
"properties": "{\n \"description\" : \"Successful operation.\"\n}"
}
"location": {
"path": "/",
"method": "GET",
"name": "Content-Type",
"statusCode": "200",
"type": "RESPONSE_HEADER"
},
"properties": "{\n \"description\" : \"Media type of request\"\n}"
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
589
Amazon API Gateway Developer Guide
API documentation
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7"
}
},
"id": "fev7j7",
"location": {
"path": "/",
"method": "GET",
"name": "Content-Type",
"statusCode": "200",
"type": "RESPONSE_HEADER"
},
"properties": "{\n \"description\" : \"Media type of request\"\n}"
}
The documentation of this Content-Type response header is the default documentation for the
Content-Type headers of any responses of the API.
{
"location" : {
"type" : "AUTHORIZER",
"name" : "myAuthorizer"
},
"properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods.
\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
590
Amazon API Gateway Developer Guide
API documentation
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3"
}
},
"id": "pw3qw3",
"location": {
"path": null,
"method": null,
"name": "myAuthorizer",
"statusCode": null,
"type": "AUTHORIZER"
},
"properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods.
\"\n}"
}
Note
The DocumentationPart instance of an AUTHORIZER entity cannot be inherited by any of its
child resources.
{
"$schema" : "http://json-schema.org/draft-04/schema#",
"title" : "Error Schema",
"type" : "object",
"properties" : {
"message" : { "type" : "string" }
}
}
and requires two DocumentationPart instances, one for the Model and the other for its message
property:
{
"location": {
"type": "MODEL",
"name": "Error"
},
"properties": {
"title": "Error Schema",
"description": "A description of the Error model"
}
}
and
591
Amazon API Gateway Developer Guide
API documentation
"location": {
"type": "MODEL",
"name": "Error.message"
},
"properties": {
"description": "An error message."
}
}
When the API is exported, the DocumentationPart's properties will override the values in the original
schema.
To add documentation for an API model, add a DocumentationPart resource targeted for the specified
model.
{
"location" : {
"type" : "MODEL",
"name" : "Pet"
},
"properties": "{\n\t\"description\" : \"Data structure of a Pet object.\"\n}"
}
If successful, the operation returns a 201 Created response containing the newly created
DocumentationPart instance in the payload. For example:
{
"_links": {
"curies": {
"href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-
documentationpart-{rel}.html",
"name": "documentationpart",
"templated": true
},
"self": {
"href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq"
},
"documentationpart:delete": {
"href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq"
},
"documentationpart:update": {
"href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq"
}
},
"id": "lkn4uq",
"location": {
"path": null,
"method": null,
"name": "Pet",
"statusCode": null,
"type": "MODEL"
},
"properties": "{\n\t\"description\" : \"Data structure of a Pet object.\"\n}"
}
592
Amazon API Gateway Developer Guide
API documentation
Repeat the same step to create a DocumentationPart instance for any of the model's properties.
Note
The DocumentationPart instance of a MODEL entity cannot be inherited by any of its child
resources.
{
"patchOperations" : [ {
"op" : "replace",
"path" : "RESOURCE_PATH",
"value" : "NEW_properties_VALUE_AS_JSON_STRING"
} ]
}
The successful response returns a 200 OK status code with the payload containing the updated
DocumentationPart instance in the payload.
The successful response returns a 200 OK status code with the payload containing the available
DocumentationPart instances in the payload.
Topics
• Create a documentation snapshot and associate it with an API stage (p. 594)
• Create a documentation snapshot (p. 594)
• Update a documentation snapshot (p. 594)
593
Amazon API Gateway Developer Guide
API documentation
{
"documentationVersion" : "1.0.0",
"stageName": "prod",
"description" : "My API Documentation v1.0.0"
}
If successful, the operation returns a 200 OK response, containing the newly created
DocumentationVersion instance as the payload.
Alternatively, you can create a documentation snapshot without associating it with an API stage first
and then call restapi:update to associate the snapshot with a specified API stage. You can also update or
query an existing documentation snapshot and then update its stage association. We show the steps in
the next four sections.
{
"documentationVersion" : "1.0.0",
"description" : "My API Documentation v1.0.0"
}
If successful, the operation returns a 200 OK response, containing the newly created
DocumentationVersion instance as the payload.
594
Amazon API Gateway Developer Guide
API documentation
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
{
"patchOperations": [{
"op": "replace",
"path": "/description",
"value": "My API for testing purposes."
}]
}
To associate a documentation snapshot with an API stage using the API Gateway REST
API, call the stage:update operation to set the desired documentation version on the
stage.documentationVersion property:
PATCH /restapis/RESTAPI_ID/stages/STAGE_NAME
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
{
"patchOperations": [{
"op": "replace",
"path": "/documentationVersion",
"value": "VERSION_IDENTIFIER"
}]
}
595
Amazon API Gateway Developer Guide
API documentation
API Gateway REST API, one of its SDKs, or the AWS CLI for API Gateway. The process is the same as for
exporting the API. The exported file format can be JSON or YAML.
Using the API Gateway REST API, you can also explicitly set the
extension=documentation,integrations,authorizers query parameter to include the API
documentation parts, API integrations and authorizers in an API export. By default, documentation parts
are included, but integrations and authorizers are excluded, when you export an API. The default output
from an API export is suited for distribution of the documentation.
To export the API documentation in an external JSON OpenAPI file using the API Gateway REST API,
submit the following GET request:
GET /restapis/restapi_id/stages/stage_name/exports/swagger?extensions=documentation
HTTP/1.1
Accept: application/json
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
Here, the x-amazon-apigateway-documentation object contains the documentation parts and the
API entity definitions contains the documentation properties supported by OpenAPI. The output does
not include details of integration or Lambda authorizers (formerly known as custom authorizers). To
include both details, set extensions=integrations,authorizers,documentation. To include
details of integrations but not of authorizers, set extensions=integrations,documentation.
You must set the Accept:application/json header in the request to output the result in a JSON file.
To produce the YAML output, change the request header to Accept:application/yaml.
As an example, we will look at an API that exposes a simple GET method on the root resource (/). This
API has four API entities defined in an OpenAPI definition file, one for each of the API, MODEL, METHOD,
and RESPONSE types. A documentation part has been added to each of the API, METHOD, and RESPONSE
entities. Calling the preceding documentation-exporting command, we get the following output, with
the documentation parts listed within the x-amazon-apigateway-documentation object as an
extension to a standard OpenAPI file.
OpenAPI 3.0
{
"openapi": "3.0.0",
"info": {
"description": "API info description",
"version": "2016-11-22T22:39:14Z",
"title": "doc",
"x-bar": "API info x-bar"
},
"paths": {
"/": {
"get": {
"description": "Method description.",
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
596
Amazon API Gateway Developer Guide
API documentation
}
},
"x-example": "x- Method example"
},
"x-bar": "resource x-bar"
}
},
"x-amazon-apigateway-documentation": {
"version": "1.0.0",
"createdDate": "2016-11-22T22:41:40Z",
"documentationParts": [
{
"location": {
"type": "API"
},
"properties": {
"description": "API description",
"foo": "API foo",
"x-bar": "API x-bar",
"info": {
"description": "API info description",
"version": "API info version",
"foo": "API info foo",
"x-bar": "API info x-bar"
}
}
},
{
"location": {
"type": "METHOD",
"method": "GET"
},
"properties": {
"description": "Method description.",
"x-example": "x- Method example",
"foo": "Method foo",
"info": {
"version": "method info version",
"description": "method info description",
"foo": "method info foo"
}
}
},
{
"location": {
"type": "RESOURCE"
},
"properties": {
"description": "resource description",
"foo": "resource foo",
"x-bar": "resource x-bar",
"info": {
"description": "resource info description",
"version": "resource info version",
"foo": "resource info foo",
"x-bar": "resource info x-bar"
}
}
}
]
},
"x-bar": "API x-bar",
"servers": [
{
"url": "https://rznaap68yi.execute-api.ap-southeast-1.amazonaws.com/
{basePath}",
597
Amazon API Gateway Developer Guide
API documentation
"variables": {
"basePath": {
"default": "/test"
}
}
}
],
"components": {
"schemas": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
}
OpenAPI 2.0
{
"swagger" : "2.0",
"info" : {
"description" : "API info description",
"version" : "2016-11-22T22:39:14Z",
"title" : "doc",
"x-bar" : "API info x-bar"
},
"host" : "rznaap68yi.execute-api.ap-southeast-1.amazonaws.com",
"basePath" : "/test",
"schemes" : [ "https" ],
"paths" : {
"/" : {
"get" : {
"description" : "Method description.",
"produces" : [ "application/json" ],
"responses" : {
"200" : {
"description" : "200 response",
"schema" : {
"$ref" : "#/definitions/Empty"
}
}
},
"x-example" : "x- Method example"
},
"x-bar" : "resource x-bar"
}
},
"definitions" : {
"Empty" : {
"type" : "object",
"title" : "Empty Schema"
}
},
"x-amazon-apigateway-documentation" : {
"version" : "1.0.0",
"createdDate" : "2016-11-22T22:41:40Z",
"documentationParts" : [ {
"location" : {
"type" : "API"
},
"properties" : {
"description" : "API description",
"foo" : "API foo",
"x-bar" : "API x-bar",
598
Amazon API Gateway Developer Guide
API documentation
"info" : {
"description" : "API info description",
"version" : "API info version",
"foo" : "API info foo",
"x-bar" : "API info x-bar"
}
}
}, {
"location" : {
"type" : "METHOD",
"method" : "GET"
},
"properties" : {
"description" : "Method description.",
"x-example" : "x- Method example",
"foo" : "Method foo",
"info" : {
"version" : "method info version",
"description" : "method info description",
"foo" : "method info foo"
}
}
}, {
"location" : {
"type" : "RESOURCE"
},
"properties" : {
"description" : "resource description",
"foo" : "resource foo",
"x-bar" : "resource x-bar",
"info" : {
"description" : "resource info description",
"version" : "resource info version",
"foo" : "resource info foo",
"x-bar" : "resource info x-bar"
}
}
} ]
},
"x-bar" : "API x-bar"
}
For an OpenAPI-compliant attribute defined in the properties map of a documentation part, API
Gateway inserts the attribute into the associated API entity definition. An attribute of x-something is a
standard OpenAPI extension. This extension gets propagated into the API entity definition. For example,
see the x-example attribute for the GET method. An attribute like foo is not part of the OpenAPI
specification and is not injected into its associated API entity definitions.
If a documentation-rendering tool (e.g., OpenAPI UI) parses the API entity definitions to
extract documentation attributes, any non OpenAPI-compliant properties attributes of a
DocumentationPart' instance are not available for the tool. However, if a documentation-rendering
tool parses the x-amazon-apigateway-documentation object to get content, or if the tool calls
restapi:documentation-parts and documenationpart:by-id to retrieve documentation parts from API
Gateway, all the documentation attributes are available for the tool to display.
To export the documentation with API entity definitions containing integration details to a JSON
OpenAPI file, submit the following GET request:
GET /restapis/restapi_id/stages/stage_name/exports/swagger?
extensions=integrations,documentation HTTP/1.1
Accept: application/json
599
Amazon API Gateway Developer Guide
API documentation
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
To export the documentation with API entity definitions containing details of integrations and
authorizers to a YAML OpenAPI file, submit the following GET request:
GET /restapis/restapi_id/stages/stage_name/exports/swagger?
extensions=integrations,authorizers,documentation HTTP/1.1
Accept: application/yaml
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
To use the API Gateway console to export and download the published documentation of an API, follow
the instructions in Export REST API using the API Gateway console (p. 489).
You have an option to merge the newly specified documentation parts into existing documentation
parts in API Gateway or to overwrite the existing documentation parts. In the MERGE mode, a new
documentation part defined in the OpenAPI file is added to the DocumentationParts collection of the
API. If an imported DocumentationPart already exists, an imported attribute replaces the existing one
if the two are different. Other existing documentation attributes remain unaffected. In the OVERWRITE
mode, the entire DocumentationParts collection is replaced according to the imported OpenAPI
definition file.
OpenAPI 3.0
PUT /restapis/<restapi_id>/documentation/parts&mode=overwrite&failonwarnings=true
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
{
"openapi": "3.0.0",
"info": {
"description": "description",
"version": "1",
"title": "doc"
600
Amazon API Gateway Developer Guide
API documentation
},
"paths": {
"/": {
"get": {
"description": "Method description.",
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Empty"
}
}
}
}
}
}
}
},
"x-amazon-apigateway-documentation": {
"version": "1.0.3",
"documentationParts": [
{
"location": {
"type": "API"
},
"properties": {
"description": "API description",
"info": {
"description": "API info description 4",
"version": "API info version 3"
}
}
},
{
"location": {
"type": "METHOD",
"method": "GET"
},
"properties": {
"description": "Method description."
}
},
{
"location": {
"type": "MODEL",
"name": "Empty"
},
"properties": {
"title": "Empty Schema"
}
},
{
"location": {
"type": "RESPONSE",
"method": "GET",
"statusCode": "200"
},
"properties": {
"description": "200 response"
}
}
]
},
"servers": [
601
Amazon API Gateway Developer Guide
API documentation
{
"url": "/"
}
],
"components": {
"schemas": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
}
OpenAPI 2.0
PUT /restapis/<restapi_id>/documentation/parts&mode=overwrite&failonwarnings=true
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/
apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date,
Signature=sigv4_secret
{
"swagger": "2.0",
"info": {
"description": "description",
"version": "1",
"title": "doc"
},
"host": "",
"basePath": "/",
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"description": "Method description.",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
}
}
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
},
"x-amazon-apigateway-documentation": {
"version": "1.0.3",
"documentationParts": [
{
"location": {
602
Amazon API Gateway Developer Guide
API documentation
"type": "API"
},
"properties": {
"description": "API description",
"info": {
"description": "API info description 4",
"version": "API info version 3"
}
}
},
{
"location": {
"type": "METHOD",
"method": "GET"
},
"properties": {
"description": "Method description."
}
},
{
"location": {
"type": "MODEL",
"name": "Empty"
},
"properties": {
"title": "Empty Schema"
}
},
{
"location": {
"type": "RESPONSE",
"method": "GET",
"statusCode": "200"
},
"properties": {
"description": "200 response"
}
}
]
}
}
When successful, this request returns a 200 OK response containing the imported
DocumentationPartId in the payload.
{
"ids": [
"kg3mth",
"796rtf",
"zhek4p",
"5ukm9s"
]
}
In addition, you can also call restapi:import or restapi:put, supplying the documentation parts in the x-
amazon-apigateway-documentation object as part of the input OpenAPI file of the API definition.
To exclude the documentation parts from the API import, set ignore=documentation in the request
query parameters.
603
Amazon API Gateway Developer Guide
SDK generation
To use the console to import documentation parts of an API from an external file
1. Choose Documentation for the API from the main navigation pane on the console.
2. Choose Import Documentation in the Documentation pane.
3. Choose Select OpenAPI File to load a file from a drive, or copy and paste a file contents into the
file view. For an example, see the payload of the example request in Importing documentation parts
using the API Gateway REST API (p. 600).
4. Optionally, choose Fail on warnings or Ignore warnings, and choose Merge or Overwrite from
Import mode.
5. Choose Import.
To grant your documentation team the access to create, update, and publish your API documentation,
you can assign the documentation team an IAM role with the following IAM policy, where account_id is
the AWS account ID of your documentation team.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "StmtDocPartsAddEditViewDelete",
"Effect": "Allow",
"Action": [
"apigateway:GET",
"apigateway:PUT",
"apigateway:POST",
"apigateway:PATCH",
"apigateway:DELETE"
],
"Resource": [
"arn:aws:apigateway::account_id:/restapis/*/documentation/*"
]
}
]
}
For information on setting permissions to access API Gateway resources, see the section called “How
Amazon API Gateway works with IAM” (p. 784).
This section explains how to generate an SDK of an API Gateway API. It also demonstrates how to use
the generated SDK in a Java app, a Java for Android app, Objective-C and Swift for iOS apps, and a
JavaScript app.
To facilitate the discussion, we use this API Gateway API (p. 611), which exposes this Simple
Calculator (p. 609) Lambda function.
604
Amazon API Gateway Developer Guide
SDK generation
Before proceeding, create or import the API and deploy it at least once in API Gateway. For instructions,
see Deploying a REST API in Amazon API Gateway (p. 490).
Topics
• Generate SDKs for an API using the API Gateway console (p. 605)
• Generate SDKs for an API using AWS CLI commands (p. 608)
• Simple calculator Lambda function (p. 609)
• Simple calculator API in API Gateway (p. 611)
• Simple calculator API OpenAPI definition (p. 615)
Topics
• Generate the Java SDK of an API (p. 605)
• Generate the Android SDK of an API (p. 606)
• Generate the iOS SDK of an API (p. 606)
• Generate the JavaScript SDK of a REST API (p. 607)
• Generate the Ruby SDK of an API (p. 607)
a. For Service Name, specify the name of your SDK. For example, SimpleCalcSdk. This becomes
the name of your SDK client class. The name corresponds to the <name> tag under <project>
in the pom.xml file, which is in the SDK's project folder. Do not include hyphens.
b. For Java Package Name, specify a package name for your SDK. For example,
examples.aws.apig.simpleCalc.sdk. This package name is used as the namespace of your
SDK library. Do not include hyphens.
c. For Java Build System, enter maven or gradle to specify the build system.
d. For Java Group Id, enter a group identifier for your SDK project. For example, enter my-apig-
api-examples. This identifier corresponds to the <groupId> tag under <project> in the
pom.xml file, which is in the SDK's project folder.
e. For Java Artifact Id, enter an artifact identifier for your SDK project. For example, enter
simple-calc-sdk. This identifier corresponds to the <artifactId> tag under <project> in
the pom.xml file, which is in the SDK's project folder.
f. For Java Artifact Version, enter a version identifier string. For example, 1.0.0. This version
identifier corresponds to the <version> tag under <project> in the pom.xml file, which is in
the SDK's project folder.
605
Amazon API Gateway Developer Guide
SDK generation
g. For Source Code License Text, enter the license text of your source code, if any.
6. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by
API Gateway.
7. Follow the instructions in Use a Java SDK generated by API Gateway for a REST API (p. 460) to use
the generated SDK.
Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates
included.
a. For Group ID, enter the unique identifier for the corresponding project. This is used in the
pom.xml file (for example, com.mycompany).
b. For Invoker package, enter the namespace for the generated client classes (for example,
com.mycompany.clientsdk).
c. For Artifact ID, enter the name of the compiled .jar file without the version. This is used in the
pom.xml file (for example, aws-apigateway-api-sdk).
d. For Artifact version, enter the artifact version number for the generated client. This is used in
the pom.xml file and should follow a major.minor.patch pattern (for example, 1.0.0).
6. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by
API Gateway.
7. Follow the instructions in Use an Android SDK generated by API Gateway for a REST API (p. 464) to
use the generated SDK.
Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates
included.
The effect of prefix is as follows: if you assign, for example, SIMPLE_CALC as the prefix for the
SDK of the SimpleCalc (p. 611) API with Input, Output, and Result models, the generated
SDK will contain the SIMPLE_CALCSimpleCalcClient class that encapsulates the API,
606
Amazon API Gateway Developer Guide
SDK generation
including the method requests/responses. In addition, the generated SDK will contain the
SIMPLE_CALCInput, SIMPLE_CALCOutput, and SIMPLE_CALCResult classes to represent
the input, output, and results, respectively, to represent the request input and response output.
For more information, see Use iOS SDK generated by API Gateway for a REST API in Objective-C
or Swift (p. 470).
6. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by
API Gateway.
7. Follow the instructions in Use iOS SDK generated by API Gateway for a REST API in Objective-C or
Swift (p. 470) to use the generated SDK.
Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates
included.
Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates
included.
a. For Service Name, specify the name of your SDK. For example, SimpleCalc. This is used to
generate the Ruby Gem namespace of your API. The name must be all letters, (a-zA-Z), without
any other special characters or numbers.
b. For Ruby Gem Name, specify the name of the Ruby Gem to contain the generated SDK source
code for your API. By default, it is the lower-cased service name plus the -sdk suffix—for
example, simplecalc-sdk.
c. For Ruby Gem Version, specify a version number for the generated Ruby Gem. By default, it is
set to 1.0.0.
6. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by
API Gateway.
607
Amazon API Gateway Developer Guide
SDK generation
7. Follow the instructions in Use a Ruby SDK generated by API Gateway for a REST API (p. 467) to use
the generated SDK.
Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates
included.
Topics
• Generate and download the Java for Android SDK using the AWS CLI (p. 608)
• Generate and download the JavaScript SDK using the AWS CLI (p. 608)
• Generate and download the Ruby SDK using the AWS CLI (p. 608)
Generate and download the Java for Android SDK using the AWS CLI
To generate and download a Java for Android SDK generated by API Gateway of an API (udpuvvzbkc) at
a given stage (test), call the command as follows:
The last input of ~/apps/myApi/myApi-android-sdk.zip is the path to the downloaded SDK file
named myApi-android-sdk.zip.
Generate and download the JavaScript SDK using the AWS CLI
To generate and download a JavaScript SDK generated by API Gateway of an API (udpuvvzbkc) at a
given stage (test), call the command as follows:
The last input of ~/apps/myApi/myApi-js-sdk.zip is the path to the downloaded SDK file named
myApi-js-sdk.zip.
Generate and download the Ruby SDK using the AWS CLI
To generate and download a Ruby SDK of an API (udpuvvzbkc) at a given stage (test), call the
command as follows:
608
Amazon API Gateway Developer Guide
SDK generation
--rest-api-id udpuvvzbkc \
--stage-name test \
--sdk-type ruby \
--parameters service.name=myApiRubySdk,ruby.gem-name=myApi,ruby.gem-
version=0.01 \
~/apps/myApi/myApi-ruby-sdk.zip
The last input of ~/apps/myApi/myApi-ruby-sdk.zip is the path to the downloaded SDK file named
myApi-ruby-sdk.zip.
Next, we show how to use the generated SDK to call the underlying API. For more information, see Call
REST API through generated SDKs (p. 460).
Topics
• Simple calculator Lambda function input format (p. 609)
• Simple calculator Lambda function output format (p. 609)
• Simple calculator Lambda function implementation (p. 609)
• Create the simple calculator Lambda function (p. 610)
609
Amazon API Gateway Developer Guide
SDK generation
res.a = Number(event.a);
res.b = Number(event.b);
res.op = event.op;
if (isNaN(event.a) || isNaN(event.b)) {
callback("400 Invalid Operand");
}
switch(event.op)
{
case "+":
case "add":
res.c = res.a + res.b;
break;
case "-":
case "sub":
res.c = res.a - res.b;
break;
case "*":
case "mul":
res.c = res.a * res.b;
break;
case "/":
case "div":
res.c = res.b===0 ? NaN : Number(event.a) / Number(event.b);
break;
default:
callback("400 Invalid Operator");
break;
}
callback(null, res);
};
610
Amazon API Gateway Developer Guide
SDK generation
These three methods show different ways to supply the input for the backend Lambda function to
perform the same operation:
• The GET /?a=...&b=...&op=... method uses the query parameters to specify the input.
• The POST / method uses a JSON payload of {"a":"Number", "b":"Number", "op":"string"}
to specify the input.
• The GET /{a}/{b}/{op} method uses the path parameters to specify the input.
If not defined, API Gateway generates the corresponding SDK method name by combining the HTTP
method and path parts. The root path part (/) is referred to as Api Root. For example, the default Java
SDK method name for the API method of GET /?a=...&b=...&op=... is getABOp, the default SDK
method name for POST / is postApiRoot, and the default SDK method name for GET /{a}/{b}/
{op} is getABOp. Individual SDKs may customize the convention. Consult the documentation in the
generated SDK source for SDK specific method names.
You can, and should, override the default SDK method names by specifying the operationName property
on each API method. You can do so when creating the API method or updating the API method using the
API Gateway REST API. In the API Swagger definition, you can set the operationId to achieve the same
result.
611
Amazon API Gateway Developer Guide
SDK generation
Before showing how to call these methods using an SDK generated by API Gateway for this API, let's
recall briefly how to set them up. For detailed instructions, see Creating a REST API in Amazon API
Gateway (p. 242). If you're new to API Gateway, see Build an API Gateway REST API with Lambda
integration (p. 30) first.
Similarly, to describe the response body data type, we create the following models in the API Gateway:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"c": {"type":"number"}
},
"title": "Output"
}
and
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type":"object",
"properties":{
"input":{
"$ref":"https://apigateway.amazonaws.com/restapis/t7dve4zn36/models/Input"
},
"output":{
"$ref":"https://apigateway.amazonaws.com/restapis/t7dve4zn36/models/Output"
}
},
612
Amazon API Gateway Developer Guide
SDK generation
"title":"Result"
}
613
Amazon API Gateway Developer Guide
SDK generation
With this model, your API customers can call the SDK to specify the input by instantiating an Input
object. Without this model, your customers would be required to create dictionary object to represent
the JSON input to the Lambda function.
Set up data model for the result output from the backend
For all three methods, we create the Result model and add it to the method's Method Response to
define the shape of output returned by the Lambda function.
614
Amazon API Gateway Developer Guide
SDK generation
With this model, your API customers can parse a successful output by reading properties of a Result
object. Without this model, customers would be required to create dictionary object to represent the
JSON output.
In addition, you can also create and set up the API following the Swagger API definitions (p. 615).
OpenAPI 2.0
{
"swagger": "2.0",
"info": {
"version": "2016-09-29T20:27:30Z",
"title": "SimpleCalc"
},
"host": "t6dve4zn25.execute-api.us-west-2.amazonaws.com",
"basePath": "/demo",
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"consumes": [
"application/json"
],
615
Amazon API Gateway Developer Guide
SDK generation
"produces": [
"application/json"
],
"parameters": [
{
"name": "op",
"in": "query",
"required": false,
"type": "string"
},
{
"name": "a",
"in": "query",
"required": false,
"type": "string"
},
{
"name": "b",
"in": "query",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Result"
}
}
},
"x-amazon-apigateway-integration": {
"requestTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n
\"a\" : $input.params('a'),\n \"b\" : $input.params('b'),\n \"op\" :
\"$input.params('op')\"\n}"
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"passthroughBehavior": "when_no_templates",
"httpMethod": "POST",
"responses": {
"default": {
"statusCode": "200",
"responseTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n
\"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" :
\"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}"
}
}
},
"type": "aws"
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "Input",
"required": true,
616
Amazon API Gateway Developer Guide
SDK generation
"schema": {
"$ref": "#/definitions/Input"
}
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Result"
}
}
},
"x-amazon-apigateway-integration": {
"uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"responses": {
"default": {
"statusCode": "200",
"responseTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n
\"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" :
\"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}"
}
}
},
"type": "aws"
}
}
},
"/{a}": {
"x-amazon-apigateway-any-method": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "a",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "404 response"
}
},
"x-amazon-apigateway-integration": {
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"passthroughBehavior": "when_no_match",
"responses": {
"default": {
"statusCode": "404",
"responseTemplates": {
"application/json": "{ \"Message\" : \"Can't $context.httpMethod
$context.resourcePath\" }"
}
}
617
Amazon API Gateway Developer Guide
SDK generation
},
"type": "mock"
}
}
},
"/{a}/{b}": {
"x-amazon-apigateway-any-method": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "a",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "b",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "404 response"
}
},
"x-amazon-apigateway-integration": {
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"passthroughBehavior": "when_no_match",
"responses": {
"default": {
"statusCode": "404",
"responseTemplates": {
"application/json": "{ \"Message\" : \"Can't $context.httpMethod
$context.resourcePath\" }"
}
}
},
"type": "mock"
}
}
},
"/{a}/{b}/{op}": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "a",
"in": "path",
"required": true,
"type": "string"
},
{
618
Amazon API Gateway Developer Guide
SDK generation
"name": "b",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "op",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Result"
}
}
},
"x-amazon-apigateway-integration": {
"requestTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n
\"a\" : $input.params('a'),\n \"b\" : $input.params('b'),\n \"op\" :
\"$input.params('op')\"\n}"
},
"uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
"passthroughBehavior": "when_no_templates",
"httpMethod": "POST",
"responses": {
"default": {
"statusCode": "200",
"responseTemplates": {
"application/json": "#set($inputRoot = $input.path('$'))\n{\n
\"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" :
\"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}"
}
}
},
"type": "aws"
}
}
}
},
"definitions": {
"Input": {
"type": "object",
"properties": {
"a": {
"type": "number"
},
"b": {
"type": "number"
},
"op": {
"type": "string"
}
},
"title": "Input"
},
"Output": {
"type": "object",
"properties": {
"c": {
"type": "number"
619
Amazon API Gateway Developer Guide
Developer portal
}
},
"title": "Output"
},
"Result": {
"type": "object",
"properties": {
"input": {
"$ref": "#/definitions/Input"
},
"output": {
"$ref": "#/definitions/Output"
}
},
"title": "Result"
}
}
}
Amazon API Gateway publishes a regularly updated Serverless Developer Portal application in the AWS
Serverless Application Repository and on GitHub. It is released under the Apache 2.0 license, which lets
you customize and incorporate it into your build and deployment tools. The front end is written in React
and is designed to be fully customizable. See https://github.com/awslabs/aws-api-gateway-developer-
portal/wiki/Customization.
For more information about the AWS Serverless Application Repository, see the AWS Serverless
Application Repository Developer Guide.
Tip
If you'd like to try out an example developer portal, see https://
developer.exampleapigateway.com/.
Topics
• Create a developer portal (p. 621)
• Developer portal settings (p. 622)
• Create an admin user for your developer portal (p. 624)
• Manage users for your developer portal (p. 624)
• Publish an API Gateway managed API to your developer portal (p. 624)
• Update or delete an API Gateway managed API (p. 625)
• Remove a non-API Gateway managed API (p. 626)
620
Amazon API Gateway Developer Guide
Developer portal
• Publish a non-API Gateway managed API to your developer portal (p. 626)
• How your customers use your developer portal (p. 626)
• Best practices for developer portals (p. 627)
• By using the AWS Serverless Application Repository. Choose the Deploy button to launch the API
Gateway Serverless Developer Portal AWS CloudFormation stack and enter a handful of stack
parameters in the Lambda console.
• By downloading the API Gateway Serverless Developer Portal from the AWS GitHub repository and
launching the API Gateway Serverless Developer Portal AWS CloudFormation stack from the AWS SAM
CLI.
To deploy the serverless developer portal using the AWS Serverless Application Repository
1. Go to the API Gateway Serverless Developer Portal page in the AWS Serverless Application
Repository.
2. Choose Deploy.
Note
You might be prompted to sign into the AWS Lambda console.
3. In the Lambda console, enter the required developer portal stack parameters (p. 622) under
Application settings.
Note
The S3 bucket names and the Amazon Cognito domain prefix are required; the other
settings are optional.
4. If you want to enable the Got an opinion? customer feedback button, you need to:
• Enter an email address in the DevPortalAdminEmail box. When a customer submits feedback,
email is sent to this address.
Note
If you don't supply an email address, the Got an opinion? doesn't appear in the developer
portal.
• You can optionally enter a table name in the DevPortalFeedbackTableName box. The default
name is DevPortalFeedback. When a customer submits feedback, it is stored in a DynamoDB
table with this name.
5. Select the check box next to I acknowledge that this app creates custom IAM roles and resource
policies.
6. Choose Deploy.
7. If you entered an email address in the AdminEmail stack parameter, an Amazon SNS subscription
email is sent to that email address. This email confirms your subscription to the Amazon SNS topic
that you specified in the MarketplaceSubscriptionTopicProductCode setting.
To download and deploy the serverless developer portal using AWS SAM
1. Ensure that you have the latest AWS CLI and AWS SAM CLI installed and configured.
2. Download or clone the API Gateway Serverless Developer Portal repository.
3. Ensure that you have a private Amazon S3 bucket where you can upload the zipped Lambda
functions. If you don't have one, you can create one using the Amazon S3 console or CLI.
621
Amazon API Gateway Developer Guide
Developer portal
In the AWS SAM CLI, run the following command from the project root, replacing {your-lambda-
artifacts-bucket-name} with the name of your Amazon S3 bucket:
4. For this step, see the section called “Developer portal settings” (p. 622) for more information
about parameters (such as CognitoDomainNameOrPrefix) that follow --parameter-
overrides.
Note
Ensure that you have a private Amazon S3 bucket where you can upload the AWS SAM
template. (AWS CloudFormation reads the template from the bucket to deploy the
developer portal.) This can be the same bucket that you specified in the previous step for
uploading the zipped Lambda functions.
After your developer portal has been fully deployed, you can get its URL as follows.
ArtifactsS3BucketName (REQUIRED)
The deployment process creates a privately accessible Amazon S3 bucket where the catalog
metadata is stored. Specify a name to assign to the bucket. This name must be globally unique.
622
Amazon API Gateway Developer Guide
Developer portal
CognitoDomainNameOrPrefix (REQUIRED)
This string is used with the Amazon Cognito hosted UI for user sign-up and sign-in. Specify a unique
domain name or prefix string.
CognitoIdentityPoolName
The deployment process creates an Amazon Cognito identity pool. The default name for the identity
pool is DevPortalIdentityPool.
CustomDomainNameAcmCertArn
If you provided a domain name associated with an ACM certificate, then you must also specify here
the ACM certificate's ARN. Leave this blank to create a developer portal without a custom domain
name.
DevPortalAdminEmail
Specify an email address to enable the Got an opinion? customer feedback button. When a
customer submits feedback, email is sent to this address.
Note
If you don't supply an email address, the Got an opinion? button doesn't appear in the
developer portal.
DevPortalFeedbackTableName
The deployment process creates a DynamoDB table where customer accounts are stored. You can
optionally specify a name to assign to this table. It must be unique within your account Region. The
default name of the table is DevPortalCustomers.
DevPortalSiteS3BucketName (REQUIRED)
The deployment process creates a privately accessible Amazon S3 bucket where the web application
code is stored. Specify a name to assign to this bucket. This name must be globally unique.
MarketplaceSubscriptionTopicProductCode
This is the Amazon SNS topic suffix for subscribe/unsubscribe events. Enter the desired value. The
default value is DevPortalMarketplaceSubscriptionTopic. This setting is only relevant if
you're using AWS Marketplace integration. For more information, see SaaS customer onboarding.
StaticAssetRebuildMode
By default, a static asset rebuild doesn't overwrite custom content. Specify overwrite-content to
replace the custom content with your local version.
Important
If you specify overwrite-content, all custom changes in your Amazon S3 bucket will be
lost. Don't do this unless you know what you're doing.
StaticAssetRebuildToken
Provide a token different from the last deployment's token to re-upload the developer portal site's
static assets. You can provide a timestamp or GUID on each deployment to always re-upload the
assets.
UseRoute53Nameservers
Only applicable if you're creating a custom domain name for your developer portal. If set to true,
a Route 53 HostedZone and RecordSet are created for you. Otherwise, leave this field set to false
and provide your own name server hosting.
623
Amazon API Gateway Developer Guide
Developer portal
1. If you haven't already done so, deploy the API to a stage (p. 492).
2. If you haven't already done so, create a usage plan (p. 549) and associate it with the API stage for
the deployed API.
Note
You don't need to associate API keys with the usage plan. The developer portal does this for
you.
3. Sign in to the Developer Portal and go to the Admin Panel.
4. You should see the API in the Admin Panel API list. In the API list, APIs are grouped by usage plan.
The Not Subscribable No Usage Plan group lists the APIs that aren't associated with a usage plan.
Step 2: Make the API Gateway managed API visible in the developer portal
1. In the Admin Panel API list, check the Displayed value for your API. When it's first uploaded, this
value is set to False.
624
Amazon API Gateway Developer Guide
Developer portal
2. To make the API visible in the developer portal, choose the False button. Its value changes to True,
which indicates that the API is now visible.
Tip
To make all APIs in a usage plan visible, choose the False or Partial button in the header bar
for the usage plan.
3. Navigate to the APIs panel to see the developer portal as your customers see it. You should see your
API listed in the left navigation column.
If the API is deployed to a stage that's associated with a usage plan, you should see a Subscribe
button for the API. This button causes the customer's API key to be associated with the usage plan
that the API is associated with.
Now that the API Gateway managed API is displayed, you can enable SDK generation so that your
customers are able to download an SDK for it.
1. In the Admin Panel API list, choose the Disabled button. Its value changes to Enabled, which
indicates that SDK generation is now allowed.
2. Navigate to the APIs panel and choose your API in the left navigation column. You should now see
Download SDK and Export API buttons.
1. Make the desired changes to the API in the API Gateway console, AWS CLI, or an SDK.
2. Redeploy the API to the same stage as before.
3. In the developer portal, in the Admin Panel API list, choose Update. This updates the API that's
displayed in the developer portal UI.
Note
The Download SDK button always gets the latest deployed version of your API, even if you
don't update it in the developer portal.
4. Navigate to the APIs panel and choose your API in the left navigation column. You should see your
changes.
To stop displaying an API in the developer portal API list (without revoking customers' access to it):
1. In the Admin Panel API list, check the Displayed value for your API. If the API is visible, this value is
set to True.
2. To make the API invisible, choose the True button. Its value changes to False, which indicates that
the API is now invisible.
3. Navigate to the APIs panel. You should no longer see your API listed in the left navigation column.
To revoke customers' access to an API without deleting it entirely, you must do one of the following in
the API Gateway console (p. 554) or the API Gateway CLI or REST API (p. 559):
625
Amazon API Gateway Developer Guide
Developer portal
A developer account gives your customer an API key, which is typically needed to use and test your APIs.
It enables usage tracking for both you and your customers.
When a customer first registers, their new API key won't be tied to any of your APIs.
1. Choose APIs.
2. Choose the API from the API list and choose Subscribe.
This causes the API key to be associated with the usage plan that the API is associated with.
The customer has now subscribed to the API, and they can make calls to methods on the API. Daily usage
statistics for the API will be displayed in MyDashboard.
626
Amazon API Gateway Developer Guide
Sell your APIs as SaaS
A customer can try out API methods in the developer portal UI without subscribing.
Note
If any of the API's methods require an API key, an Authorize button will appear above the
method list. Methods that require an API key will have a black lock icon. To try out methods that
require an API key, choose the Authorize button and enter a valid API key that's associated with
the usage plan for the API stage.
You can safely ignore the Authorize button when it appears on APIs that you're already
subscribed to.
Your customers can submit customer feedback through the developer portal.
The customer's feedback is stored in the DynamoDB table for the developer portal. The default name
of this table is DevPortalFeedback. Also, email is sent to the email addresses that was specified in the
DevPortalAdminEmail field. If no email address was specified when the developer portal was deployed,
the Got an opinion? button does not appear.
Note
If you change the name of this table, you must use a name that is unique within your account
Region.
If you've enabled SDK generation for the API in the Admin Panel, the customer can download an
SDK for it and export the API definition. To learn more, see Generating an SDK for a REST API in API
Gateway (p. 604) and Export a REST API from API Gateway (p. 487).
• In most cases, you'll only want to deploy one developer portal for all of your APIs. In some cases, you
might choose to have separate developer portals for development and production versions of your
APIs. We don't recommended using more than one developer portal for production APIs.
• When you create a usage plan and associate it with a stage, you don't need to associate any API keys
with the usage plan. The developer portal does this for you.
• Note that, if any APIs in a given usage plan are visible, all APIs in that usage plan are subscribable,
even if you haven't made them visible to your customers.
To sell your APIs on AWS Marketplace, you must set up the sales channel to integrate AWS Marketplace
with API Gateway. Generally speaking, this involves listing your product on AWS Marketplace, setting up
an IAM role with appropriate policies to allow API Gateway to send usage metrics to AWS Marketplace,
associating an AWS Marketplace product with an API Gateway usage plan, and associating an AWS
Marketplace buyer with an API Gateway API key. Details are discussed in the following sections.
For more information about selling your API as a SaaS product on AWS Marketplace, see the AWS
Marketplace User Guide.
Topics
• Initialize AWS Marketplace integration with API Gateway (p. 628)
627
Amazon API Gateway Developer Guide
Sell your APIs as SaaS
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"aws-marketplace:BatchMeterUsage",
"aws-marketplace:ResolveCustomer"
],
"Resource": "*",
"Effect": "Allow"
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
628
Amazon API Gateway Developer Guide
Sell your APIs as SaaS
PATCH /usageplans/USAGE_PLAN_ID
Host: apigateway.region.amazonaws.com
Authorization: ...
{
"patchOperations" : [{
"path" : "/productCode",
"value" : "MARKETPLACE_PRODUCT_CODE",
"op" : "replace"
}]
}
When a customer subscribes to your product through AWS Marketplace, AWS Marketplace forwards
a POST request to the SaaS subscriptions URL that you registered when listing your product on AWS
Marketplace. The POST request comes with an x-amzn-marketplace-token parameter containing
buyer information. Follow the instructions in SaaS customer onboarding to handle this redirect in your
developer portal application.
When the customer's subscription request completes, the developer portal application should present
the customer with the associated API key and inform the customer that the API key must be included in
the x-api-key header in requests to the APIs.
When a customer cancels a subscription to a usage plan, AWS Marketplace sends an unsubscribe-
success notification to the SNS topic. To complete the process of unsubscribing the customer, you
handle the unsubscribe-success notification by removing the customer's API keys from the usage
plan.
The following example shows how to call the API Gateway REST API to create a new API key with a
specific AWS Marketplace customerId value (MARKETPLACE_CUSTOMER_ID).
{
"name" : "my_api_key",
"description" : "My API key",
"enabled" : "false",
"stageKeys" : [ {
"restApiId" : "uycll6xg9a",
"stageName" : "prod"
} ],
"customerId" : "MARKETPLACE_CUSTOMER_ID"
629
Amazon API Gateway Developer Guide
Protect
The following example shows how to get an API key with a specific AWS Marketplace customerId value
(MARKETPLACE_CUSTOMER_ID).
To add an API key to a usage plan, create a UsagePlanKey with the API key for the relevant usage plan.
The following example shows how to accomplish this using the API Gateway REST API, where n371pt is
the usage plan ID and q5ugs7qjjh is an example API keyId returned from the preceding examples.
{
"keyId": "q5ugs7qjjh",
"keyType": "API_KEY"
}
PATCH /apikeys/q5ugs7qjjh
Host: apigateway.region.amazonaws.com
Authorization: ...
{
"patchOperations" : [{
"path" : "/customerId",
"value" : "MARKETPLACE_CUSTOMER_ID",
"op" : "replace"
}]
}
Topics
• Configuring mutual TLS authentication for a REST API (p. 631)
• Generate and configure an SSL certificate for backend authentication (p. 635)
• Using AWS WAF to protect your APIs (p. 662)
• Throttle API requests for better throughput (p. 663)
• Creating a private API in Amazon API Gateway (p. 665)
630
Amazon API Gateway Developer Guide
Mutual TLS
You can use mutual TLS along with other authorization and authentication operations (p. 273) that API
Gateway supports. API Gateway forwards the certificates that clients provide to Lambda authorizers and
to backend integrations.
Important
By default, clients can invoke your API by using the execute-api endpoint that API Gateway
generates for your API. To ensure that clients can access your API only by using a custom domain
name with mutual TLS, disable the default execute-api endpoint. To learn more, see the
section called “Disable the default endpoint” (p. 539).
You can request a publicly trusted certificate directly from ACM or import public or self-signed
certificates. To setup a certificate in ACM, go to ACM. If you would like to import a certificate, continue
reading in the following section.
To use a certificate imported into ACM or a certificate from AWS Certificate Manager Private Certificate
Authority with mutual TLS, API Gateway needs an ownershipVerificationCertificate
issued by ACM. This ownership certificate is only used to verify that you have permissions
to use the domain name. It is not used for the TLS handshake. If you don't already have a
ownershipVerificationCertificate, go to https://console.aws.amazon.com/acm/ to set one up.
You will need to keep this certificate valid for the lifetime of your domain name. If a certificate expires
and auto-renew fails, all updates to the domain name will be locked. You will need to update the
ownershipVerificationCertificateArn with a valid ownershipVerificationCertificate
before you can make any other changes. The ownershipVerificationCertificate cannot be
used as a server certificate for another mutual TLS domain in API Gateway. If a certificate is directly re-
imported into ACM, the issuer must stay the same.
631
Amazon API Gateway Developer Guide
Mutual TLS
You must include the complete chain of trust, starting from the issuing CA certificate, up to the root
CA certificate, in your truststore. API Gateway accepts client certificates issued by any CA present in the
chain of trust. The certificates can be from public or private certificate authorities. Certificates can have
a maximum chain length of four. You can also provide self-signed certificates. The following hashing
algorithms are supported in the truststore:
• SHA-256 or stronger
• RSA-2048 or stronger
• ECDSA-256 or stronger
API Gateway validates a number of certificate properties. You can use Lambda authorizers to perform
additional checks when a client invokes an API, including checking whether a certificate has been
revoked. API Gateway validates the following properties:
Validation Description
Name chaining / key chaining The names and subjects of certificates must
form an unbroken chain. Certificates can have a
maximum chain length of four.
Example certificates.pem
-----BEGIN CERTIFICATE-----
<Certificate contents>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<Certificate contents>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<Certificate contents>
-----END CERTIFICATE-----
...
The following AWS CLI command uploads certificates.pem to your Amazon S3 bucket.
632
Amazon API Gateway Developer Guide
Mutual TLS
After you've uploaded your truststore to Amazon S3, you can configure your custom domain name to use
mutual TLS. Paste the following (slashes included) into a terminal:
After you create the domain name, you must configure DNS records and basepath mappings for API
operations. To learn more, see Setting up a regional custom domain name in API Gateway (p. 531).
The following example curl command sends a request to api.example.com, that includes my-
cert.pem in the request. my-key.key is the private key for the certificate.
Your API is invoked only if your truststore trusts the certificate. The following conditions will cause API
Gateway to fail the TLS handshake and deny the request with a 403 status code. If your certificate:
• isn't trusted
• is expired
• doesn't use a supported algorithm
Note
API Gateway doesn't verify if a certificate has been revoked.
Use Amazon S3 versioning to maintain multiple versions of your truststore. When you update your
custom domain name to use a new truststore version, API Gateway returns warnings if certificates are
invalid.
633
Amazon API Gateway Developer Guide
Mutual TLS
API Gateway produces certificate warnings only when you update your domain name. API Gateway
doesn’t notify you if a previously uploaded certificate expires.
The following AWS CLI command updates a custom domain name to use a new truststore version.
You'll need to decode the certificates in your truststore in order to identify which certificate produced
the warning. You can use tools such as openssl to decode the certificates and identify their subjects.
The following command displays the contents of a certificate, including its subject:
Update or remove the certificates that produced warnings, and then upload a new truststore to Amazon
S3. After uploading the new truststore, update your custom domain name to use the new truststore.
634
Amazon API Gateway Developer Guide
Client certificates
PENDING_OWNERSHIP_VERIFICATION: This means your previously verified certificate has expired and
ACM was unable to auto-renew it. You will need to renew the certificate or request a new certificate.
More information about certificate renewal can be found at ACM's troubleshooting managed certificate
renewal guide.
The SSL certificates that are generated by API Gateway are self-signed, and only the public key of a
certificate is visible in the API Gateway console or through the APIs.
Topics
• Generate a client certificate using the API Gateway console (p. 635)
• Configure an API to use SSL certificates (p. 635)
• Test invoke to verify the client certificate configuration (p. 636)
• Configure a backend HTTPS server to verify the client certificate (p. 636)
• Rotate an expiring client certificate (p. 637)
• API Gateway-supported certificate authorities for HTTP and HTTP proxy integrations (p. 638)
1. In the API Gateway console, create or open an API for which you want to use the client certificate.
Make sure that 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.
635
Amazon API Gateway Developer Guide
Client certificates
If the API has been deployed previously in the API Gateway console, you'll need to redeploy it for
the changes to take effect. For more information, see the section called “Redeploy a REST API to a
stage” (p. 492).
After a certificate is selected for the API and saved, API Gateway uses the certificate for all calls to HTTP
integrations in your API.
API Gateway presents the chosen SSL certificate for the HTTP backend to authenticate the API.
Before configuring a backend HTTPS server to verify the client SSL certificate of API Gateway, you must
have obtained the PEM-encoded private key and a server-side certificate that is provided by a trusted
certificate authority.
If the server domain name is myserver.mydomain.com, the server certificate's CNAME value must be
myserver.mydomain.com or *.mydomain.com.
Supported certificate authorities include Let's Encrypt or one of the section called “Supported certificate
authorities for HTTP and HTTP proxy integration” (p. 638).
As an example, suppose that the client certificate file is apig-cert.pem and the server private key and
certificate files are server-key.pem and server-cert.pem, respectively. For a Node.js server in the
backend, you can configure the server similar to the following:
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
ca: fs.readFileSync('apig-cert.pem'),
requestCert: true,
rejectUnauthorized: true
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(443);
For a node-express app, you can use the client-certificate-auth modules to authenticate client requests
with PEM-encoded certificates.
For other HTTPS server, see the documentation for the server.
636
Amazon API Gateway Developer Guide
Client certificates
1. Generate a new client certificate by calling clientcertificate:generate of the API Gateway REST API or
the AWS CLI command of generate-client-certificate. In this tutorial, we assume that the new client
certificate ID is ndiqef.
2. Update the backend server to include the new client certificate. Don't remove the existing client
certificate yet.
Some servers might require a restart to finish the update. Consult the server documentation to see if
you must restart the server during the update.
3. Update the API stage to use the new client certificate by calling stage:update of the API Gateway
REST API, with the new client certificate ID (ndiqef):
{
"patchOperations" : [
{
"op" : "replace",
"path" : "/clientCertificateId",
"value" : "ndiqef"
}
]
}
DELETE /clientcertificates/a1b2c3
To rotate a client certificate in the console for a previously deployed API, do the following:
637
Amazon API Gateway Developer Guide
Client certificates
You need to redeploy the API for the changes to take effect. For more information, see the section
called “Redeploy a REST API to a stage” (p. 492).
638
Amazon API Gateway Developer Guide
Client certificates
SHA256:
70:A7:3F:7F:37:6B:60:07:42:48:90:45:34:B1:14:82:D5:BF:0E:69:8E:CC:49:8D:F5:25:77:EB:F2:E9:3B:9A
Alias name: affirmtrustpremiumecc
SHA1: B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB
SHA256:
BD:71:FD:F6:DA:97:E4:CF:62:D1:64:7A:DD:25:81:B0:7D:79:AD:F8:39:7E:B4:EC:BA:9C:5E:84:88:82:14:23
Alias name: affirmtrustpremiumeccca
SHA1: B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB
SHA256:
BD:71:FD:F6:DA:97:E4:CF:62:D1:64:7A:DD:25:81:B0:7D:79:AD:F8:39:7E:B4:EC:BA:9C:5E:84:88:82:14:23
Alias name: amazon-ca-g4-acm1
SHA1: F2:0D:28:B6:29:C2:2C:5E:84:05:E6:02:4D:97:FE:8F:A0:84:93:A0
SHA256:
B0:11:A4:F7:29:6C:74:D8:2B:F5:62:DF:87:D7:28:C7:1F:B5:8C:F4:E6:73:F2:78:FC:DA:F3:FF:83:A6:8C:87
Alias name: amazon-ca-g4-acm2
SHA1: A7:E6:45:32:1F:7A:B7:AD:C0:70:EA:73:5F:AB:ED:C3:DA:B4:D0:C8
SHA256:
D7:A8:7C:69:95:D0:E2:04:2A:32:70:A7:E2:87:FE:A7:E8:F4:C1:70:62:F7:90:C3:EB:BB:53:F2:AC:39:26:BE
Alias name: amazon-ca-g4-acm3
SHA1: 7A:DB:56:57:5F:D6:EE:67:85:0A:64:BB:1C:E9:E4:B0:9A:DB:9D:07
SHA256:
6B:EB:9D:20:2E:C2:00:70:BD:D2:5E:D3:C0:C8:33:2C:B4:78:07:C5:82:94:4E:7E:23:28:22:71:A4:8E:0E:C2
Alias name: amazon-ca-g4-legacy
SHA1: EA:E7:DE:F9:0A:BE:9F:0B:68:CE:B7:24:0D:80:74:03:BF:6E:B1:6E
SHA256:
CD:72:C4:7F:B4:AD:28:A4:67:2B:E1:86:47:D4:40:E9:3B:16:2D:95:DB:3C:2F:94:BB:81:D9:09:F7:91:24:5E
Alias name: amazon-root-ca-ecc-384-1
SHA1: F9:5E:4A:AB:9C:2D:57:61:63:3D:B2:57:B4:0F:24:9E:7B:E2:23:7D
SHA256:
C6:BD:E5:66:C2:72:2A:0E:96:E9:C1:2C:BF:38:92:D9:55:4D:29:03:57:30:72:40:7F:4E:70:17:3B:3C:9B:63
Alias name: amazon-root-ca-rsa-2k-1
SHA1: 8A:9A:AC:27:FC:86:D4:50:23:AD:D5:63:F9:1E:AE:2C:AF:63:08:6C
SHA256:
0F:8F:33:83:FB:70:02:89:49:24:E1:AA:B0:D7:FB:5A:BF:98:DF:75:8E:0F:FE:61:86:92:BC:F0:75:35:CC:80
Alias name: amazon-root-ca-rsa-4k-1
SHA1: EC:BD:09:61:F5:7A:B6:A8:76:BB:20:8F:14:05:ED:7E:70:ED:39:45
SHA256:
36:AE:AD:C2:6A:60:07:90:6B:83:A3:73:2D:D1:2B:D4:00:5E:C7:F2:76:11:99:A9:D4:DA:63:2F:59:B2:8B:CF
Alias name: amazon1
SHA1: 8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16
SHA256:
8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E
Alias name: amazon2
SHA1: 5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A
SHA256:
1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4
Alias name: amazon3
SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E
SHA256:
18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4
Alias name: amazon4
SHA1: F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE
SHA256:
E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92
Alias name: amazonrootca1
SHA1: 8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16
SHA256:
8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E
Alias name: amazonrootca2
SHA1: 5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A
SHA256:
1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4
Alias name: amazonrootca3
SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E
SHA256:
18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4
639
Amazon API Gateway Developer Guide
Client certificates
640
Amazon API Gateway Developer Guide
Client certificates
SHA256:
0C:25:8A:12:A5:67:4A:EF:25:F2:8B:A7:DC:FA:EC:EE:A3:48:E5:41:E6:F5:CC:4E:E6:3B:71:B3:61:60:6A:C3
Alias name: camerfirmachambersignca
SHA1: 4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C
SHA256:
13:63:35:43:93:34:A7:69:80:16:A0:D3:24:DE:72:28:4E:07:9D:7B:52:20:BB:8F:BD:74:78:16:EE:BE:BA:CA
Alias name: certigna
SHA1: B1:2E:13:63:45:86:A4:6F:1A:B2:60:68:37:58:2D:C4:AC:FD:94:97
SHA256:
E3:B6:A2:DB:2E:D7:CE:48:84:2F:7A:C5:32:41:C7:B7:1D:54:14:4B:FB:40:C1:1F:3F:1D:0B:42:F5:EE:A1:2D
Alias name: certignarootca
SHA1: 2D:0D:52:14:FF:9E:AD:99:24:01:74:20:47:6E:6C:85:27:27:F5:43
SHA256:
D4:8D:3D:23:EE:DB:50:A4:59:E5:51:97:60:1C:27:77:4B:9D:7B:18:C9:4D:5A:05:95:11:A1:02:50:B9:31:68
Alias name: certplusclass2primaryca
SHA1: 74:20:74:41:72:9C:DD:92:EC:79:31:D8:23:10:8D:C2:81:92:E2:BB
SHA256:
0F:99:3C:8A:EF:97:BA:AF:56:87:14:0E:D5:9A:D1:82:1B:B4:AF:AC:F0:AA:9A:58:B5:D5:7A:33:8A:3A:FB:CB
Alias name: certplusclass3pprimaryca
SHA1: 21:6B:2A:29:E6:2A:00:CE:82:01:46:D8:24:41:41:B9:25:11:B2:79
SHA256:
CC:C8:94:89:37:1B:AD:11:1C:90:61:9B:EA:24:0A:2E:6D:AD:D9:9F:9F:6E:1D:4D:41:E5:8E:D6:DE:3D:02:85
Alias name: certsignrootca
SHA1: FA:B7:EE:36:97:26:62:FB:2D:B0:2A:F6:BF:03:FD:E8:7C:4B:2F:9B
SHA256:
EA:A9:62:C4:FA:4A:6B:AF:EB:E4:15:19:6D:35:1C:CD:88:8D:4F:53:F3:FA:8A:E6:D7:C4:66:A9:4E:60:42:BB
Alias name: certsignrootcag2
SHA1: 26:F9:93:B4:ED:3D:28:27:B0:B9:4B:A7:E9:15:1D:A3:8D:92:E5:32
SHA256:
65:7C:FE:2F:A7:3F:AA:38:46:25:71:F3:32:A2:36:3A:46:FC:E7:02:09:51:71:07:02:CD:FB:B6:EE:DA:33:05
Alias name: certum2
SHA1: D3:DD:48:3E:2B:BF:4C:05:E8:AF:10:F5:FA:76:26:CF:D3:DC:30:92
SHA256:
B6:76:F2:ED:DA:E8:77:5C:D3:6C:B0:F6:3C:D1:D4:60:39:61:F4:9E:62:65:BA:01:3A:2F:03:07:B6:D0:B8:04
Alias name: certumca
SHA1: 62:52:DC:40:F7:11:43:A2:2F:DE:9E:F7:34:8E:06:42:51:B1:81:18
SHA256:
D8:E0:FE:BC:1D:B2:E3:8D:00:94:0F:37:D2:7D:41:34:4D:99:3E:73:4B:99:D5:65:6D:97:78:D4:D8:14:36:24
Alias name: certumtrustednetworkca
SHA1: 07:E0:32:E0:20:B7:2C:3F:19:2F:06:28:A2:59:3A:19:A7:0F:06:9E
SHA256:
5C:58:46:8D:55:F5:8E:49:7E:74:39:82:D2:B5:00:10:B6:D1:65:37:4A:CF:83:A7:D4:A3:2D:B7:68:C4:40:8E
Alias name: certumtrustednetworkca2
SHA1: D3:DD:48:3E:2B:BF:4C:05:E8:AF:10:F5:FA:76:26:CF:D3:DC:30:92
SHA256:
B6:76:F2:ED:DA:E8:77:5C:D3:6C:B0:F6:3C:D1:D4:60:39:61:F4:9E:62:65:BA:01:3A:2F:03:07:B6:D0:B8:04
Alias name: cfcaevroot
SHA1: E2:B8:29:4B:55:84:AB:6B:58:C2:90:46:6C:AC:3F:B8:39:8F:84:83
SHA256:
5C:C3:D7:8E:4E:1D:5E:45:54:7A:04:E6:87:3E:64:F9:0C:F9:53:6D:1C:CC:2E:F8:00:F3:55:C4:C5:FD:70:FD
Alias name: chambersofcommerceroot2008
SHA1: 78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C
SHA256:
06:3E:4A:FA:C4:91:DF:D3:32:F3:08:9B:85:42:E9:46:17:D8:93:D7:FE:94:4E:10:A7:93:7E:E2:9D:96:93:C0
Alias name: chunghwaepkirootca
SHA1: 67:65:0D:F1:7E:8E:7E:5B:82:40:A4:F4:56:4B:CF:E2:3D:69:C6:F0
SHA256:
C0:A6:F4:DC:63:A2:4B:FD:CF:54:EF:2A:6A:08:2A:0A:72:DE:35:80:3E:2F:F5:FF:52:7A:E5:D8:72:06:DF:D5
Alias name: cia-crt-g3-01-ca
SHA1: 2B:EE:2C:BA:A3:1D:B5:FE:60:40:41:95:08:ED:46:82:39:4D:ED:E2
SHA256:
20:48:AD:4C:EC:90:7F:FA:4A:15:D4:CE:45:E3:C8:E4:2C:EA:78:33:DC:C7:D3:40:48:FC:60:47:27:42:99:EC
Alias name: cia-crt-g3-02-ca
SHA1: 96:4A:BB:A7:BD:DA:FC:97:34:C0:0A:2D:F0:05:98:F7:E6:C6:6F:09
SHA256:
93:F1:72:FB:BA:43:31:5C:06:EE:0F:9F:04:89:B8:F6:88:BC:75:15:3C:BE:B4:80:AC:A7:14:3A:F6:FC:4A:C1
641
Amazon API Gateway Developer Guide
Client certificates
642
Amazon API Gateway Developer Guide
Client certificates
SHA256:
55:2F:7B:DC:F1:A7:AF:9E:6C:E6:72:01:7F:4F:12:AB:F7:72:40:C7:8E:76:1A:C2:03:D1:D9:D2:0A:C8:99:88
Alias name: dstrootcax3
SHA1: DA:C9:02:4F:54:D8:F6:DF:94:93:5F:B1:73:26:38:CA:6A:D7:7C:13
SHA256:
06:87:26:03:31:A7:24:03:D9:09:F1:05:E6:9B:CF:0D:32:E1:BD:24:93:FF:C6:D9:20:6D:11:BC:D6:77:07:39
Alias name: dtrustrootclass3ca22009
SHA1: 58:E8:AB:B0:36:15:33:FB:80:F7:9B:1B:6D:29:D3:FF:8D:5F:00:F0
SHA256:
49:E7:A4:42:AC:F0:EA:62:87:05:00:54:B5:25:64:B6:50:E4:F4:9E:42:E3:48:D6:AA:38:E0:39:E9:57:B1:C1
Alias name: dtrustrootclass3ca2ev2009
SHA1: 96:C9:1B:0B:95:B4:10:98:42:FA:D0:D8:22:79:FE:60:FA:B9:16:83
SHA256:
EE:C5:49:6B:98:8C:E9:86:25:B9:34:09:2E:EC:29:08:BE:D0:B0:F3:16:C2:D4:73:0C:84:EA:F1:F3:D3:48:81
Alias name: ecacc
SHA1: 28:90:3A:63:5B:52:80:FA:E6:77:4C:0B:6D:A7:D6:BA:A6:4A:F2:E8
SHA256:
88:49:7F:01:60:2F:31:54:24:6A:E2:8C:4D:5A:EF:10:F1:D8:7E:BB:76:62:6F:4A:E0:B7:F9:5B:A7:96:87:99
Alias name: emsigneccrootcac3
SHA1: B6:AF:43:C2:9B:81:53:7D:F6:EF:6B:C3:1F:1F:60:15:0C:EE:48:66
SHA256:
BC:4D:80:9B:15:18:9D:78:DB:3E:1D:8C:F4:F9:72:6A:79:5D:A1:64:3C:A5:F1:35:8E:1D:DB:0E:DC:0D:7E:B3
Alias name: emsigneccrootcag3
SHA1: 30:43:FA:4F:F2:57:DC:A0:C3:80:EE:2E:58:EA:78:B2:3F:E6:BB:C1
SHA256:
86:A1:EC:BA:08:9C:4A:8D:3B:BE:27:34:C6:12:BA:34:1D:81:3E:04:3C:F9:E8:A8:62:CD:5C:57:A3:6B:BE:6B
Alias name: emsignrootcac1
SHA1: E7:2E:F1:DF:FC:B2:09:28:CF:5D:D4:D5:67:37:B1:51:CB:86:4F:01
SHA256:
12:56:09:AA:30:1D:A0:A2:49:B9:7A:82:39:CB:6A:34:21:6F:44:DC:AC:9F:39:54:B1:42:92:F2:E8:C8:60:8F
Alias name: emsignrootcag1
SHA1: 8A:C7:AD:8F:73:AC:4E:C1:B5:75:4D:A5:40:F4:FC:CF:7C:B5:8E:8C
SHA256:
40:F6:AF:03:46:A9:9A:A1:CD:1D:55:5A:4E:9C:CE:62:C7:F9:63:46:03:EE:40:66:15:83:3D:C8:C8:D0:03:67
Alias name: entrust2048ca
SHA1: 50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31
SHA256:
6D:C4:71:72:E0:1C:BC:B0:BF:62:58:0D:89:5F:E2:B8:AC:9A:D4:F8:73:80:1E:0C:10:B9:C8:37:D2:1E:B1:77
Alias name: entrustevca
SHA1: B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9
SHA256:
73:C1:76:43:4F:1B:C6:D5:AD:F4:5B:0E:76:E7:27:28:7C:8D:E5:76:16:C1:E6:E6:14:1A:2B:2C:BC:7D:8E:4C
Alias name: entrustnetpremium2048secureserverca
SHA1: 50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31
SHA256:
6D:C4:71:72:E0:1C:BC:B0:BF:62:58:0D:89:5F:E2:B8:AC:9A:D4:F8:73:80:1E:0C:10:B9:C8:37:D2:1E:B1:77
Alias name: entrustrootcag2
SHA1: 8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4
SHA256:
43:DF:57:74:B0:3E:7F:EF:5F:E4:0D:93:1A:7B:ED:F1:BB:2E:6B:42:73:8C:4E:6D:38:41:10:3D:3A:A7:F3:39
Alias name: entrustrootcertificationauthority
SHA1: B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9
SHA256:
73:C1:76:43:4F:1B:C6:D5:AD:F4:5B:0E:76:E7:27:28:7C:8D:E5:76:16:C1:E6:E6:14:1A:2B:2C:BC:7D:8E:4C
Alias name: entrustrootcertificationauthorityec1
SHA1: 20:D8:06:40:DF:9B:25:F5:12:25:3A:11:EA:F7:59:8A:EB:14:B5:47
SHA256:
02:ED:0E:B2:8C:14:DA:45:16:5C:56:67:91:70:0D:64:51:D7:FB:56:F0:B2:AB:1D:3B:8E:B0:70:E5:6E:DF:F5
Alias name: entrustrootcertificationauthorityg2
SHA1: 8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4
SHA256:
43:DF:57:74:B0:3E:7F:EF:5F:E4:0D:93:1A:7B:ED:F1:BB:2E:6B:42:73:8C:4E:6D:38:41:10:3D:3A:A7:F3:39
Alias name: entrustrootcertificationauthorityg4
SHA1: 14:88:4E:86:26:37:B0:26:AF:59:62:5C:40:77:EC:35:29:BA:96:01
SHA256:
DB:35:17:D1:F6:73:2A:2D:5A:B9:7C:53:3E:C7:07:79:EE:32:70:A6:2F:B4:AC:42:38:37:24:60:E6:F0:1E:88
643
Amazon API Gateway Developer Guide
Client certificates
644
Amazon API Gateway Developer Guide
Client certificates
SHA256:
A0:45:9B:9F:63:B2:25:59:F5:FA:5D:4C:6D:B3:F9:F7:2F:F1:93:42:03:35:78:F0:73:BF:1D:1B:46:CB:B9:12
Alias name: geotrustuniversalca2
SHA1: 37:9A:19:7B:41:85:45:35:0C:A6:03:69:F3:3C:2E:AF:47:4F:20:79
SHA256:
A0:23:4F:3B:C8:52:7C:A5:62:8E:EC:81:AD:5D:69:89:5D:A5:68:0D:C9:1D:1C:B8:47:7F:33:F8:78:B9:5B:0B
Alias name: globalchambersignroot2008
SHA1: 4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C
SHA256:
13:63:35:43:93:34:A7:69:80:16:A0:D3:24:DE:72:28:4E:07:9D:7B:52:20:BB:8F:BD:74:78:16:EE:BE:BA:CA
Alias name: globalsignca
SHA1: B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C
SHA256:
EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99
Alias name: globalsigneccrootcar4
SHA1: 69:69:56:2E:40:80:F4:24:A1:E7:19:9F:14:BA:F3:EE:58:AB:6A:BB
SHA256:
BE:C9:49:11:C2:95:56:76:DB:6C:0A:55:09:86:D7:6E:3B:A0:05:66:7C:44:2C:97:62:B4:FB:B7:73:DE:22:8C
Alias name: globalsigneccrootcar5
SHA1: 1F:24:C6:30:CD:A4:18:EF:20:69:FF:AD:4F:DD:5F:46:3A:1B:69:AA
SHA256:
17:9F:BC:14:8A:3D:D0:0F:D2:4E:A1:34:58:CC:43:BF:A7:F5:9C:81:82:D7:83:A5:13:F6:EB:EC:10:0C:89:24
Alias name: globalsignr2ca
SHA1: 75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE
SHA256:
CA:42:DD:41:74:5F:D0:B8:1E:B9:02:36:2C:F9:D8:BF:71:9D:A1:BD:1B:1E:FC:94:6F:5B:4C:99:F4:2C:1B:9E
Alias name: globalsignr3ca
SHA1: D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD
SHA256:
CB:B5:22:D7:B7:F1:27:AD:6A:01:13:86:5B:DF:1C:D4:10:2E:7D:07:59:AF:63:5A:7C:F4:72:0D:C9:63:C5:3B
Alias name: globalsignrootca
SHA1: B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C
SHA256:
EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99
Alias name: globalsignrootcar2
SHA1: 75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE
SHA256:
CA:42:DD:41:74:5F:D0:B8:1E:B9:02:36:2C:F9:D8:BF:71:9D:A1:BD:1B:1E:FC:94:6F:5B:4C:99:F4:2C:1B:9E
Alias name: globalsignrootcar3
SHA1: D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD
SHA256:
CB:B5:22:D7:B7:F1:27:AD:6A:01:13:86:5B:DF:1C:D4:10:2E:7D:07:59:AF:63:5A:7C:F4:72:0D:C9:63:C5:3B
Alias name: globalsignrootcar6
SHA1: 80:94:64:0E:B5:A7:A1:CA:11:9C:1F:DD:D5:9F:81:02:63:A7:FB:D1
SHA256:
2C:AB:EA:FE:37:D0:6C:A2:2A:BA:73:91:C0:03:3D:25:98:29:52:C4:53:64:73:49:76:3A:3A:B5:AD:6C:CF:69
Alias name: godaddyclass2ca
SHA1: 27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4
SHA256:
C3:84:6B:F2:4B:9E:93:CA:64:27:4C:0E:C6:7C:1E:CC:5E:02:4F:FC:AC:D2:D7:40:19:35:0E:81:FE:54:6A:E4
Alias name: godaddyrootcertificateauthorityg2
SHA1: 47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B
SHA256:
45:14:0B:32:47:EB:9C:C8:C5:B4:F0:D7:B5:30:91:F7:32:92:08:9E:6E:5A:63:E2:74:9D:D3:AC:A9:19:8E:DA
Alias name: godaddyrootg2ca
SHA1: 47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B
SHA256:
45:14:0B:32:47:EB:9C:C8:C5:B4:F0:D7:B5:30:91:F7:32:92:08:9E:6E:5A:63:E2:74:9D:D3:AC:A9:19:8E:DA
Alias name: gtsrootr1
SHA1: E1:C9:50:E6:EF:22:F8:4C:56:45:72:8B:92:20:60:D7:D5:A7:A3:E8
SHA256:
2A:57:54:71:E3:13:40:BC:21:58:1C:BD:2C:F1:3E:15:84:63:20:3E:CE:94:BC:F9:D3:CC:19:6B:F0:9A:54:72
Alias name: gtsrootr2
SHA1: D2:73:96:2A:2A:5E:39:9F:73:3F:E1:C7:1E:64:3F:03:38:34:FC:4D
SHA256:
C4:5D:7B:B0:8E:6D:67:E6:2E:42:35:11:0B:56:4E:5F:78:FD:92:EF:05:8C:84:0A:EA:4E:64:55:D7:58:5C:60
645
Amazon API Gateway Developer Guide
Client certificates
646
Amazon API Gateway Developer Guide
Client certificates
SHA256:
49:E7:A4:42:AC:F0:EA:62:87:05:00:54:B5:25:64:B6:50:E4:F4:9E:42:E3:48:D6:AA:38:E0:39:E9:57:B1:C1
Alias name: mozillacert101.pem
SHA1: 99:A6:9B:E6:1A:FE:88:6B:4D:2B:82:00:7C:B8:54:FC:31:7E:15:39
SHA256:
62:F2:40:27:8C:56:4C:4D:D8:BF:7D:9D:4F:6F:36:6E:A8:94:D2:2F:5F:34:D9:89:A9:83:AC:EC:2F:FF:ED:50
Alias name: mozillacert102.pem
SHA1: 96:C9:1B:0B:95:B4:10:98:42:FA:D0:D8:22:79:FE:60:FA:B9:16:83
SHA256:
EE:C5:49:6B:98:8C:E9:86:25:B9:34:09:2E:EC:29:08:BE:D0:B0:F3:16:C2:D4:73:0C:84:EA:F1:F3:D3:48:81
Alias name: mozillacert103.pem
SHA1: 70:C1:8D:74:B4:28:81:0A:E4:FD:A5:75:D7:01:9F:99:B0:3D:50:74
SHA256:
3C:FC:3C:14:D1:F6:84:FF:17:E3:8C:43:CA:44:0C:00:B9:67:EC:93:3E:8B:FE:06:4C:A1:D7:2C:90:F2:AD:B0
Alias name: mozillacert104.pem
SHA1: 4F:99:AA:93:FB:2B:D1:37:26:A1:99:4A:CE:7F:F0:05:F2:93:5D:1E
SHA256:
1C:01:C6:F4:DB:B2:FE:FC:22:55:8B:2B:CA:32:56:3F:49:84:4A:CF:C3:2B:7B:E4:B0:FF:59:9F:9E:8C:7A:F7
Alias name: mozillacert105.pem
SHA1: 77:47:4F:C6:30:E4:0F:4C:47:64:3F:84:BA:B8:C6:95:4A:8A:41:EC
SHA256:
F0:9B:12:2C:71:14:F4:A0:9B:D4:EA:4F:4A:99:D5:58:B4:6E:4C:25:CD:81:14:0D:29:C0:56:13:91:4C:38:41
Alias name: mozillacert106.pem
SHA1: E7:A1:90:29:D3:D5:52:DC:0D:0F:C6:92:D3:EA:88:0D:15:2E:1A:6B
SHA256:
D9:5F:EA:3C:A4:EE:DC:E7:4C:D7:6E:75:FC:6D:1F:F6:2C:44:1F:0F:A8:BC:77:F0:34:B1:9E:5D:B2:58:01:5D
Alias name: mozillacert107.pem
SHA1: 8E:1C:74:F8:A6:20:B9:E5:8A:F4:61:FA:EC:2B:47:56:51:1A:52:C6
SHA256:
F9:6F:23:F4:C3:E7:9C:07:7A:46:98:8D:5A:F5:90:06:76:A0:F0:39:CB:64:5D:D1:75:49:B2:16:C8:24:40:CE
Alias name: mozillacert108.pem
SHA1: B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C
SHA256:
EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99
Alias name: mozillacert109.pem
SHA1: B5:61:EB:EA:A4:DE:E4:25:4B:69:1A:98:A5:57:47:C2:34:C7:D9:71
SHA256:
E2:3D:4A:03:6D:7B:70:E9:F5:95:B1:42:20:79:D2:B9:1E:DF:BB:1F:B6:51:A0:63:3E:AA:8A:9D:C5:F8:07:03
Alias name: mozillacert11.pem
SHA1: 05:63:B8:63:0D:62:D7:5A:BB:C8:AB:1E:4B:DF:B5:A8:99:B2:4D:43
SHA256:
3E:90:99:B5:01:5E:8F:48:6C:00:BC:EA:9D:11:1E:E7:21:FA:BA:35:5A:89:BC:F1:DF:69:56:1E:3D:C6:32:5C
Alias name: mozillacert110.pem
SHA1: 93:05:7A:88:15:C6:4F:CE:88:2F:FA:91:16:52:28:78:BC:53:64:17
SHA256:
9A:6E:C0:12:E1:A7:DA:9D:BE:34:19:4D:47:8A:D7:C0:DB:18:22:FB:07:1D:F1:29:81:49:6E:D1:04:38:41:13
Alias name: mozillacert111.pem
SHA1: 9C:BB:48:53:F6:A4:F6:D3:52:A4:E8:32:52:55:60:13:F5:AD:AF:65
SHA256:
59:76:90:07:F7:68:5D:0F:CD:50:87:2F:9F:95:D5:75:5A:5B:2B:45:7D:81:F3:69:2B:61:0A:98:67:2F:0E:1B
Alias name: mozillacert112.pem
SHA1: 43:13:BB:96:F1:D5:86:9B:C1:4E:6A:92:F6:CF:F6:34:69:87:82:37
SHA256:
DD:69:36:FE:21:F8:F0:77:C1:23:A1:A5:21:C1:22:24:F7:22:55:B7:3E:03:A7:26:06:93:E8:A2:4B:0F:A3:89
Alias name: mozillacert113.pem
SHA1: 50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31
SHA256:
6D:C4:71:72:E0:1C:BC:B0:BF:62:58:0D:89:5F:E2:B8:AC:9A:D4:F8:73:80:1E:0C:10:B9:C8:37:D2:1E:B1:77
Alias name: mozillacert114.pem
SHA1: 51:C6:E7:08:49:06:6E:F3:92:D4:5C:A0:0D:6D:A3:62:8F:C3:52:39
SHA256:
B0:BF:D5:2B:B0:D7:D9:BD:92:BF:5D:4D:C1:3D:A2:55:C0:2C:54:2F:37:83:65:EA:89:39:11:F5:5E:55:F2:3C
Alias name: mozillacert115.pem
SHA1: 59:0D:2D:7D:88:4F:40:2E:61:7E:A5:62:32:17:65:CF:17:D8:94:E9
SHA256:
91:E2:F5:78:8D:58:10:EB:A7:BA:58:73:7D:E1:54:8A:8E:CA:CD:01:45:98:BC:0B:14:3E:04:1B:17:05:25:52
647
Amazon API Gateway Developer Guide
Client certificates
648
Amazon API Gateway Developer Guide
Client certificates
SHA256:
F4:C1:49:55:1A:30:13:A3:5B:C7:BF:FE:17:A7:F3:44:9B:C1:AB:5B:5A:0A:E7:4B:06:C2:3B:90:00:4C:01:04
Alias name: mozillacert131.pem
SHA1: 37:9A:19:7B:41:85:45:35:0C:A6:03:69:F3:3C:2E:AF:47:4F:20:79
SHA256:
A0:23:4F:3B:C8:52:7C:A5:62:8E:EC:81:AD:5D:69:89:5D:A5:68:0D:C9:1D:1C:B8:47:7F:33:F8:78:B9:5B:0B
Alias name: mozillacert132.pem
SHA1: 39:21:C1:15:C1:5D:0E:CA:5C:CB:5B:C4:F0:7D:21:D8:05:0B:56:6A
SHA256:
77:40:73:12:C6:3A:15:3D:5B:C0:0B:4E:51:75:9C:DF:DA:C2:37:DC:2A:33:B6:79:46:E9:8E:9B:FA:68:0A:E3
Alias name: mozillacert133.pem
SHA1: 85:B5:FF:67:9B:0C:79:96:1F:C8:6E:44:22:00:46:13:DB:17:92:84
SHA256:
7D:3B:46:5A:60:14:E5:26:C0:AF:FC:EE:21:27:D2:31:17:27:AD:81:1C:26:84:2D:00:6A:F3:73:06:CC:80:BD
Alias name: mozillacert134.pem
SHA1: 70:17:9B:86:8C:00:A4:FA:60:91:52:22:3F:9F:3E:32:BD:E0:05:62
SHA256:
69:FA:C9:BD:55:FB:0A:C7:8D:53:BB:EE:5C:F1:D5:97:98:9F:D0:AA:AB:20:A2:51:51:BD:F1:73:3E:E7:D1:22
Alias name: mozillacert135.pem
SHA1: 62:52:DC:40:F7:11:43:A2:2F:DE:9E:F7:34:8E:06:42:51:B1:81:18
SHA256:
D8:E0:FE:BC:1D:B2:E3:8D:00:94:0F:37:D2:7D:41:34:4D:99:3E:73:4B:99:D5:65:6D:97:78:D4:D8:14:36:24
Alias name: mozillacert136.pem
SHA1: D1:EB:23:A4:6D:17:D6:8F:D9:25:64:C2:F1:F1:60:17:64:D8:E3:49
SHA256:
D7:A7:A0:FB:5D:7E:27:31:D7:71:E9:48:4E:BC:DE:F7:1D:5F:0C:3E:0A:29:48:78:2B:C8:3E:E0:EA:69:9E:F4
Alias name: mozillacert137.pem
SHA1: 4A:65:D5:F4:1D:EF:39:B8:B8:90:4A:4A:D3:64:81:33:CF:C7:A1:D1
SHA256:
BD:81:CE:3B:4F:65:91:D1:1A:67:B5:FC:7A:47:FD:EF:25:52:1B:F9:AA:4E:18:B9:E3:DF:2E:34:A7:80:3B:E8
Alias name: mozillacert138.pem
SHA1: E1:9F:E3:0E:8B:84:60:9E:80:9B:17:0D:72:A8:C5:BA:6E:14:09:BD
SHA256:
3F:06:E5:56:81:D4:96:F5:BE:16:9E:B5:38:9F:9F:2B:8F:F6:1E:17:08:DF:68:81:72:48:49:CD:5D:27:CB:69
Alias name: mozillacert139.pem
SHA1: DE:3F:40:BD:50:93:D3:9B:6C:60:F6:DA:BC:07:62:01:00:89:76:C9
SHA256:
A4:5E:DE:3B:BB:F0:9C:8A:E1:5C:72:EF:C0:72:68:D6:93:A2:1C:99:6F:D5:1E:67:CA:07:94:60:FD:6D:88:73
Alias name: mozillacert14.pem
SHA1: 5F:B7:EE:06:33:E2:59:DB:AD:0C:4C:9A:E6:D3:8F:1A:61:C7:DC:25
SHA256:
74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
Alias name: mozillacert140.pem
SHA1: CA:3A:FB:CF:12:40:36:4B:44:B2:16:20:88:80:48:39:19:93:7C:F7
SHA256:
85:A0:DD:7D:D7:20:AD:B7:FF:05:F8:3D:54:2B:20:9D:C7:FF:45:28:F7:D6:77:B1:83:89:FE:A5:E5:C4:9E:86
Alias name: mozillacert141.pem
SHA1: 31:7A:2A:D0:7F:2B:33:5E:F5:A1:C3:4E:4B:57:E8:B7:D8:F1:FC:A6
SHA256:
58:D0:17:27:9C:D4:DC:63:AB:DD:B1:96:A6:C9:90:6C:30:C4:E0:87:83:EA:E8:C1:60:99:54:D6:93:55:59:6B
Alias name: mozillacert142.pem
SHA1: 1F:49:14:F7:D8:74:95:1D:DD:AE:02:C0:BE:FD:3A:2D:82:75:51:85
SHA256:
18:F1:FC:7F:20:5D:F8:AD:DD:EB:7F:E0:07:DD:57:E3:AF:37:5A:9C:4D:8D:73:54:6B:F4:F1:FE:D1:E1:8D:35
Alias name: mozillacert143.pem
SHA1: 36:B1:2B:49:F9:81:9E:D7:4C:9E:BC:38:0F:C6:56:8F:5D:AC:B2:F7
SHA256:
E7:5E:72:ED:9F:56:0E:EC:6E:B4:80:00:73:A4:3F:C3:AD:19:19:5A:39:22:82:01:78:95:97:4A:99:02:6B:6C
Alias name: mozillacert144.pem
SHA1: 37:F7:6D:E6:07:7C:90:C5:B1:3E:93:1A:B7:41:10:B4:F2:E4:9A:27
SHA256:
79:08:B4:03:14:C1:38:10:0B:51:8D:07:35:80:7F:FB:FC:F8:51:8A:00:95:33:71:05:BA:38:6B:15:3D:D9:27
Alias name: mozillacert145.pem
SHA1: 10:1D:FA:3F:D5:0B:CB:BB:9B:B5:60:0C:19:55:A4:1A:F4:73:3A:04
SHA256:
D4:1D:82:9E:8C:16:59:82:2A:F9:3F:CE:62:BF:FC:DE:26:4F:C8:4E:8B:95:0C:5F:F2:75:D0:52:35:46:95:A3
649
Amazon API Gateway Developer Guide
Client certificates
650
Amazon API Gateway Developer Guide
Client certificates
SHA256:
66:8C:83:94:7D:A6:3B:72:4B:EC:E1:74:3C:31:A0:E6:AE:D0:DB:8E:C5:B3:1B:E3:77:BB:78:4F:91:B6:71:6F
Alias name: mozillacert25.pem
SHA1: 4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5
SHA256:
9A:CF:AB:7E:43:C8:D8:80:D0:6B:26:2A:94:DE:EE:E4:B4:65:99:89:C3:D0:CA:F1:9B:AF:64:05:E4:1A:B7:DF
Alias name: mozillacert26.pem
SHA1: 87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11
SHA256:
F1:C1:B5:0A:E5:A2:0D:D8:03:0E:C9:F6:BC:24:82:3D:D3:67:B5:25:57:59:B4:E7:1B:61:FC:E9:F7:37:5D:73
Alias name: mozillacert27.pem
SHA1: 3A:44:73:5A:E5:81:90:1F:24:86:61:46:1E:3B:9C:C4:5F:F5:3A:1B
SHA256:
42:00:F5:04:3A:C8:59:0E:BB:52:7D:20:9E:D1:50:30:29:FB:CB:D4:1C:A1:B5:06:EC:27:F1:5A:DE:7D:AC:69
Alias name: mozillacert28.pem
SHA1: 66:31:BF:9E:F7:4F:9E:B6:C9:D5:A6:0C:BA:6A:BE:D1:F7:BD:EF:7B
SHA256:
0C:2C:D6:3D:F7:80:6F:A3:99:ED:E8:09:11:6B:57:5B:F8:79:89:F0:65:18:F9:80:8C:86:05:03:17:8B:AF:66
Alias name: mozillacert29.pem
SHA1: 74:F8:A3:C3:EF:E7:B3:90:06:4B:83:90:3C:21:64:60:20:E5:DF:CE
SHA256:
15:F0:BA:00:A3:AC:7A:F3:AC:88:4C:07:2B:10:11:A0:77:BD:77:C0:97:F4:01:64:B2:F8:59:8A:BD:83:86:0C
Alias name: mozillacert3.pem
SHA1: 87:9F:4B:EE:05:DF:98:58:3B:E3:60:D6:33:E7:0D:3F:FE:98:71:AF
SHA256:
39:DF:7B:68:2B:7B:93:8F:84:71:54:81:CC:DE:8D:60:D8:F2:2E:C5:98:87:7D:0A:AA:C1:2B:59:18:2B:03:12
Alias name: mozillacert30.pem
SHA1: E7:B4:F6:9D:61:EC:90:69:DB:7E:90:A7:40:1A:3C:F4:7D:4F:E8:EE
SHA256:
A7:12:72:AE:AA:A3:CF:E8:72:7F:7F:B3:9F:0F:B3:D1:E5:42:6E:90:60:B0:6E:E6:F1:3E:9A:3C:58:33:CD:43
Alias name: mozillacert31.pem
SHA1: 9F:74:4E:9F:2B:4D:BA:EC:0F:31:2C:50:B6:56:3B:8E:2D:93:C3:11
SHA256:
17:93:92:7A:06:14:54:97:89:AD:CE:2F:8F:34:F7:F0:B6:6D:0F:3A:E3:A3:B8:4D:21:EC:15:DB:BA:4F:AD:C7
Alias name: mozillacert32.pem
SHA1: 60:D6:89:74:B5:C2:65:9E:8A:0F:C1:88:7C:88:D2:46:69:1B:18:2C
SHA256:
B9:BE:A7:86:0A:96:2E:A3:61:1D:AB:97:AB:6D:A3:E2:1C:10:68:B9:7D:55:57:5E:D0:E1:12:79:C1:1C:89:32
Alias name: mozillacert33.pem
SHA1: FE:B8:C4:32:DC:F9:76:9A:CE:AE:3D:D8:90:8F:FD:28:86:65:64:7D
SHA256:
A2:2D:BA:68:1E:97:37:6E:2D:39:7D:72:8A:AE:3A:9B:62:96:B9:FD:BA:60:BC:2E:11:F6:47:F2:C6:75:FB:37
Alias name: mozillacert34.pem
SHA1: 59:22:A1:E1:5A:EA:16:35:21:F8:98:39:6A:46:46:B0:44:1B:0F:A9
SHA256:
41:C9:23:86:6A:B4:CA:D6:B7:AD:57:80:81:58:2E:02:07:97:A6:CB:DF:4F:FF:78:CE:83:96:B3:89:37:D7:F5
Alias name: mozillacert35.pem
SHA1: 2A:C8:D5:8B:57:CE:BF:2F:49:AF:F2:FC:76:8F:51:14:62:90:7A:41
SHA256:
92:BF:51:19:AB:EC:CA:D0:B1:33:2D:C4:E1:D0:5F:BA:75:B5:67:90:44:EE:0C:A2:6E:93:1F:74:4F:2F:33:CF
Alias name: mozillacert36.pem
SHA1: 23:88:C9:D3:71:CC:9E:96:3D:FF:7D:3C:A7:CE:FC:D6:25:EC:19:0D
SHA256:
32:7A:3D:76:1A:BA:DE:A0:34:EB:99:84:06:27:5C:B1:A4:77:6E:FD:AE:2F:DF:6D:01:68:EA:1C:4F:55:67:D0
Alias name: mozillacert37.pem
SHA1: B1:2E:13:63:45:86:A4:6F:1A:B2:60:68:37:58:2D:C4:AC:FD:94:97
SHA256:
E3:B6:A2:DB:2E:D7:CE:48:84:2F:7A:C5:32:41:C7:B7:1D:54:14:4B:FB:40:C1:1F:3F:1D:0B:42:F5:EE:A1:2D
Alias name: mozillacert38.pem
SHA1: CB:A1:C5:F8:B0:E3:5E:B8:B9:45:12:D3:F9:34:A2:E9:06:10:D3:36
SHA256:
A6:C5:1E:0D:A5:CA:0A:93:09:D2:E4:C0:E4:0C:2A:F9:10:7A:AE:82:03:85:7F:E1:98:E3:E7:69:E3:43:08:5C
Alias name: mozillacert39.pem
SHA1: AE:50:83:ED:7C:F4:5C:BC:8F:61:C6:21:FE:68:5D:79:42:21:15:6E
SHA256:
E6:B8:F8:76:64:85:F8:07:AE:7F:8D:AC:16:70:46:1F:07:C0:A1:3E:EF:3A:1F:F7:17:53:8D:7A:BA:D3:91:B4
651
Amazon API Gateway Developer Guide
Client certificates
652
Amazon API Gateway Developer Guide
Client certificates
SHA256:
B4:78:B8:12:25:0D:F8:78:63:5C:2A:A7:EC:7D:15:5E:AA:62:5E:E8:29:16:E2:CD:29:43:61:88:6C:D1:FB:D4
Alias name: mozillacert55.pem
SHA1: AA:DB:BC:22:23:8F:C4:01:A1:27:BB:38:DD:F4:1D:DB:08:9E:F0:12
SHA256:
A4:31:0D:50:AF:18:A6:44:71:90:37:2A:86:AF:AF:8B:95:1F:FB:43:1D:83:7F:1E:56:88:B4:59:71:ED:15:57
Alias name: mozillacert56.pem
SHA1: F1:8B:53:8D:1B:E9:03:B6:A6:F0:56:43:5B:17:15:89:CA:F3:6B:F2
SHA256:
4B:03:F4:58:07:AD:70:F2:1B:FC:2C:AE:71:C9:FD:E4:60:4C:06:4C:F5:FF:B6:86:BA:E5:DB:AA:D7:FD:D3:4C
Alias name: mozillacert57.pem
SHA1: D6:DA:A8:20:8D:09:D2:15:4D:24:B5:2F:CB:34:6E:B2:58:B2:8A:58
SHA256:
F9:E6:7D:33:6C:51:00:2A:C0:54:C6:32:02:2D:66:DD:A2:E7:E3:FF:F1:0A:D0:61:ED:31:D8:BB:B4:10:CF:B2
Alias name: mozillacert58.pem
SHA1: 8D:17:84:D5:37:F3:03:7D:EC:70:FE:57:8B:51:9A:99:E6:10:D7:B0
SHA256:
5E:DB:7A:C4:3B:82:A0:6A:87:61:E8:D7:BE:49:79:EB:F2:61:1F:7D:D7:9B:F9:1C:1C:6B:56:6A:21:9E:D7:66
Alias name: mozillacert59.pem
SHA1: 36:79:CA:35:66:87:72:30:4D:30:A5:FB:87:3B:0F:A7:7B:B7:0D:54
SHA256:
23:99:56:11:27:A5:71:25:DE:8C:EF:EA:61:0D:DF:2F:A0:78:B5:C8:06:7F:4E:82:82:90:BF:B8:60:E8:4B:3C
Alias name: mozillacert6.pem
SHA1: 27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4
SHA256:
C3:84:6B:F2:4B:9E:93:CA:64:27:4C:0E:C6:7C:1E:CC:5E:02:4F:FC:AC:D2:D7:40:19:35:0E:81:FE:54:6A:E4
Alias name: mozillacert60.pem
SHA1: 3B:C4:9F:48:F8:F3:73:A0:9C:1E:BD:F8:5B:B1:C3:65:C7:D8:11:B3
SHA256:
BF:0F:EE:FB:9E:3A:58:1A:D5:F9:E9:DB:75:89:98:57:43:D2:61:08:5C:4D:31:4F:6F:5D:72:59:AA:42:16:12
Alias name: mozillacert61.pem
SHA1: E0:B4:32:2E:B2:F6:A5:68:B6:54:53:84:48:18:4A:50:36:87:43:84
SHA256:
03:95:0F:B4:9A:53:1F:3E:19:91:94:23:98:DF:A9:E0:EA:32:D7:BA:1C:DD:9B:C8:5D:B5:7E:D9:40:0B:43:4A
Alias name: mozillacert62.pem
SHA1: A1:DB:63:93:91:6F:17:E4:18:55:09:40:04:15:C7:02:40:B0:AE:6B
SHA256:
A4:B6:B3:99:6F:C2:F3:06:B3:FD:86:81:BD:63:41:3D:8C:50:09:CC:4F:A3:29:C2:CC:F0:E2:FA:1B:14:03:05
Alias name: mozillacert63.pem
SHA1: 89:DF:74:FE:5C:F4:0F:4A:80:F9:E3:37:7D:54:DA:91:E1:01:31:8E
SHA256:
3C:5F:81:FE:A5:FA:B8:2C:64:BF:A2:EA:EC:AF:CD:E8:E0:77:FC:86:20:A7:CA:E5:37:16:3D:F3:6E:DB:F3:78
Alias name: mozillacert64.pem
SHA1: 62:7F:8D:78:27:65:63:99:D2:7D:7F:90:44:C9:FE:B3:F3:3E:FA:9A
SHA256:
AB:70:36:36:5C:71:54:AA:29:C2:C2:9F:5D:41:91:16:3B:16:2A:22:25:01:13:57:D5:6D:07:FF:A7:BC:1F:72
Alias name: mozillacert65.pem
SHA1: 69:BD:8C:F4:9C:D3:00:FB:59:2E:17:93:CA:55:6A:F3:EC:AA:35:FB
SHA256:
BC:23:F9:8A:31:3C:B9:2D:E3:BB:FC:3A:5A:9F:44:61:AC:39:49:4C:4A:E1:5A:9E:9D:F1:31:E9:9B:73:01:9A
Alias name: mozillacert66.pem
SHA1: DD:E1:D2:A9:01:80:2E:1D:87:5E:84:B3:80:7E:4B:B1:FD:99:41:34
SHA256:
E6:09:07:84:65:A4:19:78:0C:B6:AC:4C:1C:0B:FB:46:53:D9:D9:CC:6E:B3:94:6E:B7:F3:D6:99:97:BA:D5:98
Alias name: mozillacert67.pem
SHA1: D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD
SHA256:
CB:B5:22:D7:B7:F1:27:AD:6A:01:13:86:5B:DF:1C:D4:10:2E:7D:07:59:AF:63:5A:7C:F4:72:0D:C9:63:C5:3B
Alias name: mozillacert68.pem
SHA1: AE:C5:FB:3F:C8:E1:BF:C4:E5:4F:03:07:5A:9A:E8:00:B7:F7:B6:FA
SHA256:
04:04:80:28:BF:1F:28:64:D4:8F:9A:D4:D8:32:94:36:6A:82:88:56:55:3F:3B:14:30:3F:90:14:7F:5D:40:EF
Alias name: mozillacert69.pem
SHA1: 2F:78:3D:25:52:18:A7:4A:65:39:71:B5:2C:A2:9C:45:15:6F:E9:19
SHA256:
25:30:CC:8E:98:32:15:02:BA:D9:6F:9B:1F:BA:1B:09:9E:2D:29:9E:0F:45:48:BB:91:4F:36:3B:C0:D4:53:1F
653
Amazon API Gateway Developer Guide
Client certificates
654
Amazon API Gateway Developer Guide
Client certificates
SHA256:
79:3C:BF:45:59:B9:FD:E3:8A:B2:2D:F1:68:69:F6:98:81:AE:14:C4:B0:13:9A:C7:88:A7:8A:1A:FC:CA:02:FB
Alias name: mozillacert85.pem
SHA1: CF:9E:87:6D:D3:EB:FC:42:26:97:A3:B5:A3:7A:A0:76:A9:06:23:48
SHA256:
BF:D8:8F:E1:10:1C:41:AE:3E:80:1B:F8:BE:56:35:0E:E9:BA:D1:A6:B9:BD:51:5E:DC:5C:6D:5B:87:11:AC:44
Alias name: mozillacert86.pem
SHA1: 74:2C:31:92:E6:07:E4:24:EB:45:49:54:2B:E1:BB:C5:3E:61:74:E2
SHA256:
E7:68:56:34:EF:AC:F6:9A:CE:93:9A:6B:25:5B:7B:4F:AB:EF:42:93:5B:50:A2:65:AC:B5:CB:60:27:E4:4E:70
Alias name: mozillacert87.pem
SHA1: 5F:3B:8C:F2:F8:10:B3:7D:78:B4:CE:EC:19:19:C3:73:34:B9:C7:74
SHA256:
51:3B:2C:EC:B8:10:D4:CD:E5:DD:85:39:1A:DF:C6:C2:DD:60:D8:7B:B7:36:D2:B5:21:48:4A:A4:7A:0E:BE:F6
Alias name: mozillacert88.pem
SHA1: FE:45:65:9B:79:03:5B:98:A1:61:B5:51:2E:AC:DA:58:09:48:22:4D
SHA256:
BC:10:4F:15:A4:8B:E7:09:DC:A5:42:A7:E1:D4:B9:DF:6F:05:45:27:E8:02:EA:A9:2D:59:54:44:25:8A:FE:71
Alias name: mozillacert89.pem
SHA1: C8:EC:8C:87:92:69:CB:4B:AB:39:E9:8D:7E:57:67:F3:14:95:73:9D
SHA256:
E3:89:36:0D:0F:DB:AE:B3:D2:50:58:4B:47:30:31:4E:22:2F:39:C1:56:A0:20:14:4E:8D:96:05:61:79:15:06
Alias name: mozillacert9.pem
SHA1: F4:8B:11:BF:DE:AB:BE:94:54:20:71:E6:41:DE:6B:BE:88:2B:40:B9
SHA256:
76:00:29:5E:EF:E8:5B:9E:1F:D6:24:DB:76:06:2A:AA:AE:59:81:8A:54:D2:77:4C:D4:C0:B2:C0:11:31:E1:B3
Alias name: mozillacert90.pem
SHA1: F3:73:B3:87:06:5A:28:84:8A:F2:F3:4A:CE:19:2B:DD:C7:8E:9C:AC
SHA256:
55:92:60:84:EC:96:3A:64:B9:6E:2A:BE:01:CE:0B:A8:6A:64:FB:FE:BC:C7:AA:B5:AF:C1:55:B3:7F:D7:60:66
Alias name: mozillacert91.pem
SHA1: 3B:C0:38:0B:33:C3:F6:A6:0C:86:15:22:93:D9:DF:F5:4B:81:C0:04
SHA256:
C1:B4:82:99:AB:A5:20:8F:E9:63:0A:CE:55:CA:68:A0:3E:DA:5A:51:9C:88:02:A0:D3:A6:73:BE:8F:8E:55:7D
Alias name: mozillacert92.pem
SHA1: A3:F1:33:3F:E2:42:BF:CF:C5:D1:4E:8F:39:42:98:40:68:10:D1:A0
SHA256:
E1:78:90:EE:09:A3:FB:F4:F4:8B:9C:41:4A:17:D6:37:B7:A5:06:47:E9:BC:75:23:22:72:7F:CC:17:42:A9:11
Alias name: mozillacert93.pem
SHA1: 31:F1:FD:68:22:63:20:EE:C6:3B:3F:9D:EA:4A:3E:53:7C:7C:39:17
SHA256:
C7:BA:65:67:DE:93:A7:98:AE:1F:AA:79:1E:71:2D:37:8F:AE:1F:93:C4:39:7F:EA:44:1B:B7:CB:E6:FD:59:95
Alias name: mozillacert94.pem
SHA1: 49:0A:75:74:DE:87:0A:47:FE:58:EE:F6:C7:6B:EB:C6:0B:12:40:99
SHA256:
9A:11:40:25:19:7C:5B:B9:5D:94:E6:3D:55:CD:43:79:08:47:B6:46:B2:3C:DF:11:AD:A4:A0:0E:FF:15:FB:48
Alias name: mozillacert95.pem
SHA1: DA:FA:F7:FA:66:84:EC:06:8F:14:50:BD:C7:C2:81:A5:BC:A9:64:57
SHA256:
ED:F7:EB:BC:A2:7A:2A:38:4D:38:7B:7D:40:10:C6:66:E2:ED:B4:84:3E:4C:29:B4:AE:1D:5B:93:32:E6:B2:4D
Alias name: mozillacert96.pem
SHA1: 55:A6:72:3E:CB:F2:EC:CD:C3:23:74:70:19:9D:2A:BE:11:E3:81:D1
SHA256:
FD:73:DA:D3:1C:64:4F:F1:B4:3B:EF:0C:CD:DA:96:71:0B:9C:D9:87:5E:CA:7E:31:70:7A:F3:E9:6D:52:2B:BD
Alias name: mozillacert97.pem
SHA1: 85:37:1C:A6:E5:50:14:3D:CE:28:03:47:1B:DE:3A:09:E8:F8:77:0F
SHA256:
83:CE:3C:12:29:68:8A:59:3D:48:5F:81:97:3C:0F:91:95:43:1E:DA:37:CC:5E:36:43:0E:79:C7:A8:88:63:8B
Alias name: mozillacert98.pem
SHA1: C9:A8:B9:E7:55:80:5E:58:E3:53:77:A7:25:EB:AF:C3:7B:27:CC:D7
SHA256:
3E:84:BA:43:42:90:85:16:E7:75:73:C0:99:2F:09:79:CA:08:4E:46:85:68:1F:F1:95:CC:BA:8A:22:9B:8A:76
Alias name: mozillacert99.pem
SHA1: F1:7F:6F:B6:31:DC:99:E3:A3:C8:7F:FE:1C:F1:81:10:88:D9:60:33
SHA256:
97:8C:D9:66:F2:FA:A0:7B:A7:AA:95:00:D9:C0:2E:9D:77:F2:CD:AD:A6:AD:6B:A7:4A:F4:B9:1C:66:59:3C:50
655
Amazon API Gateway Developer Guide
Client certificates
656
Amazon API Gateway Developer Guide
Client certificates
SHA256:
BF:0F:EE:FB:9E:3A:58:1A:D5:F9:E9:DB:75:89:98:57:43:D2:61:08:5C:4D:31:4F:6F:5D:72:59:AA:42:16:12
Alias name: securetrustca
SHA1: 87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11
SHA256:
F1:C1:B5:0A:E5:A2:0D:D8:03:0E:C9:F6:BC:24:82:3D:D3:67:B5:25:57:59:B4:E7:1B:61:FC:E9:F7:37:5D:73
Alias name: securitycommunicationrootca
SHA1: 36:B1:2B:49:F9:81:9E:D7:4C:9E:BC:38:0F:C6:56:8F:5D:AC:B2:F7
SHA256:
E7:5E:72:ED:9F:56:0E:EC:6E:B4:80:00:73:A4:3F:C3:AD:19:19:5A:39:22:82:01:78:95:97:4A:99:02:6B:6C
Alias name: securitycommunicationrootca2
SHA1: 5F:3B:8C:F2:F8:10:B3:7D:78:B4:CE:EC:19:19:C3:73:34:B9:C7:74
SHA256:
51:3B:2C:EC:B8:10:D4:CD:E5:DD:85:39:1A:DF:C6:C2:DD:60:D8:7B:B7:36:D2:B5:21:48:4A:A4:7A:0E:BE:F6
Alias name: soneraclass1ca
SHA1: 07:47:22:01:99:CE:74:B9:7C:B0:3D:79:B2:64:A2:C8:55:E9:33:FF
SHA256:
CD:80:82:84:CF:74:6F:F2:FD:6E:B5:8A:A1:D5:9C:4A:D4:B3:CA:56:FD:C6:27:4A:89:26:A7:83:5F:32:31:3D
Alias name: soneraclass2ca
SHA1: 37:F7:6D:E6:07:7C:90:C5:B1:3E:93:1A:B7:41:10:B4:F2:E4:9A:27
SHA256:
79:08:B4:03:14:C1:38:10:0B:51:8D:07:35:80:7F:FB:FC:F8:51:8A:00:95:33:71:05:BA:38:6B:15:3D:D9:27
Alias name: soneraclass2rootca
SHA1: 37:F7:6D:E6:07:7C:90:C5:B1:3E:93:1A:B7:41:10:B4:F2:E4:9A:27
SHA256:
79:08:B4:03:14:C1:38:10:0B:51:8D:07:35:80:7F:FB:FC:F8:51:8A:00:95:33:71:05:BA:38:6B:15:3D:D9:27
Alias name: sslcomevrootcertificationauthorityecc
SHA1: 4C:DD:51:A3:D1:F5:20:32:14:B0:C6:C5:32:23:03:91:C7:46:42:6D
SHA256:
22:A2:C1:F7:BD:ED:70:4C:C1:E7:01:B5:F4:08:C3:10:88:0F:E9:56:B5:DE:2A:4A:44:F9:9C:87:3A:25:A7:C8
Alias name: sslcomevrootcertificationauthorityrsar2
SHA1: 74:3A:F0:52:9B:D0:32:A0:F4:4A:83:CD:D4:BA:A9:7B:7C:2E:C4:9A
SHA256:
2E:7B:F1:6C:C2:24:85:A7:BB:E2:AA:86:96:75:07:61:B0:AE:39:BE:3B:2F:E9:D0:CC:6D:4E:F7:34:91:42:5C
Alias name: sslcomrootcertificationauthorityecc
SHA1: C3:19:7C:39:24:E6:54:AF:1B:C4:AB:20:95:7A:E2:C3:0E:13:02:6A
SHA256:
34:17:BB:06:CC:60:07:DA:1B:96:1C:92:0B:8A:B4:CE:3F:AD:82:0E:4A:A3:0B:9A:CB:C4:A7:4E:BD:CE:BC:65
Alias name: sslcomrootcertificationauthorityrsa
SHA1: B7:AB:33:08:D1:EA:44:77:BA:14:80:12:5A:6F:BD:A9:36:49:0C:BB
SHA256:
85:66:6A:56:2E:E0:BE:5C:E9:25:C1:D8:89:0A:6F:76:A8:7E:C1:6D:4D:7D:5F:29:EA:74:19:CF:20:12:3B:69
Alias name: staatdernederlandenevrootca
SHA1: 76:E2:7E:C1:4F:DB:82:C1:C0:A6:75:B5:05:BE:3D:29:B4:ED:DB:BB
SHA256:
4D:24:91:41:4C:FE:95:67:46:EC:4C:EF:A6:CF:6F:72:E2:8A:13:29:43:2F:9D:8A:90:7A:C4:CB:5D:AD:C1:5A
Alias name: staatdernederlandenrootcag3
SHA1: D8:EB:6B:41:51:92:59:E0:F3:E7:85:00:C0:3D:B6:88:97:C9:EE:FC
SHA256:
3C:4F:B0:B9:5A:B8:B3:00:32:F4:32:B8:6F:53:5F:E1:72:C1:85:D0:FD:39:86:58:37:CF:36:18:7F:A6:F4:28
Alias name: starfieldclass2ca
SHA1: AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A
SHA256:
14:65:FA:20:53:97:B8:76:FA:A6:F0:A9:95:8E:55:90:E4:0F:CC:7F:AA:4F:B7:C2:C8:67:75:21:FB:5F:B6:58
Alias name: starfieldrootcertificateauthorityg2
SHA1: B5:1C:06:7C:EE:2B:0C:3D:F8:55:AB:2D:92:F4:FE:39:D4:E7:0F:0E
SHA256:
2C:E1:CB:0B:F9:D2:F9:E1:02:99:3F:BE:21:51:52:C3:B2:DD:0C:AB:DE:1C:68:E5:31:9B:83:91:54:DB:B7:F5
Alias name: starfieldrootg2ca
SHA1: B5:1C:06:7C:EE:2B:0C:3D:F8:55:AB:2D:92:F4:FE:39:D4:E7:0F:0E
SHA256:
2C:E1:CB:0B:F9:D2:F9:E1:02:99:3F:BE:21:51:52:C3:B2:DD:0C:AB:DE:1C:68:E5:31:9B:83:91:54:DB:B7:F5
Alias name: starfieldservicesrootcertificateauthorityg2
SHA1: 92:5A:8F:8D:2C:6D:04:E0:66:5F:59:6A:FF:22:D8:63:E8:25:6F:3F
SHA256:
56:8D:69:05:A2:C8:87:08:A4:B3:02:51:90:ED:CF:ED:B1:97:4A:60:6A:13:C6:E5:29:0F:CB:2A:E6:3E:DA:B5
657
Amazon API Gateway Developer Guide
Client certificates
658
Amazon API Gateway Developer Guide
Client certificates
SHA256:
EB:F3:C0:2A:87:89:B1:FB:7D:51:19:95:D6:63:B7:29:06:D9:13:CE:0D:5E:10:56:8A:8A:77:E2:58:61:67:E7
Alias name: trustcoreca1
SHA1: 58:D1:DF:95:95:67:6B:63:C0:F0:5B:1C:17:4D:8B:84:0B:C8:78:BD
SHA256:
5A:88:5D:B1:9C:01:D9:12:C5:75:93:88:93:8C:AF:BB:DF:03:1A:B2:D4:8E:91:EE:15:58:9B:42:97:1D:03:9C
Alias name: trustcorrootcertca1
SHA1: FF:BD:CD:E7:82:C8:43:5E:3C:6F:26:86:5C:CA:A8:3A:45:5B:C3:0A
SHA256:
D4:0E:9C:86:CD:8F:E4:68:C1:77:69:59:F4:9E:A7:74:FA:54:86:84:B6:C4:06:F3:90:92:61:F4:DC:E2:57:5C
Alias name: trustcorrootcertca2
SHA1: B8:BE:6D:CB:56:F1:55:B9:63:D4:12:CA:4E:06:34:C7:94:B2:1C:C0
SHA256:
07:53:E9:40:37:8C:1B:D5:E3:83:6E:39:5D:AE:A5:CB:83:9E:50:46:F1:BD:0E:AE:19:51:CF:10:FE:C7:C9:65
Alias name: trustisfpsrootca
SHA1: 3B:C0:38:0B:33:C3:F6:A6:0C:86:15:22:93:D9:DF:F5:4B:81:C0:04
SHA256:
C1:B4:82:99:AB:A5:20:8F:E9:63:0A:CE:55:CA:68:A0:3E:DA:5A:51:9C:88:02:A0:D3:A6:73:BE:8F:8E:55:7D
Alias name: ttelesecglobalrootclass2
SHA1: 59:0D:2D:7D:88:4F:40:2E:61:7E:A5:62:32:17:65:CF:17:D8:94:E9
SHA256:
91:E2:F5:78:8D:58:10:EB:A7:BA:58:73:7D:E1:54:8A:8E:CA:CD:01:45:98:BC:0B:14:3E:04:1B:17:05:25:52
Alias name: ttelesecglobalrootclass2ca
SHA1: 59:0D:2D:7D:88:4F:40:2E:61:7E:A5:62:32:17:65:CF:17:D8:94:E9
SHA256:
91:E2:F5:78:8D:58:10:EB:A7:BA:58:73:7D:E1:54:8A:8E:CA:CD:01:45:98:BC:0B:14:3E:04:1B:17:05:25:52
Alias name: ttelesecglobalrootclass3
SHA1: 55:A6:72:3E:CB:F2:EC:CD:C3:23:74:70:19:9D:2A:BE:11:E3:81:D1
SHA256:
FD:73:DA:D3:1C:64:4F:F1:B4:3B:EF:0C:CD:DA:96:71:0B:9C:D9:87:5E:CA:7E:31:70:7A:F3:E9:6D:52:2B:BD
Alias name: ttelesecglobalrootclass3ca
SHA1: 55:A6:72:3E:CB:F2:EC:CD:C3:23:74:70:19:9D:2A:BE:11:E3:81:D1
SHA256:
FD:73:DA:D3:1C:64:4F:F1:B4:3B:EF:0C:CD:DA:96:71:0B:9C:D9:87:5E:CA:7E:31:70:7A:F3:E9:6D:52:2B:BD
Alias name: tubitakkamusmsslkoksertifikasisurum1
SHA1: 31:43:64:9B:EC:CE:27:EC:ED:3A:3F:0B:8F:0D:E4:E8:91:DD:EE:CA
SHA256:
46:ED:C3:68:90:46:D5:3A:45:3F:B3:10:4A:B8:0D:CA:EC:65:8B:26:60:EA:16:29:DD:7E:86:79:90:64:87:16
Alias name: twcaglobalrootca
SHA1: 9C:BB:48:53:F6:A4:F6:D3:52:A4:E8:32:52:55:60:13:F5:AD:AF:65
SHA256:
59:76:90:07:F7:68:5D:0F:CD:50:87:2F:9F:95:D5:75:5A:5B:2B:45:7D:81:F3:69:2B:61:0A:98:67:2F:0E:1B
Alias name: twcarootcertificationauthority
SHA1: CF:9E:87:6D:D3:EB:FC:42:26:97:A3:B5:A3:7A:A0:76:A9:06:23:48
SHA256:
BF:D8:8F:E1:10:1C:41:AE:3E:80:1B:F8:BE:56:35:0E:E9:BA:D1:A6:B9:BD:51:5E:DC:5C:6D:5B:87:11:AC:44
Alias name: ucaextendedvalidationroot
SHA1: A3:A1:B0:6F:24:61:23:4A:E3:36:A5:C2:37:FC:A6:FF:DD:F0:D7:3A
SHA256:
D4:3A:F9:B3:54:73:75:5C:96:84:FC:06:D7:D8:CB:70:EE:5C:28:E7:73:FB:29:4E:B4:1E:E7:17:22:92:4D:24
Alias name: ucaglobalg2root
SHA1: 28:F9:78:16:19:7A:FF:18:25:18:AA:44:FE:C1:A0:CE:5C:B6:4C:8A
SHA256:
9B:EA:11:C9:76:FE:01:47:64:C1:BE:56:A6:F9:14:B5:A5:60:31:7A:BD:99:88:39:33:82:E5:16:1A:A0:49:3C
Alias name: usertrustecc
SHA1: D1:CB:CA:5D:B2:D5:2A:7F:69:3B:67:4D:E5:F0:5A:1D:0C:95:7D:F0
SHA256:
4F:F4:60:D5:4B:9C:86:DA:BF:BC:FC:57:12:E0:40:0D:2B:ED:3F:BC:4D:4F:BD:AA:86:E0:6A:DC:D2:A9:AD:7A
Alias name: usertrustecccertificationauthority
SHA1: D1:CB:CA:5D:B2:D5:2A:7F:69:3B:67:4D:E5:F0:5A:1D:0C:95:7D:F0
SHA256:
4F:F4:60:D5:4B:9C:86:DA:BF:BC:FC:57:12:E0:40:0D:2B:ED:3F:BC:4D:4F:BD:AA:86:E0:6A:DC:D2:A9:AD:7A
Alias name: usertrustrsa
SHA1: 2B:8F:1B:57:33:0D:BB:A2:D0:7A:6C:51:F7:0E:E9:0D:DA:B9:AD:8E
SHA256:
E7:93:C9:B0:2F:D8:AA:13:E2:1C:31:22:8A:CC:B0:81:19:64:3B:74:9C:89:89:64:B1:74:6D:46:C3:D4:CB:D2
659
Amazon API Gateway Developer Guide
Client certificates
660
Amazon API Gateway Developer Guide
Client certificates
SHA256:
EB:04:CF:5E:B1:F3:9A:FA:76:2F:2B:B1:20:F2:96:CB:A5:20:C1:B9:7D:B1:58:95:65:B8:1C:B9:A1:7B:72:44
Alias name: verisignc3g4.pem
SHA1: 22:D5:D8:DF:8F:02:31:D1:8D:F7:9D:B7:CF:8A:2D:64:C9:3F:6C:3A
SHA256:
69:DD:D7:EA:90:BB:57:C9:3E:13:5D:C8:5E:A6:FC:D5:48:0B:60:32:39:BD:C4:54:FC:75:8B:2A:26:CF:7F:79
Alias name: verisignc3g5.pem
SHA1: 4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5
SHA256:
9A:CF:AB:7E:43:C8:D8:80:D0:6B:26:2A:94:DE:EE:E4:B4:65:99:89:C3:D0:CA:F1:9B:AF:64:05:E4:1A:B7:DF
Alias name: verisignc4g2.pem
SHA1: 0B:77:BE:BB:CB:7A:A2:47:05:DE:CC:0F:BD:6A:02:FC:7A:BD:9B:52
SHA256:
44:64:0A:0A:0E:4D:00:0F:BD:57:4D:2B:8A:07:BD:B4:D1:DF:ED:3B:45:BA:AB:A7:6F:78:57:78:C7:01:19:61
Alias name: verisignc4g3.pem
SHA1: C8:EC:8C:87:92:69:CB:4B:AB:39:E9:8D:7E:57:67:F3:14:95:73:9D
SHA256:
E3:89:36:0D:0F:DB:AE:B3:D2:50:58:4B:47:30:31:4E:22:2F:39:C1:56:A0:20:14:4E:8D:96:05:61:79:15:06
Alias name: verisignclass1ca
SHA1: CE:6A:64:A3:09:E4:2F:BB:D9:85:1C:45:3E:64:09:EA:E8:7D:60:F1
SHA256:
51:84:7C:8C:BD:2E:9A:72:C9:1E:29:2D:2A:E2:47:D7:DE:1E:3F:D2:70:54:7A:20:EF:7D:61:0F:38:B8:84:2C
Alias name: verisignclass1g2ca
SHA1: 27:3E:E1:24:57:FD:C4:F9:0C:55:E8:2B:56:16:7F:62:F5:32:E5:47
SHA256:
34:1D:E9:8B:13:92:AB:F7:F4:AB:90:A9:60:CF:25:D4:BD:6E:C6:5B:9A:51:CE:6E:D0:67:D0:0E:C7:CE:9B:7F
Alias name: verisignclass1g3ca
SHA1: 20:42:85:DC:F7:EB:76:41:95:57:8E:13:6B:D4:B7:D1:E9:8E:46:A5
SHA256:
CB:B5:AF:18:5E:94:2A:24:02:F9:EA:CB:C0:ED:5B:B8:76:EE:A3:C1:22:36:23:D0:04:47:E4:F3:BA:55:4B:65
Alias name: verisignclass2g2ca
SHA1: B3:EA:C4:47:76:C9:C8:1C:EA:F2:9D:95:B6:CC:A0:08:1B:67:EC:9D
SHA256:
3A:43:E2:20:FE:7F:3E:A9:65:3D:1E:21:74:2E:AC:2B:75:C2:0F:D8:98:03:05:BC:50:2C:AF:8C:2D:9B:41:A1
Alias name: verisignclass2g3ca
SHA1: 61:EF:43:D7:7F:CA:D4:61:51:BC:98:E0:C3:59:12:AF:9F:EB:63:11
SHA256:
92:A9:D9:83:3F:E1:94:4D:B3:66:E8:BF:AE:7A:95:B6:48:0C:2D:6C:6C:2A:1B:E6:5D:42:36:B6:08:FC:A1:BB
Alias name: verisignclass3ca
SHA1: A1:DB:63:93:91:6F:17:E4:18:55:09:40:04:15:C7:02:40:B0:AE:6B
SHA256:
A4:B6:B3:99:6F:C2:F3:06:B3:FD:86:81:BD:63:41:3D:8C:50:09:CC:4F:A3:29:C2:CC:F0:E2:FA:1B:14:03:05
Alias name: verisignclass3g2ca
SHA1: 85:37:1C:A6:E5:50:14:3D:CE:28:03:47:1B:DE:3A:09:E8:F8:77:0F
SHA256:
83:CE:3C:12:29:68:8A:59:3D:48:5F:81:97:3C:0F:91:95:43:1E:DA:37:CC:5E:36:43:0E:79:C7:A8:88:63:8B
Alias name: verisignclass3g3ca
SHA1: 13:2D:0D:45:53:4B:69:97:CD:B2:D5:C3:39:E2:55:76:60:9B:5C:C6
SHA256:
EB:04:CF:5E:B1:F3:9A:FA:76:2F:2B:B1:20:F2:96:CB:A5:20:C1:B9:7D:B1:58:95:65:B8:1C:B9:A1:7B:72:44
Alias name: verisignclass3g4ca
SHA1: 22:D5:D8:DF:8F:02:31:D1:8D:F7:9D:B7:CF:8A:2D:64:C9:3F:6C:3A
SHA256:
69:DD:D7:EA:90:BB:57:C9:3E:13:5D:C8:5E:A6:FC:D5:48:0B:60:32:39:BD:C4:54:FC:75:8B:2A:26:CF:7F:79
Alias name: verisignclass3g5ca
SHA1: 4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5
SHA256:
9A:CF:AB:7E:43:C8:D8:80:D0:6B:26:2A:94:DE:EE:E4:B4:65:99:89:C3:D0:CA:F1:9B:AF:64:05:E4:1A:B7:DF
Alias name: verisignclass3publicprimarycertificationauthorityg4
SHA1: 22:D5:D8:DF:8F:02:31:D1:8D:F7:9D:B7:CF:8A:2D:64:C9:3F:6C:3A
SHA256:
69:DD:D7:EA:90:BB:57:C9:3E:13:5D:C8:5E:A6:FC:D5:48:0B:60:32:39:BD:C4:54:FC:75:8B:2A:26:CF:7F:79
Alias name: verisignclass3publicprimarycertificationauthorityg5
SHA1: 4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5
SHA256:
9A:CF:AB:7E:43:C8:D8:80:D0:6B:26:2A:94:DE:EE:E4:B4:65:99:89:C3:D0:CA:F1:9B:AF:64:05:E4:1A:B7:DF
661
Amazon API Gateway Developer Guide
AWS WAF
You can use AWS WAF to protect your API Gateway API from common web exploits, such as SQL injection
and cross-site scripting (XSS) attacks. These could affect API availability and performance, compromise
security, or consume excessive resources. For example, you can create rules to allow or block requests
from specified IP address ranges, requests from CIDR blocks, requests that originate from a specific
country or region, requests that contain malicious SQL code, or requests that contain malicious script.
You can also create rules that match a specified string or a regular expression pattern in HTTP headers,
method, query string, URI, and the request body (limited to the first 8 KB). Additionally, you can create
rules to block attacks from specific user agents, bad bots, and content scrapers. For example, you can use
rate-based rules to specify the number of web requests that are allowed by each client IP in a trailing,
continuously updated, 5-minute period.
Important
AWS WAF is your first line of defense against web exploits. When AWS WAF is enabled on
an API, AWS WAF rules are evaluated before other access control features, such as resource
policies (p. 274), IAM policies (p. 290), Lambda authorizers (p. 299), and Amazon Cognito
authorizers (p. 315). For example, if AWS WAF blocks access from a CIDR block that a resource
policy allows, AWS WAF takes precedence and the resource policy isn't evaluated.
To enable AWS WAF for your API, you need to do the following:
1. Use the AWS WAF console, AWS SDK, or CLI to create a Regional web ACL that contains the desired
combination of AWS WAF managed rules and your own custom rules. For more information, see
Getting Started with AWS WAF and Creating and Configuring a Web Access Control List (Web ACL).
Important
API Gateway requires a Regional web ACL.
2. Associate the AWS WAF Regional web ACL with an API stage. You can do this by using the AWS WAF
console, AWS SDK, or CLI or by using the API Gateway console, AWS SDK, or CLI.
662
Amazon API Gateway Developer Guide
Throttling
• In the AWS WAF web ACL dropdown list, choose the Regional web ACL that you want to
associate with this stage.
Note
If the web ACL you need doesn't exist yet, choose Create WebACL. Then choose Go to
AWS WAFto open the AWS WAF console in a new browser tab and create a Regional
web ACL. Then return to the API Gateway console to associate the web ACL with the
stage.
6. Choose Save Changes.
import boto3
waf = boto3.client('waf-regional')
waf.associate_web_acl(
WebACLId='aabc123a-fb4f-4fc6-becb-2b00831cadcf',
ResourceArn='arn:aws:apigateway:{region}::/restapis/4wk1k4onj3/stages/prod'
)
663
Amazon API Gateway Developer Guide
Throttling
API Gateway throttles requests to your API using the token bucket algorithm, where a token counts for
a request. Specifically, API Gateway examines the rate and a burst of request submissions against all
APIs in your account, per Region. In the token bucket algorithm, a burst can allow pre-defined overrun of
those limits, but other factors can also cause limits to be overrun in some cases.
When request submissions exceed the steady-state request rate and burst limits, API Gateway begins to
throttle requests. Clients may receive 429 Too Many Requests error responses at this point. Upon
catching such exceptions, the client can resubmit the failed requests in a way that is rate limiting.
As an API developer, you can set the target limits for individual API stages or methods to improve overall
performance across all APIs in your account. Alternatively, you can enable usage plans to set throttles on
client request submissions based on specified requests rates and quotas.
Topics
• How throttling limit settings are applied in API Gateway (p. 664)
• Account-level throttling per Region (p. 664)
• Configuring API-level and stage-level throttling targets in a usage plan (p. 665)
• Configuring method-level throttling targets in a usage plan (p. 665)
• AWS throttling limits are applied across all accounts and clients in a region. These limit settings exist to
prevent your API—and your account—from being overwhelmed by too many requests. These limits are
set by AWS and can't be changed by a customer.
• Per-account limits are applied to all APIs in an account in a specified Region. The account-level rate
limit can be increased upon request - higher limits are possible with APIs that have shorter timeouts
and smaller payloads. To request an increase of account-level throttling limits per Region, contact the
AWS Support Center. For more information, see Quotas and important notes (p. 813). Note that these
limits can't be higher than the AWS throttling limits.
• Per-API, per-stage throttling limits are applied at the API method level for a stage. You can configure
the same settings for all methods, or configure different throttle settings for each method. Note that
these limits can't be higher than the AWS throttling limits.
• Per-client throttling limits are applied to clients that use API keys associated with your usage plan as
client identifier. Note that these limits can't be higher than the per-account limits.
1. Per-client or per-method throttling limits (p. 665) that you set for an API stage in a usage
plan (p. 555)
2. Per-method throttling limits that you set for an API stage.
3. Account-level throttling per Region (p. 664)
4. AWS Regional throttling
664
Amazon API Gateway Developer Guide
Private APIs
AWS account, per Region. In API Gateway, the burst limit represents the target maximum number of
concurrent request submissions that API Gateway will fulfill before returning 429 Too Many Requests
error responses. For more information on throttling quotas, see Quotas and important notes (p. 813).
Using resource policies (p. 669), you can allow or deny access to your API from selected VPCs and VPC
endpoints, including across AWS accounts. Each endpoint can be used to access multiple private APIs.
You can also use AWS Direct Connect to establish a connection from an on-premises network to Amazon
VPC and access your private API over that connection.
Important
To restrict access to your private API to specific VPCs and VPC endpoints, you must add
aws:SourceVpc and aws:SourceVpce conditions to your API's resource policy. For example
policies, see the section called “Example: Allow private API traffic based on source VPC or VPC
endpoint” (p. 287).
In all cases, traffic to your private API uses secure connections and does not leave the Amazon network—
it is isolated from the public internet.
You can access (p. 478) your private APIs through interface VPC endpoints for API Gateway as shown
in the following diagram. If you have private DNS enabled, you can use private or public DNS names to
access your APIs. If you have private DNS disabled, you can only use public DNS names.
Note
API Gateway private APIs only support TLS 1.2. Earlier TLS versions are not supported.
665
Amazon API Gateway Developer Guide
Private APIs
At a high level, the steps for creating a private API are as follows:
1. First, create an interface VPC endpoint (p. 667) for the API Gateway component service for API
execution, known as execute-api, in your VPC.
2. Create and test your private API.
Note
The procedures below assume you already have a fully configured VPC. For more information,
and to get started with creating a VPC, see Getting Started With Amazon VPC in the Amazon
VPC User Guide.
666
Amazon API Gateway Developer Guide
Private APIs
• VPC endpoints for private APIs are subject to the same limitations as other interface VPC endpoints.
For more information, see Interface Endpoint Properties and Limitations in the Amazon VPC User
Guide.
• You can associate or disassociate a VPC endpoint to a REST API, which gives a Route 53 alias DNS
record and simplifies invoking your private API. For more information, see Associate or Disassociate a
VPC Endpoint with a Private REST API (p. 670).
Topics
• Create an interface VPC endpoint for API Gateway execute-api (p. 667)
• Create a private API using the API Gateway console (p. 668)
• Create a private API using the AWS CLI (p. 668)
• Create a private API using the AWS SDK for JavaScript (p. 669)
• Set up a resource policy for a private API (p. 669)
• Deploy a private API using the API Gateway console (p. 670)
• Associate or disassociate a VPC endpoint with a private REST API (p. 670)
After you've created your VPC endpoint, you can use it to access multiple private APIs.
1. Sign in to the AWS Management Console and open the Amazon VPC console at https://
console.aws.amazon.com/vpc/.
2. In the navigation pane, choose Endpoints, Create Endpoint.
3. For Service category, ensure that AWS services is selected.
4. For Service Name, choose the API Gateway service endpoint, including the AWS Region that you
want to connect to. This is in the form com.amazonaws.region.execute-api—for example,
com.amazonaws.us-east-1.execute-api.
• For VPC, choose the VPC that you want to create the endpoint in.
• For Subnets, choose the subnets (Availability Zones) in which to create the endpoint network
interfaces. To improve the availability of your API, choose multiple subnets.
Note
Not all Availability Zones may be supported for all AWS services.
• For Enable Private DNS Name, leave the check box selected. Private DNS is enabled by default.
When private DNS is enabled, you're able to access your API via private or public DNS. (This setting
doesn't affect who can access your API, only which DNS addresses they can use.) However, you
cannot access public APIs from a VPC by using an API Gateway VPC endpoint with private DNS
enabled. Note that these DNS settings don't affect the ability to call these public APIs from the
VPC if you're using an edge-optimized custom domain name to access the public API. Using an
edge-optimized custom domain name to access your public API (while using private DNS to access
667
Amazon API Gateway Developer Guide
Private APIs
your private API) is one way to access both public and private APIs from a VPC where the endpoint
has been created with private DNS enabled.
Note
Leaving private DNS enabled is the recommended choice. If you choose not to enable
private DNS, you're only able to access your API via public DNS.
To use the private DNS option, the enableDnsSupport and enableDnsHostnames attributes of
your VPC must be set to true. For more information, see DNS Support in Your VPC and Updating
DNS Support for Your VPC in the Amazon VPC User Guide.
• For Security group, select the security group to associate with the VPC endpoint network
interfaces.
The security group you choose must be set to allow TCP Port 443 inbound HTTPS traffic from
either an IP range in your VPC or another security group in your VPC.
6. Choose Create endpoint.
From here on, you can set up API methods and their associated integrations as described in steps 1-6 of
??? (p. 60).
Note
Until your API has a resource policy that grants access to your VPC or VPC endpoint (p. 667),
all API calls will fail. Before you test and deploy your API, you need to create a resource policy
and attach it to the API as described in ??? (p. 669).
{
"createdDate": "2017-10-13T18:41:39Z",
"description": "Simple private PetStore API",
"endpointConfiguration": {
"types": "PRIVATE"
},
668
Amazon API Gateway Developer Guide
Private APIs
"id": "0qzs2sy7bh",
"name": "Simple PetStore (AWS CLI, Private)"
}
From here on, you can follow the same instructions given in the section called “Set up an edge-optimized
API using AWS CLI commands” (p. 246) to set up methods and integrations for this API.
When you are ready to test your API, be sure to create a resource policy and attach it to the API as
described in ??? (p. 669).
apig.createRestApi({
name: "Simple PetStore (node.js SDK, private)",
endpointConfiguration: {
types: ['PRIVATE']
},
description: "Demo private API created using the AWS SDK for node.js",
version: "0.00.001"
}, function(err, data){
if (!err) {
console.log('Create API succeeded:\n', data);
restApiId = data.id;
} else {
console.log('Create API failed:\n', err);
}
});
{
"createdDate": "2017-10-13T18:41:39Z",
"description": "Demo private API created using the AWS SDK for node.js",
"endpointConfiguration": {
"types": "PRIVATE"
},
"id": "0qzs2sy7bh",
"name": "Simple PetStore (node.js SDK, private)"
}
After completing the preceding steps, you can follow the instructions in the section called “Set up an
edge-optimized API using the AWS SDK for Node.js” (p. 251) to set up methods and integrations for
this API.
When you are ready to test your API, be sure to create a resource policy and attach it to the API as
described in ??? (p. 669).
To do this, follow the instructions in the section called “Create and attach an API Gateway resource policy
to an API” (p. 288). In step 4, choose the Source VPC example. Replace {{vpceID}} (including the
curly braces) with your VPC endpoint ID, and then choose Save to save your resource policy.
669
Amazon API Gateway Developer Guide
Private APIs
You should also consider attaching an endpoint policy to the VPC endpoint to specify the access that's
being granted. For more information, see the section called “Use VPC endpoint policies for private
APIs” (p. 297).
1. In the left navigation pane, select the API and then choose Deploy API from the Actions drop-down
menu.
2. In the Deploy API dialog, choose a stage (or [New Stage] for the API's first deployment). Enter
a name (for example, "test", "prod", or "dev") in the Stage name input field. Optionally, provide a
description in Stage description and/or Deployment description. Then choose Deploy.
https://{rest-api-id}-{vpce-id}.execute-api.{region}.amazonaws.com/{stage}
Associating or disassociating a VPC endpoint with a private REST API requires you to update the API's
configuration. You can perform this change using the API Gateway console, the AWS CLI, or an AWS SDK
for API Gateway. The update operation may take few minutes to complete due to DNS propagation.
During this time, your API is available, but DNS propagation for the newly generated DNS URLs may
still be in progress. You may try creating a new deployment for your API (p. 490), if even after several
minutes your new URLs are not resolving in DNS.
Use the AWS CLI to associate VPC endpoint with a private REST API
To associate VPC endpoints at the time of API creation, use the following command:
{
"apiKeySource": "HEADER",
"endpointConfiguration": {
"types": [
"PRIVATE"
],
"vpcEndpointIds": [
"vpce-0212a4ababd5b8c3e",
"vpce-0393a628149c867ee"
]
670
Amazon API Gateway Developer Guide
Private APIs
},
"id": "u67n3ov968",
"createdDate": 1565718256,
"name": "Petstore"
}
To associate VPC endpoints to an already created private API, use the following CLI command:
{
"name": "Petstore",
"apiKeySource": "1565718256",
"tags": {},
"createdDate": 1565718256,
"endpointConfiguration": {
"vpcEndpointIds": [
"vpce-0212a4ababd5b8c3e",
"vpce-0393a628149c867ee",
"vpce-01d622316a7df47f9"
],
"types": [
"PRIVATE"
]
},
"id": "u67n3ov968"
}
Use the AWS CLI to disassociate VPC endpoint from a private REST API
To disassociate a VPC endpoint from a private API, use the following CLI command:
{
"name": "Petstore",
"apiKeySource": "1565718256",
"tags": {},
"createdDate": 1565718256,
"endpointConfiguration": {
"vpcEndpointIds": [
"vpce-0212a4ababd5b8c3e",
"vpce-01d622316a7df47f9"
],
"types": [
"PRIVATE"
671
Amazon API Gateway Developer Guide
Monitor
]
},
"id": "u67n3ov968"
}
Topics
• Monitoring REST API execution with Amazon CloudWatch metrics (p. 672)
• Setting up CloudWatch logging for a REST API in API Gateway (p. 678)
• Logging API calls to Kinesis Data Firehose (p. 681)
• Tracing user requests to REST APIs using X-Ray (p. 682)
The metrics reported by API Gateway provide information that you can analyze in different ways. The
following list shows some common uses for the metrics that are suggestions to get you started:
Topics
• Amazon API Gateway dimensions and metrics (p. 673)
• View CloudWatch metrics with the API dashboard in API Gateway (p. 675)
672
Amazon API Gateway Developer Guide
CloudWatch metrics
Metric Description
Unit: Count
Unit: Count
Unit: Count
673
Amazon API Gateway Developer Guide
CloudWatch metrics
Metric Description
The Sum statistic represents this metric, namely, the
total count of the cache misses in the given period.
The Average statistic represents the cache miss rate,
namely, the total count of the cache misses divided by
the total number of requests during the period. The
denominator corresponds to the Count metric (below).
Unit: Count
Unit: Count
Unit: Millisecond
Unit: Millisecond
Dimension Description
ApiName Filters API Gateway metrics for the REST API with the
specified API name.
ApiName, Method, Resource, Stage Filters API Gateway metrics for the API method with the
specified API name, stage, resource, and method.
API Gateway will not send these metrics unless you have
explicitly enabled detailed CloudWatch metrics. You
can do this in the console by selecting Enable Detailed
CloudWatch Metrics under a stage Logs/Tracing tab.
Alternatively, you can call the update-stage AWS CLI
command to update the metricsEnabled property to
true.
674
Amazon API Gateway Developer Guide
CloudWatch metrics
Dimension Description
ApiName, Stage Filters API Gateway metrics for the API stage resource
with the specified API name and stage.
Topics
• Prerequisites (p. 675)
• Examine API activities in the dashboard (p. 675)
Prerequisites
1. You must have an API created in API Gateway. Follow the instructions in Creating a REST API in
Amazon API Gateway (p. 242).
2. You must have the API deployed at least once. Follow the instructions in Deploying a REST API in
Amazon API Gateway (p. 490).
3. To get CloudWatch metrics for individual methods, you must have CloudWatch Logs enabled for
those methods in a given stage as described in Update stage settings (p. 494). Your account will be
charged for accessing method-level logs, but not for accessing API- or stage-level logs.
675
Amazon API Gateway Developer Guide
CloudWatch metrics
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. In the navigation pane, choose Metrics.
4. In the All metrics tab, choose API Gateway.
5. To view metrics by stage, choose the By Stage panel. And then select desired APIs and metric names.
6. To view metrics by specific API, choose the By Api Name panel. And then select desired APIs and
metric names.
2. To view a specific statistics (for example, Average) over a period of time of a 5 minutes intervals,
call the following command:
Important
CloudWatch lets you delete log groups or streams. Do not manually delete API Gateway API log
groups or streams; let API Gateway manage these resources. Manually deleting log groups or
streams may cause API requests and responses not to be logged. If that happens, you can delete
the entire log group for the API and redeploy the API. This is because API Gateway creates log
groups or log streams for an API stage at the time when it is deployed.
676
Amazon API Gateway Developer Guide
CloudWatch metrics
• Amazon CloudWatch Alarms – Watch a single metric over a time period that you specify, and perform
one or more actions based on the value of the metric relative to a given threshold over a number
of time periods. The action is a notification sent to an Amazon Simple Notification Service (Amazon
SNS) topic or Amazon EC2 Auto Scaling policy. CloudWatch alarms do not invoke actions simply
because they are in a particular state; the state must have changed and been maintained for a
specified number of periods. For more information, see Monitoring REST API execution with Amazon
CloudWatch metrics (p. 672).
• Amazon CloudWatch Logs – Monitor, store, and access your log files from AWS CloudTrail or other
sources. For more information, see Monitoring Log Files in the Amazon CloudWatch User Guide.
• Amazon CloudWatch Events – Match events and route them to one or more target functions or
streams to make changes, capture state information, and take corrective action. For more information,
see What is Amazon CloudWatch Events in the Amazon CloudWatch User Guide.
• AWS CloudTrail Log Monitoring – Share log files between accounts, monitor CloudTrail log files in real
time by sending them to CloudWatch Logs, write log processing applications in Java, and validate that
your log files have not changed after delivery by CloudTrail. For more information, see Working with
CloudTrail Log Files in the AWS CloudTrail User Guide.
• API Gateway dashboard shows the following statistics for a given API stage during a specified period of
time:
• API Calls
• Cache Hit, only when API caching is enabled.
• Cache Miss, only when API caching is enabled.
• Latency
• Integration Latency
• 4XX Error
• 5XX Error
• The CloudWatch home page shows:
• Current alarms and status
• Graphs of alarms and resources
• Service health status
state changes only. CloudWatch alarms do not invoke actions simply because they are in a particular
state; the state must have changed and been maintained for a specified number of periods.
The logged data includes errors or execution traces (such as request or response parameter values or
payloads), data used by Lambda authorizers (formerly known as custom authorizers), whether API keys
are required, whether usage plans are enabled, and so on.
When you deploy an API, API Gateway creates a log group and log streams under the log group. The log
group is named following the API-Gateway-Execution-Logs_{rest-api-id}/{stage_name}
format. Within each log group, the logs are further divided into log streams, which are ordered by Last
Event Time as logged data is reported.
In access logging, you, as an API developer, want to log who has accessed your API and how the caller
accessed the API. You can create your own log group or choose an existing log group that could be
managed by API Gateway. To specify the access details, you select $context (p. 410) variables
(expressed in a format of your choosing) and choose a log group as the destination. The access log
format must include at least $context.requestId. As a best practice, include $context.requestId
and $context.extendedRequestId in your log format. $context.requestId logs the value
in the x-amzn-RequestId header. Clients can override the value in the x-amzn-RequestId
header. API Gateway returns this request ID in the x-amzn-RequestId response header.
$context.extendedRequestId is a unique ID that API Gateway generates. API Gateway returns this
request ID in the x-amz-apigw-id response header. An API caller can't provide or override this request
ID. For more information, see the section called “$context Variables for data models, authorizers,
mapping templates, and CloudWatch access logging” (p. 410).
Note
Only $context variables are supported (not $input, and so on).
Choose a log format that is also adopted by your analytic backend, such as Common Log Format (CLF),
JSON, XML, or CSV. You can then feed the access logs to it directly to have your metrics computed and
rendered. To define the log format, set the log group ARN on the accessLogSettings/destinationArn
property on the stage. You can obtain a log group ARN in the CloudWatch console, provided that
the ARN column is selected for display. To define the access log format, set a chosen format on the
accessLogSetting/format property on the stage.
Examples of some commonly used access log formats are shown in the API Gateway console and are
listed as follows.
$context.identity.sourceIp $context.identity.caller \
$context.identity.user [$context.requestTime] \
"$context.httpMethod $context.resourcePath $context.protocol" \
$context.status $context.responseLength $context.requestId $context.extendedRequestId
678
Amazon API Gateway Developer Guide
CloudWatch logs
The continuation characters (\) are meant as a visual aid. The log format must be a single line. You can
add a newline character (\n) at the end of the log format to include a newline at the end of each log
entry.
• JSON:
{ "requestId":"$context.requestId", \
"extendedRequestId":"$context.extendedRequestId", \
"ip": "$context.identity.sourceIp", \
"caller":"$context.identity.caller", \
"user":"$context.identity.user", \
"requestTime":"$context.requestTime", \
"httpMethod":"$context.httpMethod", \
"resourcePath":"$context.resourcePath", \
"status":"$context.status", \
"protocol":"$context.protocol", \
"responseLength":"$context.responseLength" \
}
The continuation characters (\) are meant as a visual aid. The log format must be a single line. You can
add a newline character (\n) at the end of the log format to include a newline at the end of each log
entry.
• XML:
<request id="$context.requestId"> \
<extendedRequestId>$context.extendedRequestId</extendedRequestId>
<ip>$context.identity.sourceIp</ip> \
<caller>$context.identity.caller</caller> \
<user>$context.identity.user</user> \
<requestTime>$context.requestTime</requestTime> \
<httpMethod>$context.httpMethod</httpMethod> \
<resourcePath>$context.resourcePath</resourcePath> \
<status>$context.status</status> \
<protocol>$context.protocol</protocol> \
<responseLength>$context.responseLength</responseLength> \
</request>
The continuation characters (\) are meant as a visual aid. The log format must be a single line. You can
add a newline character (\n) at the end of the log format to include a newline at the end of each log
entry.
• CSV (comma-separated values):
$context.identity.sourceIp,$context.identity.caller,\
$context.identity.user,$context.requestTime,$context.httpMethod,\
$context.resourcePath,$context.protocol,$context.status,\
$context.responseLength,$context.requestId,$context.extendedRequestId
The continuation characters (\) are meant as a visual aid. The log format must be a single line. You can
add a newline character (\n) at the end of the log format to include a newline at the end of each log
entry.
679
Amazon API Gateway Developer Guide
CloudWatch logs
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
"logs:GetLogEvents",
"logs:FilterLogEvents"
],
"Resource": "*"
}
]
}
Note
API Gateway calls AWS Security Token Service in order to assume the IAM role, so make sure
that AWS STS is enabled for the Region. For more information, see Managing AWS STS in an
AWS Region.
To grant these permissions to your account, create an IAM role with apigateway.amazonaws.com
as its trusted entity, attach the preceding policy to the IAM role, and set the IAM role ARN on the
cloudWatchRoleArn property on your Account. You must set the cloudWatchRoleArn property separately
for each AWS Region in which you want to enable CloudWatch Logs.
If you receive an error when setting the IAM role ARN, check your AWS Security Token Service account
settings to make sure that AWS STS is enabled in the Region that you're using. For more information
about enabling AWS STS, see Managing AWS STS in an AWS Region in the IAM User Guide.
680
Amazon API Gateway Developer Guide
Kinesis Data Firehose
For more information about CloudWatch metrics, see the section called “CloudWatch
metrics” (p. 672).
7. To enable access logging:
Note
You can enable execution logging and access logging independent of each other.
API Gateway is now ready to log requests to your API. You don't need to redeploy the API when you
update the stage settings, logs, or stage variables.
For access logging, you can only enable CloudWatch or Kinesis Data Firehose—you can't enable both.
However, you can enable CloudWatch for execution logging and Kinesis Data Firehose for access logging.
Topics
• Kinesis Data Firehose log formats for API Gateway (p. 681)
• Permissions for Kinesis Data Firehose logging (p. 681)
• Set up Kinesis Data Firehose access logging by using the API Gateway console (p. 681)
681
Amazon API Gateway Developer Guide
X-Ray
API Gateway is now ready to log requests to your API to Kinesis Data Firehose. You don't need to
redeploy the API when you update the stage settings, logs, or stage variables.
Because X-Ray gives you an end-to-end view of an entire request, you can analyze latencies in your APIs
and their backend services. You can use an X-Ray service map to view the latency of an entire request
and that of the downstream services that are integrated with X-Ray. You can also configure sampling
rules to tell X-Ray which requests to record and at what sampling rates, according to criteria that you
specify.
If you call an API Gateway API from a service that's already being traced, API Gateway passes the trace
through, even if X-Ray tracing isn't enabled on the API.
You can enable X-Ray for an API stage by using the API Gateway console, or by using the API Gateway
API or CLI.
Topics
• Setting up AWS X-Ray with API Gateway REST APIs (p. 682)
• Using AWS X-Ray service maps and trace views with API Gateway (p. 685)
• Configuring AWS X-Ray sampling rules for API Gateway APIs (p. 688)
• Understanding AWS X-Ray traces for Amazon API Gateway APIs (p. 690)
Topics
682
Amazon API Gateway Developer Guide
X-Ray
• Passive: This is the default setting if you have not enabled X-Ray tracing on an API stage. This
approach means that the API Gateway API is only traced if X-Ray has been enabled on an upstream
service.
• Active: When an API Gateway API stage has this setting, API Gateway automatically samples API
invocation requests, based on the sampling algorithm specified by X-Ray.
When active tracing is enabled on a stage, API Gateway creates a service-linked role in your account,
if the role does not exist already. The role is named AWSServiceRoleForAPIGateway and will have
the APIGatewayServiceRolePolicy managed policy attached to it. For more information about
service-linked roles, see Using Service-Linked Roles.
Note
X-Ray applies a sampling algorithm to ensure that tracing is efficient, while still providing a
representative sample of the requests that your API receives. The default sampling algorithm
is 1 request per second, with 5 percent of requests sampled past that limit.
You can change the tracing mode for your API by using the API Gateway management console, the API
Gateway CLI, or an AWS SDK.
These steps assume that you have already deployed the API to a stage.
Once you've enabled X-Ray for your API stage, you can use the X-Ray management console to view the
traces and service maps.
683
Amazon API Gateway Developer Guide
X-Ray
{
"tracingEnabled": true,
"stageName": {stage-name},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": {deployment-id},
"lastUpdatedDate": 1533849811,
"createdDate": 1533849811,
"methodSettings": {}
}
To use the AWS CLI to disable active X-Ray tracing for an API stage when you create the stage, call the
create-stage command as in the following example:
{
"tracingEnabled": false,
"stageName": {stage-name},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": {deployment-id},
"lastUpdatedDate": 1533849811,
"createdDate": 1533849811,
"methodSettings": {}
}
To use the AWS CLI to enable active X-Ray tracing for an API that's already been deployed, call the
update-stage command as follows:
To use the AWS CLI to disable active X-Ray tracing for an API that's already been deployed, call the
update-stage command as in the following example:
684
Amazon API Gateway Developer Guide
X-Ray
{
"tracingEnabled": false,
"stageName": {stage-name},
"cacheClusterEnabled": false,
"cacheClusterStatus": "NOT_AVAILABLE",
"deploymentId": {deployment-id},
"lastUpdatedDate": 1533850033,
"createdDate": 1533849811,
"methodSettings": {}
}
Once you've enabled X-Ray for your API stage, use the X-Ray CLI to retrieve trace information. For more
information, see Using the AWS X-Ray API with the AWS CLI.
Using AWS X-Ray service maps and trace views with API
Gateway
In this section you can find detailed information on how to use AWS X-Ray service maps and trace views
with API Gateway.
For detailed information about service maps and trace views, and how to interpret them, see AWS X-Ray
Console.
Topics
• Example X-Ray service map (p. 685)
• Example X-Ray trace view (p. 688)
The following example shows a service map for the test stage of an API called xray. This API has a
Lambda integration with a Lambda authorizer function and a Lambda backend function. The nodes
represent the API Gateway service, the Lambda service, and the two Lambda functions.
For a detailed explanation of service map structure, see Viewing the Service Map.
685
Amazon API Gateway Developer Guide
X-Ray
From the service map, you can zoom in to see a trace view of your API stage. The trace will display in-
depth information regarding your API, represented as segments and subsegments. For example, the
trace for the service map shown above would include segments for the Lambda service and Lambda
function. For more information, see Lambda as an AWS X-Ray Trace.
If you choose a node or edge on an X-Ray service map, the X-Ray console shows a latency distribution
histogram. You can use a latency histogram to see how long it takes for a service to complete its
requests. Following is a histogram of the API Gateway stage named xray/test in the previous service
map. For a detailed explanation of latency distribution histograms, see Using Latency Histograms in the
AWS X-Ray Console.
686
Amazon API Gateway Developer Guide
X-Ray
687
Amazon API Gateway Developer Guide
X-Ray
Before you specify your X-Ray sampling rules, read the following topics in the X-Ray Developer Guide:
Topics
• X-Ray sampling rule option values for API Gateway APIs (p. 688)
• X-Ray sampling rule examples (p. 689)
688
Amazon API Gateway Developer Guide
X-Ray
• Rate (number between 0 and 100) — The percentage of matching requests to instrument, after the
reservoir is exhausted.
• Service name (string) — API stage name, in the form {api-name}/{stage-name}. For example, if
you were to deploy the PetStore (p. 46) sample API to a stage named test, the Service name value to
specify in your sampling rule would be pets/test.
• Service type (string) — For an API Gateway API, either AWS::ApiGateway::Stage or
AWS::ApiGateway::* can be specified.
• Host (string) — The hostname from the HTTP host header. Set this to * to match against all
hostnames. Or you can specify a full or partial hostname to match, for example, api.example.com or
*.example.com.
• Resource ARN (string) — The ARN of the API stage, for example, arn:aws:apigateway:region::/
restapis/api-id/stages/stage-name.
The stage name can be obtained from the console or the API Gateway CLI or API. For more information
about ARN formats, see the Amazon Web Services General Reference.
• HTTP method (string) — The method to be sampled, for example, GET.
• URL path (string) — This option is not supported for API Gateway.
• (optional) Attributes (key and value) — Headers from the original HTTP request, for example,
Connection, Content-Length, or Content-Type. Each attribute value can be up to 32 characters
long.
This rule samples all GET requests for the testxray API at the test stage.
This rule samples all requests for the testxray API at the prod stage.
689
Amazon API Gateway Developer Guide
X-Ray
Before you read this section, review the following topics in the X-Ray Developer Guide:
Topics
• Examples of trace objects for an API Gateway API (p. 690)
• Understanding the trace (p. 690)
Annotations
Annotations can appear in segments and subsegments. They are used as filtering expressions in sampling
rules to filter traces. For more information, see Configuring Sampling Rules in the AWS X-Ray Console.
Following is an example of an annotations object, in which an API stage is identified by the API ID and
the API stage name:
"annotations": {
"aws:api_id": "a1b2c3d4e5",
"aws:api_stage": "dev"
}
The aws object appears only in segments. Following is an example of an aws object that matches the
Default sampling rule. For an in-depth explanation of sampling rules, see Configuring Sampling Rules in
the AWS X-Ray Console.
"aws": {
"xray": {
"sampling_rule_name": "Default"
},
"api_gateway": {
"account_id": "123412341234",
"rest_api_id": "a1b2c3d4e5",
"stage": "dev",
"request_id": "a1b2c3d4-a1b2-a1b2-a1b2-a1b2c3d4e5f6"
}
}
690
Amazon API Gateway Developer Guide
X-Ray
"Document": {
"id": "a1b2c3d4a1b2c3d4",
"name": "testxray/dev",
"start_time": 1533928226.229,
"end_time": 1533928226.614,
"metadata": {
"default": {
"extended_request_id": "abcde12345abcde=",
"request_id": "a1b2c3d4-a1b2-a1b2-a1b2-a1b2c3d4e5f6"
}
},
"http": {
"request": {
"url": "https://example.com/dev?
username=demo&message=hellofromdemo/",
"method": "GET",
"client_ip": "192.0.2.0",
"x_forwarded_for": true
},
"response": {
"status": 200,
"content_length": 0
}
},
"aws": {
"xray": {
"sampling_rule_name": "Default"
},
"api_gateway": {
"account_id": "123412341234",
"rest_api_id": "a1b2c3d4e5",
"stage": "dev",
"request_id": "a1b2c3d4-a1b2-a1b2-a1b2-a1b2c3d4e5f6"
}
},
"annotations": {
"aws:api_id": "a1b2c3d4e5",
"aws:api_stage": "dev"
},
"trace_id": "1-a1b2c3d4-a1b2c3d4a1b2c3d4a1b2c3d4",
"origin": "AWS::ApiGateway::Stage",
"resource_arn": "arn:aws:apigateway:us-east-1::/restapis/a1b2c3d4e5/stages/
dev",
"subsegments": [
{
"id": "abcdefgh12345678",
"name": "Lambda",
"start_time": 1533928226.233,
"end_time": 1533928226.6130002,
"http": {
"request": {
"url": "https://example.com/2015-03-31/functions/
arn:aws:lambda:us-east-1:123412341234:function:xray123/invocations",
"method": "GET"
},
"response": {
"status": 200,
"content_length": 62
}
},
"aws": {
"function_name": "xray123",
"region": "us-east-1",
"operation": "Invoke",
"resource_names": [
"xray123"
691
Amazon API Gateway Developer Guide
X-Ray
]
},
"namespace": "aws"
}
]
},
"Id": "a1b2c3d4a1b2c3d4"
}
692
Amazon API Gateway Developer Guide
About WebSocket APIs
API Gateway WebSocket APIs are bidirectional. A client can send messages to a service, and services
can independently send messages to clients. This bidirectional behavior enables richer client/service
interactions because services can push data to clients without requiring clients to make an explicit
request. WebSocket APIs are often used in real-time applications such as chat applications, collaboration
platforms, multiplayer games, and financial trading platforms.
In this section, you can learn how to develop, publish, protect, and monitor your WebSocket APIs using
API Gateway.
Topics
• About WebSocket APIs in API Gateway (p. 693)
• Developing a WebSocket API in API Gateway (p. 702)
• Publishing WebSocket APIs for customers to invoke (p. 726)
• Protecting your WebSocket API (p. 733)
• Monitoring WebSocket APIs (p. 733)
Unlike a REST API, which receives and responds to requests, a WebSocket API supports two-way
communication between client apps and your backend. The backend can send callback messages to
connected clients.
In your WebSocket API, incoming JSON messages are directed to backend integrations based on routes
that you configure. (Non-JSON messages are directed to a $default route that you configure.)
A route includes a route key, which is the value that is expected once a route selection expression is
evaluated. The routeSelectionExpression is an attribute defined at the API level. It specifies a
JSON property that is expected to be present in the message payload. For more information about route
selection expressions, see the section called “” (p. 704).
For example, if your JSON messages contain an action property, and you want to perform different
actions based on this property, your route selection expression might be ${request.body.action}.
Your routing table would specify which action to perform by matching the value of the action property
against the custom route key values that you have defined in the table.
There are three predefined routes that can be used: $connect, $disconnect, and $default. In
addition, you can create custom routes.
• API Gateway calls the $connect route when a persistent connection between the client and a
WebSocket API is being initiated.
• API Gateway calls the $disconnect route when the client or the server disconnects from the API.
• API Gateway calls a custom route after the route selection expression is evaluated against the message
if a matching route is found; the match determines which integration is invoked.
693
Amazon API Gateway Developer Guide
Managing connected users and client apps
• API Gateway calls the $default route if the route selection expression cannot be evaluated against
the message or if no matching route is found.
For more information about the $connect and $disconnect routes, see the section called “Managing
connected users and client apps” (p. 694).
For more information about the $default route and custom routes, see the section called “Invoking
your backend integration” (p. 695).
Backend services can send data to connected client apps. For more information, see the section called
“Sending data from backend services to connected clients” (p. 697).
Because the WebSocket connection is a stateful connection, you can configure authorization on the
$connect route only. AuthN/AuthZ will be performed only at connection time.
Until execution of the integration associated with the $connect route is completed, the upgrade request
is pending and the actual connection will not be established. If the $connect request fails (e.g., due to
AuthN/AuthZ failure or an integration failure), the connection will not be made.
Note
If authorization fails on $connect, the connection will not be established, and the client will
receive a 401 or 403 response.
Setting up an integration for $connect is optional. You should consider setting up a $connect
integration if:
• You want to enable clients to specify subprotocols by using the Sec-WebSocket-Protocol field. For
example code, see Setting up a $connect route that requires a WebSocket subprotocol (p. 707).
• You want to be notified when clients connect and disconnect.
• You want to throttle connections or control who connects.
• You want your backend to send messages back to clients using a callback URL.
• You want to store each connection ID and other information into a database (for example, Amazon
DynamoDB).
The connection can be closed by the server or by the client. As the connection is already closed when it is
executed, $disconnect is a best-effort event. API Gateway will try its best to deliver the $disconnect
event to your integration, but it cannot guarantee delivery.
694
Amazon API Gateway Developer Guide
Invoking your backend integration
The backend can initiate disconnection by using the @connections API. For more information, see the
section called “Use @connections commands in your backend service” (p. 725).
Messages can be JSON or non-JSON. However, only JSON messages can be routed to specific
integrations based on message content. Non-JSON messages are passed through to the backend by the
$default route.
Note
API Gateway supports message payloads up to 128 KB with a maximum frame size of 32 KB. If a
message exceeds 32 KB, you must split it into multiple frames, each 32 KB or smaller. If a larger
message (or frame) is received, the connection is closed with code 1009.
Currently binary payloads are not supported. If a binary frame is received, the connection is
closed with code 1003. However, it is possible to convert binary payloads to text. See the section
called “Binary media types” (p. 724).
With WebSocket APIs in API Gateway, JSON messages can be routed to execute a specific backend
service based on message content. When a client sends a message over its WebSocket connection,
this results in a route request to the WebSocket API. The request will be matched to the route with the
corresponding route key in API Gateway. You can set up a route request for a WebSocket API in the API
Gateway console, by using the AWS CLI, or by using an AWS SDK.
Note
In the AWS CLI and AWS SDKs, you can create routes before or after you create integrations.
Currently the console does not support reuse of integrations, so you must create the route first
and then create the integration for that route.
You can configure API Gateway to perform validation on a route request before proceeding with the
integration request. If the validation fails, API Gateway fails the request without calling your backend,
sends a "Bad request body" gateway response similar to the following to the client, and publishes
the validation results in CloudWatch Logs:
This reduces unnecessary calls to your backend and lets you focus on the other requirements of your API.
You can also define a route response for your API's routes to enable two-way communication. A
route response describes what data will be sent to your client upon completion of a particular route's
integration. It is not necessary to define a response for a route if, for example, you want a client to send
messages to your backend without receiving a response (one-way communication). However, if you don't
695
Amazon API Gateway Developer Guide
Invoking your backend integration
provide a route response, API Gateway won't send any information about the result of your integration
to your clients.
• You can use it together with defined route keys, to specify a "fallback" route (for example, a generic
mock integration that returns a particular error message) for incoming messages that don't match any
of the defined route keys.
• You can use it without any defined route keys, to specify a proxy model that delegates routing to a
backend component.
• You can use it to specify a route for non-JSON payloads.
Custom routes
If you want to invoke a specific integration based on message content, you can do so by creating a
custom route.
A custom route uses a route key and integration that you specify. When an incoming message contains
a JSON property, and that property evaluates to a value that matches the route key value, API Gateway
invokes the integration. (For more information, see the section called “About WebSocket APIs” (p. 693).)
For example, suppose you wanted to create a chat room application. You might start by creating a
WebSocket API whose route selection expression is $request.body.action. You could then define
two routes: joinroom and sendmessage. A client app might invoke the joinroom route by sending a
message such as the following:
{"action":"joinroom","roomname":"developers"}
And it might invoke the sendmessage route by sending a message such as the following:
{"action":"sendmessage","message":"Hello everyone"}
For more information about setting up integrations, see the section called “Integrations” (p. 712).
• Currently, in the API Gateway console you must create a route first and then create an integration as
that route's target. However, in the API and CLI, you can create routes and integrations independently,
in any order.
696
Amazon API Gateway Developer Guide
Sending data from backend services to connected clients
• You can use a single integration for multiple routes. For example, if you have a set of actions that
closely relate to each other, you may want all of those routes to go to a single Lambda function.
Rather than defining the details of the integration multiple times, you can specify it once and assign it
to each of the related routes.
Note
Currently the console does not support reuse of integrations, so you must create the route
first and then create the integration for that route.
In the AWS CLI and AWS SDKs, you can reuse an integration by setting the route's target to a
value of "integrations/{integration-id}", where {integration-id}" is the unique
ID of the integration to be associated with the route.
• API Gateway provides multiple selection expressions (p. 697) you can use in your routes and
integrations. You don't need to rely on the content type to select an input template or output
mapping. As with route selection expressions, you can define a selection expression to be evaluated
by API Gateway to choose the right item. All of them will fall back to the $default template if a
matching template is not found.
• In integration requests, the template selection expression supports
$request.body.<json_path_expression> and static values.
• In integration responses, the template selection expression supports
$request.body.<json_path_expression>, $integration.response.statuscode, and
$integration.response.header.<headerName>.
In the HTTP protocol, in which requests and responses are sent synchronously; communication is
essentially one-way. In the WebSocket protocol, communication is two-way. Responses are asynchronous
and are not necessarily received by the client in the same order as the client's messages were sent. In
addition, the backend can send messages to the client.
Note
For a route that is configured to use AWS_PROXY or LAMBDA_PROXY integration, communication
is one-way, and API Gateway will not pass the backend response through to the route response
automatically. For example, in the case of LAMBDA_PROXY integration, the body that the
Lambda function returns will not be returned to the client. If you want the client to receive
integration responses, you must define a route response to make two-way communication
possible.
• An integration can send a response, which is returned to the client by a route response that you have
defined.
• You can use the @connections API to send a POST request. For more information, see the section
called “Use @connections commands in your backend service” (p. 725).
697
Amazon API Gateway Developer Guide
WebSocket selection expressions
API Gateway uses selection expressions as a way to evaluate request and response context and produce
a key. The key is then used to select from a set of possible values, typically provided by you, the API
developer. The exact set of supported variables will vary depending on the particular expression. Each
expression is discussed in more detail below.
For all of the expressions, the language follows the same set of rules:
Evaluation of the route response selection expression produces a route response key. Eventually, this key
will be used to choose from one of the RouteResponses associated with the API. However, currently
only the $default key is supported.
Api.RouteSelectionExpression
Route.RouteKey $defaultRoute
is WebSocket
supported messages
as a based
catch- on the
context
698
Amazon API Gateway Developer Guide
WebSocket selection expressions
$default
is
supported
as a
catch-
all.
${request.body.jsonPath}
and
static
values
are
supported.
$default
is
supported
as a
catch-
all.
699
Amazon API Gateway Developer Guide
WebSocket selection expressions
Integration.IntegrationResponseSelectionExpression
IntegrationResponse.IntegrationResponseKey Optional. Manipulate
May be the
provided response
for non- from
proxy the
integration.
backend.
Acts Choose
as a the
pattern action
match to occur
for error based
messages on the
(from dynamic
Lambda) response
or of the
status backend
codes (e.g.,
(from handling
HTTP certain
integrations).
errors
distinctly).
$default
is
required
for non-
proxy
integrations
to act
as the
catch-
all for
successful
responses.
700
Amazon API Gateway Developer Guide
WebSocket selection expressions
${request.body.js
${integration.res
${integration.res
${integration.res
and
static
values
are
supported.
$default
is
supported
as a
catch-
all.
701
Amazon API Gateway Developer Guide
Develop
Route.RouteResponseSelectionExpression
RouteResponse.RouteResponseKey Should
be
provided
to
initiate
two-
way
communication
for a
WebSocket
route.
Currently,
this
value is
restricted
to
$default
only.
As you're developing your API Gateway API, you decide on a number of characteristics of your API. These
characteristics depend on the use case of your API. For example, you might want to only allow certain
clients to call your API, or you might want it to be available to everyone. You might want an API call to
execute a Lambda function, make a database query, or call an application.
Topics
• Create a WebSocket API in API Gateway (p. 702)
• Working with routes for WebSocket APIs (p. 703)
• Controlling and managing access to a WebSocket API in API Gateway (p. 708)
• Setting up WebSocket API integrations (p. 712)
• Request validation (p. 716)
• Setting up data transformations for WebSocket APIs (p. 716)
• Working with binary media types for WebSocket APIs (p. 724)
• Invoking a WebSocket API (p. 724)
702
Amazon API Gateway Developer Guide
Routes
Note
WebSocket APIs only support TLS 1.2. Earlier TLS versions are not supported.
Example output:
{
"ApiKeySelectionExpression": "$request.header.x-api-key",
"Name": "myWebSocketApi3",
"CreatedDate": "2018-11-15T06:23:51Z",
"ProtocolType": "WEBSOCKET",
"RouteSelectionExpression": "'$request.body.action'",
"ApiId": "aabbccddee"
}
For more information about route selection expressions, see the section called “” (p. 704).
5. If desired, enter a Description for your API.
6. Choose Create API.
A route includes a route key, which is the value that is expected once a route selection expression is
evaluated. The routeSelectionExpression is an attribute defined at the API level. It specifies a
JSON property that is expected to be present in the message payload. For more information about route
selection expressions, see the section called “” (p. 704).
For example, if your JSON messages contain an action property and you want to perform different
actions based on this property, your route selection expression might be ${request.body.action}.
703
Amazon API Gateway Developer Guide
Routes
Your routing table would specify which action to perform by matching the value of the action property
against the custom route key values that you have defined in the table.
There are three predefined routes that can be used: $connect, $disconnect, and $default. In
addition, you can create custom routes.
• API Gateway calls the $connect route when a persistent connection between the client and a
WebSocket API is being initiated.
• API Gateway calls the $disconnect route when the client or the server disconnects from the API.
• API Gateway calls a custom route after the route selection expression is evaluated against the message
if a matching route is found; the match determines which integration is invoked.
• API Gateway calls the $default route if the route selection expression cannot be evaluated against
the message or if no matching route is found.
For example, suppose you are sending the following JSON message:
{
"service" : "chat",
"action" : "join",
"data" : {
"room" : "room1234"
}
}
You might want to select your API's behavior based on the action property. In that case, you might
define the following route selection expression:
$request.body.action
In this example, request.body refers to your message's JSON payload, and .action is a JSONPath
expression. You can use any JSON path expression after request.body, but keep in mind that the result
will be stringified. For example, if your JSONPath expression returns an array of two elements, that
will be presented as the string "[item1, item2]". For this reason, it's a good practice to have your
expression evaluate to a value and not an array or an object.
You can simply use a static value, or you can use multiple variables. The following table shows examples
and their evaluated results against the preceding payload.
$request.body.action
join An
unwrapped
variable
${request.body.action}
join A
wrapped
variable
704
Amazon API Gateway Developer Guide
Routes
${request.body.service}/
chat/join Multiple
${request.body.action} variables
with
static
values
${request.body.action}-
join- If the
${request.body.invalidPath} JSONPath
is not
found,
the
variable
is
resolved
as "".
The evaluated result is used to find a route. If there is a route with a matching route key, the route
is selected to process the message. If no matching route is found, then API Gateway tries to find the
$default route if available. If the $default route is not defined, then API Gateway returns an error.
1. Sign in to the API Gateway console, choose the API, and choose Routes.
2. To create one of the predefined routes ($connect, $disconnect, and $default), choose its name.
3. If desired, you can create custom routes. To do so, enter the route key name in the New Route Key
text box and choose the checkmark icon.
Note
When you create a custom route, do not use the $ prefix in the route key name. This prefix
is reserved for predefined routes.
705
Amazon API Gateway Developer Guide
Routes
Example output:
{
"ApiKeyRequired": false,
"AuthorizationType": "NONE",
"RouteKey": "$default",
"RouteId": "1122334"
}
When you set up the $connect route for your API, the following optional settings are available
to enable authorization for your API. For more information, see the section called “The $connect
route” (p. 694).
• Authorization: If no authorization is needed, you can specify NONE. Otherwise, you can specify:
• AWS_IAM to use standard AWS IAM policies to control access to your API.
• CUSTOM to implement authorization for an API by specifying a Lambda authorizer function that
you have previously created. The authorizer can reside in your own AWS account or a different
AWS account. For more information about Lambda authorizers, see Use API Gateway Lambda
authorizers (p. 299).
Note
In the API Gateway console, the CUSTOM setting is visible only after you have set up an
authorizer function as described in the section called “Configure a Lambda authorizer using
the console” (p. 306).
Important
The Authorization setting is applied to the entire API, not just the $connect route. The
$connect route protects the other routes, because it is called on every connection.
• API Key Required: You can optionally require an API key for an API's $connect route. You can use API
keys together with usage plans to control and track access to your APIs. For more information, see the
section called “Usage plans” (p. 549).
Set up the $connect route request using the API Gateway console
To set up the $connect route request for a WebSocket API using the API Gateway console:
1. Sign in to the API Gateway console, choose the API, and choose Routes.
2. Under Routes, choose $connect.
3. Choose Route Request in the route overview pane.
4. Under Access Settings, configure the route settings as follows:
a. To edit the Authorization setting, choose the pencil icon. Choose the desired setting from the
dropdown menu and choose the checkmark icon to save the new setting.
b. To edit the API Key Required setting, choose the pencil icon. Choose true or false from the
dropdown menu and choose the checkmark icon to save the new setting.
706
Amazon API Gateway Developer Guide
Routes
You can configure route responses and response selection expressions by using the API Gateway console
or the AWS CLI or an AWS SDK. For more information about route responses, see the section called
“Invoking your backend integration” (p. 695).
For more information about route response selection expressions, see the section called “” (p. 698).
Topics
• Set up a route response using the API Gateway console (p. 707)
• Set up a route response using the AWS CLI (p. 707)
Example output:
{
"RouteResponseId": "abcdef",
"RouteResponseKey": "$default"
}
The following example Lambda function returns the Sec-WebSocket-Protocol header to clients. The
function establishes a connection to your API only if the client specifies the myprotocol subprotocol.
For an AWS CloudFormation template that creates this example API and Lambda proxy integration, see
ws-subprotocol.yaml.
707
Amazon API Gateway Developer Guide
Access control
if (headers['sec-websocket-protocol'] != undefined) {
const subprotocolHeader = headers['sec-websocket-protocol'];
const subprotocols = subprotocolHeader.split(',');
if (subprotocols.indexOf('myprotocol') >= 0) {
const response = {
statusCode: 200,
headers: {
"Sec-WebSocket-Protocol" : "myprotocol"
}
};
return response;
}
}
}
const response = {
statusCode: 400
};
return response;
};
function toLowerCaseProperties(obj) {
var wrapper = {};
for (var key in obj) {
wrapper[key.toLowerCase()] = obj[key];
}
return wrapper;
}
You can use wscat to test that your API allows connections only if a client requests a subprotocol
that your API supports. The following commands use the -s flag to specify subprotocols during the
connection.
The following command attempts a connection with an unsupported subprotocol. Because the client
specified the chat1 subprotocol, the Lambda integration returns a 400 error, and the connection is
unsuccessful.
The following command includes a supported subprotocol in the connection request. The Lambda
integration allows the connection.
To learn more about invoking WebSocket APIs, see Invoking a WebSocket API (p. 724).
708
Amazon API Gateway Developer Guide
Access control
You can use the following mechanisms for authentication and authorization:
• Standard AWS IAM roles and policies offer flexible and robust access controls. You can use IAM roles
and policies for controlling who can create and manage your APIs, as well as who can invoke them. For
more information, see Using IAM authorization (p. 709).
• IAM tags can be used together with IAM policies to control access. For more information, see Using
tags to control access to API Gateway resources (p. 808).
• Lambda authorizers are Lambda functions that control access to APIs. For more information, see
Creating a Lambda REQUEST authorizer function (p. 710).
Topics
• Using IAM authorization (p. 709)
• Creating a Lambda REQUEST authorizer function (p. 710)
arn:aws:execute-api:region:account-id:api-id/stage-name/route-key
• The @connections API uses the same ARN format as REST APIs:
arn:aws:execute-api:region:account-id:api-id/stage-name/POST/@connections
For example, you could set up the following policy to the client. This example allows everyone to send a
message (Invoke) for all routes except for a secret route in the prod stage and prevents everyone from
sending a message back to connected clients (ManageConnections) for all stages.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:account-id:api-id/prod/*"
]
},
{
"Effect": "Deny",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:account-id:api-id/prod/secret"
]
},
{
"Effect": "Deny",
709
Amazon API Gateway Developer Guide
Access control
"Action": [
"execute-api:ManageConnections"
],
"Resource": [
"arn:aws:execute-api:us-east-1:account-id:api-id/*"
]
}
]
}
• You cannot use path variables (event.pathParameters), because the path is fixed.
• event.methodArn is different from its REST API equivalent, because it has no HTTP method. In the
case of $connect, methodArn ends with "$connect":
arn:aws:execute-api:region:account-id:api-id/stage-name/$connect
• The context variables in event.requestContext are different from those for REST APIs.
The following example Lambda authorizer function is a WebSocket version of the Lambda authorizer
function for REST APIs in the section called “Create a Lambda authorizer function in the Lambda
console” (p. 301):
// Perform authorization to return the Allow policy for correct parameters and
// the 'Unauthorized' error, otherwise.
var authResponse = {};
var condition = {};
condition.IpAddress = {};
710
Amazon API Gateway Developer Guide
Access control
callback("Unauthorized");
}
}
To configure the preceding Lambda function as a REQUEST authorizer function for a WebSocket API,
follow the same procedure as for REST APIs (p. 306).
To configure the $connect route to use this Lambda authorizer in the console, select or create the
$connect route. Choose the route request and choose your authorizer in the Authorization dropdown
menu.
To test the authorizer, you need to create a new connection. Changing authorizer in $connect doesn't
affect the already connected client. When you connect to your WebSocket API, you need to provide
values for any configured identity sources. For example, you can connect by sending a valid query string
and header using wscat as in the following example:
wscat -c 'wss://myapi.execute-api.us-east-1.amazonaws.com/beta?QueryString1=queryValue1' -H
HeaderAuth1:headerValue1
If you attempt to connect without a valid identity value, you'll receive a 401 response:
wscat -c wss://myapi.execute-api.us-east-1.amazonaws.com/beta
error: Unexpected server response: 401
711
Amazon API Gateway Developer Guide
Integrations
In this section, you can learn how to set up integration requests and integration responses for your
WebSocket API.
Topics
• Setting up a WebSocket API integration request in API Gateway (p. 712)
• Setting up a WebSocket API integration responses in API Gateway (p. 714)
Set up a WebSocket API integration request using the API Gateway console
To add an integration request to a route in a WebSocket API using the API Gateway console
1. Sign in to the API Gateway console, choose the API, and choose Routes.
2. Under Routes, choose the route.
3. In the Route Overview pane, choose Integration Request.
4. For Integration Type, choose one of the following:
• Choose Lambda Function only if your API will be integrated with an AWS Lambda function that
you have already created in this account or in another account.
To create a new Lambda function in AWS Lambda, to set a resource permission on the Lambda
function, or to perform any other Lambda service actions, choose AWS Service instead.
• Choose HTTP if your API will be integrated with an existing HTTP endpoint. For more information,
see Set up HTTP integrations in API Gateway (p. 349).
• Choose Mock if you want to generate API responses from API Gateway directly, without the
need for an integration backend. For more information, see Set up mock integrations in API
Gateway (p. 361).
• Choose AWS Service if your API will be integrated with an AWS service.
• Choose VPC Link if your API will use a VpcLink as a private integration endpoint. For more
information, see Set up API Gateway private integrations (p. 354).
5. If you chose Lambda Function, do the following:
a. 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, choose us-east-1. For a list of Region names and identifiers, see AWS
Lambda in the Amazon Web Services General Reference.
b. For Use Lambda Proxy integration, choose the check box if you intend to use Lambda proxy
integration (p. 332) or cross-account Lambda proxy integration (p. 36).
712
Amazon API Gateway Developer Guide
Integrations
c. For Lambda Function, specify the function in one of the following ways:
• If your Lambda function is in the same account, start typing the function name and then
choose the function from the dropdown list.
Note
The function name can optionally include its alias or version specification, as in
HelloWorld, HelloWorld:1, or HelloWorld:alpha.
• If the function is in a different account, enter the ARN for the function.
d. Choose Invoke with caller credentials if you want API Gateway to invoke your Lambda function
using credentials received in the incoming request.
e. For Execution role, enter the ARN of the Lambda invocation role that enables API Gateway to
invoke your Lambda functions.
f. To use the default timeout value of 29 seconds, leave Use Default Timeout check box selected.
To set a custom timeout, clear the check box, and enter a timeout value between 50 and 29000
milliseconds.
g. Choose Save.
6. If you chose HTTP, follow the instructions in step 4 of the section called “ Set up integration request
using the console” (p. 328).
7. If you chose Mock, proceed to the Request Templates step.
8. If you chose AWS Service, follow the instructions in step 6 of the section called “ Set up integration
request using the console” (p. 328).
9. If you chose VPC Link, do the following:
a. For Use Proxy integration, choose the check box if you want requests to be proxied to your
VPCLink's endpoint.
b. From the VPC Link dropdown list, choose [Use Stage Variables] and enter
${stageVariables.vpcLinkId} in the text box below the list.
We will define the vpcLinkId stage variable after deploying the API to a stage and set its value
to the ID of the VpcLink.
c. For HTTP method, choose the HTTP method type that most closely matches the method in the
HTTP backend.
d. For Endpoint URL, enter the URL of the HTTP backend you want this integration to use.
e. To use the default timeout value of 29 seconds, leave Use Default Timeout selection checked.
To set a custom timeout, uncheck the box, and enter a timeout value between 50 and 29000
milliseconds.
10. Under Request Templates, do the following:
• For Template Selection Expression, choose the pencil icon and replace the word template
with a template selection expression. This is an expression that API Gateway looks for in the
message payload. If it is found, it is evaluated, and the result is a template key value that is used
to select the data mapping template to be applied to the data in the message payload.
For information about template selection expressions, see the section called “Template
selection expressions” (p. 717).
713
Amazon API Gateway Developer Guide
Integrations
{
"PassthroughBehavior": "WHEN_NO_MATCH",
"TimeoutInMillis": 29000,
"ConnectionType": "INTERNET",
"IntegrationResponseSelectionExpression": "${response.statuscode}",
"RequestTemplates": {
"application/json": "{\"statusCode\":200}"
},
"IntegrationId": "0abcdef",
"IntegrationType": "MOCK"
}
Alternatively, you can set up an integration request for a proxy integration by using the AWS CLI as in the
following example:
1. Create a Lambda function in the Lambda console and give it a basic Lambda execution role.
2. Execute the create-integration command as in the following example:
{
"PassthroughBehavior": "WHEN_NO_MATCH",
"IntegrationMethod": "POST",
"TimeoutInMillis": 29000,
"ConnectionType": "INTERNET",
"IntegrationUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:123412341234:function:simpleproxy-echo-e2e/invocations",
"IntegrationId": "abcdefg",
"IntegrationType": "AWS_PROXY"
}
714
Amazon API Gateway Developer Guide
Integrations
WebSocket routes can be configured for two-way or one-way communication. If a route has a route
response, it is configured for two-way communication. Otherwise, it is configured for one-way
communication.
• When a route is configured for two-way communication, an integration response allows you to
configure transformations on the returned message payload, similar to integration responses for REST
APIs.
• If a route is configured for one-way communication, then regardless of any integration response
configuration, no response will be returned over the WebSocket channel after the message is
processed.
The remainder of this document assumes you have chosen to configure a route with two-way
communication.
For non-proxy integrations, you must set up at least one integration response:
• Ideally, one of your integration responses should act as a catch-all when no explicit choice can be
made. This default case is represented by setting an integration response key of $default.
• In all other cases, the integration response key functions as a regular expression. It should follow a
format of "/expression/".
• API Gateway will attempt to match the HTTP status code of the backend response. The integration
response key will function as a regular expression in this case. If a match cannot be found, then
$default is chosen as the integration response.
• The template selection expression, as described above, functions identically. For example:
• /2\d\d/: Receive and transform successful responses
• /4\d\d/: Receive and transform bad request errors
• $default: Receive and transform all unexpected responses
For current limitations of template selection expressions, see the section called “Template selection
expressions” (p. 717).
1. Sign in to the API Gateway console, choose the API, and choose Routes.
2. Choose the route.
3. Choose Integration Response.
4. Under Integration Responses, enter a value in the Response Selection Expression text box.
5. Under Response Key, choose Add Response.
715
Amazon API Gateway Developer Guide
Request validation
a. To define an integration response key, enter a key name in the New Response Key text box and
choose the checkmark icon.
b. Choose the pencil icon next to Template Selection Expression and enter an expression for
API Gateway to look for in your outgoing message. This expression should evaluate to an
integration response key value that maps to one of your response templates.
For information about template selection expressions, see the section called “Template
selection expressions” (p. 717).
Request validation
You can configure API Gateway to perform validation on a route request before proceeding with the
integration request. If the validation fails, API Gateway fails the request without calling your backend,
sends a "Bad request body" gateway response to the client, and publishes the validation results in
CloudWatch Logs. Using validation this way reduces unnecessary calls to your API backend.
When you define a route (p. 706) for a WebSocket API, you can optionally specify a model selection
expression. This expression is evaluated to select the model to be used for body validation when a
request is received. The expression evaluates to one of the entries in a route's requestmodels.
A model is expressed as a JSON schema and describes the data structure of the request body. The nature
of this selection expression enables you to dynamically choose the model to validate against at runtime
for a particular route. For information about how to create a model, see the section called “Working with
models and mapping templates” (p. 377).
API Gateway lets you use mapping templates to map the payload from a method request to the
corresponding integration request and from an integration response to the corresponding method
response. You specify a template selection expression to determine which template to use to perform
the necessary data transformations.
716
Amazon API Gateway Developer Guide
Data transformations
You can use data mappings to map data from a route request (p. 9) to a backend integration. To learn
more, see the section called “Data mapping” (p. 717).
The payload can have a data model according to the JSON schema draft 4. You do not have to define
a model to create a mapping template. However, a model can help you create a template because API
Gateway generates a template blueprint based on a provided model. For more information about API
Gateway models, see Models (p. 377).
Unlike the other preceding selection expressions, this expression currently supports a pattern-matching
format. The expression should be wrapped with forward slashes.
Topics
• Map route request data to integration request parameters (p. 718)
717
Amazon API Gateway Developer Guide
Data transformations
In the following table, PARAM_NAME is the name of a route request parameter of the given parameter
type. It must match the regular expression '^[a-zA-Z0-9._$-]+$]'. JSONPath_EXPRESSION is a
JSONPath expression for a JSON field of the request body.
Examples
The following AWS CLI examples configure data mappings. For an example AWS CloudFormation
template, see websocket-data-mapping.yaml.
The following example command maps a client's connectionId to a connectionId header in the
request to a backend integration.
The following example commands map an authToken query string parameter to an authToken header
in the integration request.
First, add the authToken query string parameter to the route's request parameters.
718
Amazon API Gateway Developer Guide
Data transformations
Next, map the query string parameter to the authToken header in the request to the backend
integration.
Parameter Description
"context" : {
719
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
"key": "value",
"numKey": 1,
"boolKey": true
}
calling $context.authorizer.key
returns the "value" string, calling
$context.authorizer.numKey
returns the "1" string, and calling
$context.authorizer.boolKey returns the
"true" string.
720
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
721
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
[
{
"id": 1,
"type": "dog",
"price": 249.99
},
{
"id": 2,
"type": "cat",
"price": 124.99
},
{
"id": 3,
"type": "fish",
"price": 0.99
}
]
$input.path('$.pets').count() would
return "3".
722
Amazon API Gateway Developer Guide
Data transformations
Parameter Description
$util.escapeJavaScript(data).replaceAll("\
\'","'")
{"errorMessage":"{\"key1\":\"var1\",
\"key2\":{\"arr\":[1,2,3]}}"}
#set ($errorMessageObj =
$util.parseJson($input.path('$.errorMessage')))
{
"errorMessageObjKey2ArrVal" :
$errorMessageObj.key2.arr[0]
}
{
"errorMessageObjKey2ArrVal" : 1
}
723
Amazon API Gateway Developer Guide
Binary media types
There is a workaround for this behavior. If the client sends a text-encoded binary data (e.g.,
base64) as a text frame, you can set the integration's contentHandlingStrategy property to
CONVERT_TO_BINARY to convert the payload from base64-encoded string to binary.
To return a route response for a binary payload in non-proxy integrations, you can set the integration
response's contentHandlingStrategy property to CONVERT_TO_TEXT to convert the payload from
binary to base64-encoded string.
• You can use wscat to connect to your WebSocket API and send messages to it to simulate client
behavior. See the section called “Use wscat to connect to a WebSocket API and send messages to
it” (p. 724).
• You can use the @connections API from your backend service to send a callback message to a
connected client, get connection information, or disconnect the client. See the section called “Use
@connections commands in your backend service” (p. 725).
• A client application can use its own WebSocket library to invoke your WebSocket API.
3. To connect to your API, run the wscat command as shown in the following example. Note that this
example assumes that the Authorization setting is NONE.
wscat -c wss://aabbccddee.execute-api.us-east-1.amazonaws.com/test/
You need to replace aabbccddee with the actual API ID, which is displayed in the API Gateway
console or returned by the AWS CLI create-api command.
In addition, if your API is in a Region other than us-east-1, you need to substitute the correct
Region.
4. To test your API, enter a message such as the following while connected:
{"{jsonpath-expression}":"{route-key}"}
724
Amazon API Gateway Developer Guide
Invoke
{"action":"action1"}
{"message":"test response body"}
For more information about JSONPath, see JSONPath or JSONPath for Java.
5. To disconnect from your API, enter ctrl-C.
In the following command, you need to replace {api-id} with the actual API ID, which is displayed in
the API Gateway console or returned by the AWS CLI create-api command. In addition, if your API is in
a Region other than us-east-1, you need to substitute the correct Region.
POST https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/
@connections/{connection_id}
You can test this request by using Postman or by calling awscurl as in the following example:
GET https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/
@connections/{connection_id}
DELETE https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/
@connections/{connection_id}
You can dynamically build a callback URL by using the $context variables in your integration. For
example, if you use Lambda proxy integration with a Node.js Lambda function, you can build the URL
as follows:
725
Amazon API Gateway Developer Guide
Publish
In this section, you can learn how to deploy your API and customize the URL that you provide to users to
access it.
Topics
• Working with stages for WebSocket APIs (p. 726)
• Deploy a WebSocket API in API Gateway (p. 727)
• Setting up custom domain names for WebSocket APIs (p. 729)
A deployment is a snapshot of your API configuration. After you deploy an API to a stage, it’s available
for clients to invoke. You must deploy an API for changes to take effect.
Stage variables
Stage variables are key-value pairs that you can define for a stage of a WebSocket API. They act like
environment variables and can be used in your API setup.
For example, you can define a stage variable, and then set its value as an HTTP endpoint for an HTTP
proxy integration. Later, you can reference the endpoint by using the associated stage variable name. By
doing this, you can use the same API setup with a different endpoint at each stage. Similarly, you can use
stage variables to specify a different AWS Lambda function integration for each stage of your API.
Note
Stage variables are not intended to be used for sensitive data, such as credentials. To pass
sensitive data to integrations, use an AWS Lambda authorizer. You can pass sensitive data
to integrations in the output of the Lambda authorizer. To learn more, see the section called
“Lambda authorizer response format” (p. 191).
Examples
To use a stage variable to customize the HTTP integration endpoint, you must first set the name and
value of the stage variable (for example, url) with a value of example.com. Next, set up an HTTP
proxy integration. Instead of entering the endpoint's URL, you can tell API Gateway to use the stage
726
Amazon API Gateway Developer Guide
Deploy a WebSocket API
variable value, http://${stageVariables.url}. This value tells API Gateway to substitute your
stage variable ${} at runtime, depending on the stage of your API.
You can reference stage variables in a similar way to specify a Lambda function name or an AWS role
ARN.
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 (AWS CLI) to do this.
Lambda functions
You can use a stage variable in place of a Lambda function name or alias, as shown in the following
examples.
• arn:aws:apigateway:<region>:lambda:path/2015-03-31/
functions/arn:aws:lambda:<region>:<account_id>:function:
${stageVariables.<function_variable_name>}/invocations
• arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/
arn:aws:lambda:<region>:<account_id>:function:<function_name>:
${stageVariables.<version_variable_name>}/invocations
Note
To use a stage variable for a Lambda function, the function must be in the same account as the
API. Stage variables don't support cross-account Lambda functions.
• arn:aws:iam::<account_id>:${stageVariables.<variable_name>}
727
Amazon API Gateway Developer Guide
Deploy a WebSocket API
To deploy an API, you create an API deployment (p. 6) and associate it with a stage (p. 6). Each stage is a
snapshot of the API and is made available for client apps to call.
Important
Every time you update an API, which includes modification of routes, methods, integrations,
authorizers, and anything else other than stage settings, you must redeploy the API to an
existing stage or to a new stage.
By default you are limited to 10 stages per API, so it is good practice to reuse them.
To call a deployed WebSocket API, the client sends a message to the API's URL. The URL is determined by
the API's hostname and stage name.
Note
API Gateway will support payloads up to 128 KB with a maximum frame size of 32 KB. If a
message exceeds 32 KB, it must be split into multiple frames, each 32 KB or smaller.
Using the API's default domain name, the URL of (for example) a WebSocket API in a given stage
({stageName}) is in the following format:
wss://{api-id}.execute-api.{region}.amazonaws.com/{stageName}
To make the WebSocket API's URL more user-friendly, you can create a custom domain name (e.g.,
api.example.com) to replace the default host name of the API. The configuration process is the same
as for REST APIs. For more information, see the section called “Custom domain names” (p. 518).
Stages enable robust version control of your API. For example, you can deploy an API to a test stage
and a prod stage, and use the test stage as a test build and use the prod stage as a stable build. After
the updates pass the test, you can promote the test stage to the prod stage. The promotion can be
done by redeploying the API to the prod stage. For more details about stages, see the section called “Set
up a stage” (p. 493).
Topics
• Create a WebSocket API deployment using the AWS CLI (p. 728)
• Create a WebSocket API deployment using the API Gateway console (p. 729)
Example output:
{
"DeploymentId": "fedcba",
"DeploymentStatus": "DEPLOYED",
"CreatedDate": "2018-11-15T06:49:09Z"
}
The deployed API is not callable until you associate the deployment with a stage. You can create a new
stage or reuse a stage that you have previously created.
To create a new stage and associate it with the deployment, use the create-stage command as shown
in the following example:
728
Amazon API Gateway Developer Guide
Custom domain names
Example output:
{
"StageName": "test",
"CreatedDate": "2018-11-15T06:50:28Z",
"DeploymentId": "fedcba",
"DefaultRouteSettings": {
"MetricsEnabled": false,
"ThrottlingBurstLimit": 5000,
"DataTraceEnabled": false,
"ThrottlingRateLimit": 10000.0
},
"LastUpdatedDate": "2018-11-15T06:50:28Z",
"StageVariables": {},
"RouteSettings": {}
}
To reuse an existing stage, update the stage's deploymentId property with the newly created
deployment ID ({deployment-id}) by using the update-stage command.
After deploying your API, you (and your customers) can invoke the API using the default base URL of the
following format:
https://api-id.execute-api.region.amazonaws.com/stage
where api-id is generated by API Gateway, region (AWS Region) is specified by you when creating the
API, and stage is specified by you when deploying the API.
729
Amazon API Gateway Developer Guide
Custom domain names
With custom domain names, you can set up your API's hostname, and choose a base path (for example,
myservice) to map the alternative URL to your API. For example, a more user-friendly API base URL can
become:
https://api.example.com/myservice
If you don't set any base mapping under a custom domain name, the resulting API's base URL is the same
as the custom domain (for example, https://api.example.com). In this case, the custom domain
name can't support more than one API.
Note
A custom domain name for a WebSocket API can't be mapped to REST APIs or HTTP APIs.
For WebSocket APIs, TLS 1.2 is the only supported TLS version.
After a custom domain name is created in API Gateway, you must create or update your DNS provider's
resource record to map to your API endpoint. Without such a mapping, API requests bound for the
custom domain name cannot reach API Gateway.
To create a wildcard custom domain name, specify a wildcard (*) as the first subdomain of a custom
domain that represents all possible subdomains of a root domain.
For example, the wildcard custom domain name *.example.com results in subdomains such as
a.example.com, b.example.com, and c.example.com, which all route to the same domain.
Wildcard custom domain names support distinct configurations from API Gateway's standard custom
domain names. For example, in a single AWS account, you can configure *.example.com and
a.example.com to behave differently.
To create a wildcard custom domain name, you must provide a certificate issued by ACM that has been
validated using either the DNS or the email validation method.
Note
You can't create a wildcard custom domain name if a different AWS account has created a
custom domain name that conflicts with the wildcard custom domain name. For example,
730
Amazon API Gateway Developer Guide
Custom domain names
if account A has created a.example.com, then account B can't create the wildcard custom
domain name *.example.com.
If account A and account B share an owner, you can contact the AWS Support Center to request
an exception.
To import an SSL/TLS certificate, you must provide the PEM-formatted SSL/TLS certificate body, its
private key, and the certificate chain for the custom domain name. Each certificate stored in ACM is
identified by its ARN. To use an AWS managed certificate for a domain name, you simply reference its
ARN.
ACM makes it straightforward to set up and use a custom domain name for an API. You create a
certificate for the given domain name (or import a certificate), set up the domain name in API Gateway
with the ARN of the certificate provided by ACM, and map a base path under the custom domain name
to a deployed stage of the API. With certificates issued by ACM, you do not have to worry about exposing
any sensitive certificate details, such as the private key.
For details on setting up a custom domain name, see Getting certificates ready in AWS Certificate
Manager (p. 521) and Setting up a regional custom domain name in API Gateway (p. 531).
An API mapping specifies an API, a stage, and optionally a path to use for the mapping. For example, you
can map the production stage of an API to wss://api.example.com/orders.
Before you create an API mapping, you must have an API, a stage, and a custom domain name. To
learn more about creating a custom domain name, see the section called “Setting up a regional custom
domain name” (p. 531).
Restrictions
• In an API mapping, the custom domain name and mapped APIs must be in the same AWS account.
• API mappings must contain only letters, numbers, and the following characters: $-_.+!*'().
• The maximum length for the path in an API mapping is 300 characters.
• You can't map WebSocket APIs to the same custom domain name as an HTTP API or REST API.
731
Amazon API Gateway Developer Guide
Custom domain names
AWS CLI
The following AWS CLI command creates an API mapping. In this example, API Gateway sends
requests to api.example.com/v1 to the specified API and stage.
AWS CloudFormation
MyApiMapping:
Type: 'AWS::ApiGatewayV2::ApiMapping'
Properties:
DomainName: api.example.com
ApiMappingKey: 'v1'
ApiId: !Ref MyApi
Stage: !Ref MyStage
The following AWS CLI command disables the default endpoint for an WebSocket API.
After you disable the default endpoint, you must deploy your API for the change to take effect.
732
Amazon API Gateway Developer Guide
Protect
API Gateway throttles requests to your API using the token bucket algorithm, where a token counts for
a request. Specifically, API Gateway examines the rate and a burst of request submissions against all
APIs in your account, per Region. In the token bucket algorithm, a burst can allow pre-defined overrun of
those limits, but other factors can also cause limits to be overrun in some cases.
When request submissions exceed the steady-state request rate and burst limits, API Gateway begins to
throttle requests. Clients may receive 429 Too Many Requests error responses at this point. Upon
catching such exceptions, the client can resubmit the failed requests in a way that is rate limiting.
As an API developer, you can set the target limits for individual API stages or routes to improve overall
performance across all APIs in your account.
Per-account limits are applied to all APIs in an account in a specified Region. The account-level rate limit
can be increased upon request - higher limits are possible with APIs that have shorter timeouts and
smaller payloads. To request an increase of account-level throttling limits per Region, contact the AWS
Support Center. For more information, see Quotas and important notes (p. 813). Note that these limits
can't be higher than the AWS throttling limits.
Route-level throttling
You can set route-level throttling to override the account-level request throttling limits for a specific
stage or for individual routes in your API. The default route throttling limits can' exceed account-level
rate limits.
Topics
• Monitoring WebSocket API execution with CloudWatch metrics (p. 734)
• Configuring logging for a WebSocket API (p. 735)
733
Amazon API Gateway Developer Guide
Metrics
Metric Description
You can use the dimensions in the following table to filter API Gateway metrics.
Dimension Description
734
Amazon API Gateway Developer Guide
Logging
Dimension Description
CloudWatch metrics. You can do
this by calling the UpdateStage
action of the API Gateway
V2 REST API to update the
metricsEnabled property to
true. Enabling such metrics will
incur additional charges to your
account. For pricing information,
see Amazon CloudWatch Pricing.
For instructions on how to set up CloudWatch logging, see the section called “Set up CloudWatch API
logging using the API Gateway console” (p. 680).
When you specify the Log Format, you can choose which context variables to log. The following
variables are supported.
Parameter Description
735
Amazon API Gateway Developer Guide
Logging
Parameter Description
"context" : {
"key": "value",
"numKey": 1,
"boolKey": true
}
calling $context.authorizer.key
returns the "value" string, calling
$context.authorizer.numKey
returns the "1" string, and calling
$context.authorizer.boolKey returns the
"true" string.
736
Amazon API Gateway Developer Guide
Logging
Parameter Description
737
Amazon API Gateway Developer Guide
Logging
Parameter Description
738
Amazon API Gateway Developer Guide
HTTP API and WebSocket API resources
AccessLogSettings arn:partition:apigateway:region::/
apis/api-id/stages/stage-name/
accesslogsettings
Api arn:partition:apigateway:region::/
apis/api-id
Apis arn:partition:apigateway:region::/apis
ApiMapping arn:partition:apigateway:region::/
domainnames/domain-name/apimappings/id
ApiMappings arn:partition:apigateway:region::/
domainnames/domain-name/apimappings
Authorizer arn:partition:apigateway:region::/
apis/api-id/authorizers/id
Authorizers arn:partition:apigateway:region::/
apis/api-id/authorizers
Cors arn:partition:apigateway:region::/
apis/api-id/cors
Deployment arn:partition:apigateway:region::/
apis/api-id/deployments/id
Deployments arn:partition:apigateway:region::/
apis/api-id/deployments
DomainName arn:partition:apigateway:region::/
domainnames/domain-name
DomainNames arn:partition:apigateway:region::/
domainnames
ExportedAPI arn:partition:apigateway:region::/
apis/api-id/exports/specification
Integration arn:partition:apigateway:region::/
apis/api-id/integrations/integration-
id
739
Amazon API Gateway Developer Guide
HTTP API and WebSocket API resources
Resource ARN
Integrations arn:partition:apigateway:region::/
apis/api-id/integrations
IntegrationResponse arn:partition:apigateway:region::/
apis/api-id/
integrationresponses/integration-
response
IntegrationResponses arn:partition:apigateway:region::/
apis/api-id/integrationresponses
Model arn:partition:apigateway:region::/
apis/api-id/models/id
Models arn:partition:apigateway:region::/
apis/api-id/models
ModelTemplate arn:partition:apigateway:region::/
apis/api-id/models/id/template
Route arn:partition:apigateway:region::/
apis/api-id/routes/id
Routes arn:partition:apigateway:region::/
apis/api-id/routes
RouteRequestParameter arn:partition:apigateway:region::/
apis/api-id/routes/id/
requestparameters/key
RouteResponse arn:partition:apigateway:region::/
apis/api-id/routes/id/
routeresponses/id
RouteResponses arn:partition:apigateway:region::/
apis/api-id/routes/id/routeresponses
RouteSettings arn:partition:apigateway:region::/
apis/api-id/stages/stage-name/
routesettings/route-key
Stage arn:partition:apigateway:region::/
apis/api-id/stages/stage-name
Stages arn:partition:apigateway:region::/
apis/api-id/stages
VpcLink arn:partition:apigateway:region::/
vpclinks/vpclink-id
VpcLinks arn:partition:apigateway:region::/
vpclinks
740
Amazon API Gateway Developer Guide
REST API resources
Account arn:partition:apigateway:region::/
account
ApiKey arn:partition:apigateway:region::/
apikeys/id
ApiKeys arn:partition:apigateway:region::/
apikeys
Authorizer arn:partition:apigateway:region::/
restapis/api-id/authorizers/id
Authorizers arn:partition:apigateway:region::/
restapis/api-id/authorizers
BasePathMapping arn:partition:apigateway:region::/
domainnames/domain-name/
basepathmappings/basepath
BasePathMappings arn:partition:apigateway:region::/
domainnames/domain-name/
basepathmappings
ClientCertificate arn:partition:apigateway:region::/
clientcertificates/id
ClientCertificates arn:partition:apigateway:region::/
clientcertificates
Deployment arn:partition:apigateway:region::/
restapis/api-id/deployments/id
Deployments arn:partition:apigateway:region::/
restapis/api-id/deployments
DocumentationPart arn:partition:apigateway:region::/
restapis/api-id/documentation/parts/id
DocumentationParts arn:partition:apigateway:region::/
restapis/api-id/documentation/parts
DocumentationVersion arn:partition:apigateway:region::/
restapis/api-id/documentation/
versions/version
DocumentationVersions arn:partition:apigateway:region::/
restapis/api-id/documentation/versions
DomainName arn:partition:apigateway:region::/
domainnames/domain-name
DomainNames arn:partition:apigateway:region::/
domainnames
741
Amazon API Gateway Developer Guide
REST API resources
Resource ARN
GatewayResponse arn:partition:apigateway:region::/
restapis/api-id/
gatewayresponses/response-type
GatewayResponses arn:partition:apigateway:region::/
restapis/api-id/gatewayresponses
Integration arn:partition:apigateway:region::/
restapis/api-id/resources/resource-id/
methods/http-method/integration
IntegrationResponse arn:partition:apigateway:region::/
restapis/api-id/resources/resource-
id/methods/http-method/integration/
responses/status-code
Method arn:partition:apigateway:region::/
restapis/api-id/resources/resource-id/
methods/http-method
MethodResponse arn:partition:apigateway:region::/
restapis/api-id/resources/resource-id/
methods/http-method/responses/status-
code
Model arn:partition:apigateway:region::/
restapis/api-id/models/model-name
Models arn:partition:apigateway:region::/
restapis/api-id/models
RequestValidator arn:partition:apigateway:region::/
restapis/api-id/requestvalidators/id
RequestValidators arn:partition:apigateway:region::/
restapis/api-id/requestvalidators
Resource arn:partition:apigateway:region::/
restapis/api-id/resources/id
Resources arn:partition:apigateway:region::/
restapis/api-id/resources
RestApi arn:partition:apigateway:region::/
restapis/api-id
RestApis arn:partition:apigateway:region::/
restapis
Stage arn:partition:apigateway:region::/
restapis/api-id/stages/stage-name
Stages arn:partition:apigateway:region::/
restapis/api-id/stages
Template arn:partition:apigateway:region::/
restapis/models/model-name/template
742
Amazon API Gateway Developer Guide
execute-api (HTTP APIs, WebSocket APIs, and REST APIs)
Resource ARN
UsagePlan arn:partition:apigateway:region::/
usageplans/usageplan-id
UsagePlans arn:partition:apigateway:region::/
usageplans
UsagePlanKey arn:partition:apigateway:region::/
usageplans/usageplan-id/keys/id
UsagePlanKeys arn:partition:apigateway:region::/
usageplans/usageplan-id/keys
VpcLink arn:partition:apigateway:region::/
vpclinks/vpclink-id
VpcLinks arn:partition:apigateway:region::/
vpclinks
* This ARN is applicable only when setting the SourceArn condition in the resource policy for a Lambda
authorizer function. For an example, see the section called “Create a Lambda authorizer” (p. 195).
743
Amazon API Gateway Developer Guide
Topics
• x-amazon-apigateway-any-method object (p. 745)
• x-amazon-apigateway-cors object (p. 746)
• x-amazon-apigateway-api-key-source property (p. 747)
• x-amazon-apigateway-auth object (p. 747)
• x-amazon-apigateway-authorizer object (p. 748)
• x-amazon-apigateway-authtype property (p. 753)
• x-amazon-apigateway-binary-media-types property (p. 755)
• x-amazon-apigateway-documentation object (p. 755)
• x-amazon-apigateway-endpoint-configuration object (p. 756)
• x-amazon-apigateway-gateway-responses object (p. 757)
• x-amazon-apigateway-gateway-responses.gatewayResponse object (p. 757)
• x-amazon-apigateway-gateway-responses.responseParameters object (p. 758)
• x-amazon-apigateway-gateway-responses.responseTemplates object (p. 759)
• x-amazon-apigateway-importexport-version (p. 759)
• x-amazon-apigateway-integration object (p. 760)
• x-amazon-apigateway-integrations object (p. 764)
• x-amazon-apigateway-integration.requestTemplates object (p. 766)
• x-amazon-apigateway-integration.requestParameters object (p. 767)
• x-amazon-apigateway-integration.responses object (p. 768)
• x-amazon-apigateway-integration.response object (p. 769)
• x-amazon-apigateway-integration.responseTemplates object (p. 771)
• x-amazon-apigateway-integration.responseParameters object (p. 771)
• x-amazon-apigateway-integration.tlsConfig object (p. 772)
• x-amazon-apigateway-minimum-compression-size (p. 773)
• x-amazon-apigateway-policy (p. 773)
• x-amazon-apigateway-request-validator property (p. 774)
• x-amazon-apigateway-request-validators object (p. 775)
• x-amazon-apigateway-request-validators.requestValidator object (p. 776)
• x-amazon-apigateway-tag-value property (p. 776)
744
Amazon API Gateway Developer Guide
x-amazon-apigateway-any-method
x-amazon-apigateway-any-method object
Specifies the OpenAPI Operation Object for the API Gateway catch-all ANY method in an OpenAPI Path
Item Object. This object can exist alongside other Operation objects and will catch any HTTP method
that wasn't explicitly declared.
The following table lists the properties extended by API Gateway. For the other OpenAPI Operation
properties, see the OpenAPI specification.
Properties
x-amazon-apigateway-any-method examples
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"
],
"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",
"httpMethod": "POST",
"type": "aws_proxy"
}
The following example creates a $default route for an HTTP API that integrates with a Lambda
function, HelloWorld.
"/$default": {
745
Amazon API Gateway Developer Guide
x-amazon-apigateway-cors
"x-amazon-apigateway-any-method": {
"isDefaultRoute": true,
"x-amazon-apigateway-integration": {
"type": "AWS_PROXY",
"httpMethod": "POST",
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations",
"timeoutInMillis": 1000,
"connectionType": "INTERNET",
"payloadFormatVersion": 1.0
}
}
}
x-amazon-apigateway-cors object
Specifies the cross-origin resource sharing (CORS) configuration for an HTTP API. The extension applies
to the root-level OpenAPI structure. To learn more, see Configuring CORS for an HTTP API (p. 209).
Properties
x-amazon-apigateway-cors example
The following is an example CORS configuration for an HTTP API.
"x-amazon-apigateway-cors": {
"allowOrigins": [
"https://www.example.com"
],
"allowCredentials": true,
"exposeHeaders": [
"x-apigateway-header",
"x-amz-date",
"content-type"
],
"maxAge": 3600,
"allowMethods": [
"GET",
"OPTIONS",
746
Amazon API Gateway Developer Guide
x-amazon-apigateway-api-key-source
"POST"
],
"allowHeaders": [
"x-apigateway-header",
"x-amz-date",
"content-type"
]
}
x-amazon-apigateway-api-key-source property
Specify the source to receive an API key to throttle API methods that require a key. This API-level
property is a String type.
Specify the source of the API key for requests. Valid values are:
• HEADER for receiving the API key from the X-API-Key header of a request.
• AUTHORIZER for receiving the API key from the UsageIdentifierKey from a Lambda authorizer
(formerly known as a custom authorizer).
x-amazon-apigateway-api-key-source example
The following example sets the X-API-Key header as the API key source.
OpenAPI 2.0
{
"swagger" : "2.0",
"info" : {
"title" : "Test1"
},
"schemes" : [ "https" ],
"basePath" : "/import",
"x-amazon-apigateway-api-key-source" : "HEADER",
.
.
.
}
x-amazon-apigateway-auth object
Defines an authorization type to be applied for authorization of method invocations in API Gateway.
Properties
747
Amazon API Gateway Developer Guide
x-amazon-apigateway-auth example
x-amazon-apigateway-auth example
The following example sets the authorization type for an API method.
OpenAPI 3.0.1
{
"openapi": "3.0.1",
"info": {
"title": "openapi3",
"version": "1.0"
},
"paths": {
"/protected-by-iam": {
"get": {
"x-amazon-apigateway-auth": {
"type": "AWS_IAM"
}
}
}
}
}
x-amazon-apigateway-authorizer object
Defines a Lambda authorizer or JWT authorizer to be applied for authorization of method invocations in
API Gateway. This extension applies to the security definition in OpenAPI 2 and OpenAPI 3.
Properties
"arn:aws:apigateway:us-
east-1:lambda:path/2015-03-31/
functions/arn:aws:lambda:us-
748
Amazon API Gateway Developer Guide
x-amazon-apigateway-authorizer
authorizerPayloadFormatVersion
string For HTTP APIs, specifies the
format of the data that API
Gateway sends to a Lambda
authorizer, and how API
Gateway interprets the response
from Lambda. To learn more,
see the section called “Payload
format version” (p. 189).
identityValidationExpression
string A regular expression for
validating the token as the
incoming identity. For example,
"^x-[a-z]+". Supported only for
REST APIs.
749
Amazon API Gateway Developer Guide
x-amazon-apigateway-authorizer examples for REST APIs
authorizerResultTtlInSeconds
string The number of seconds during
which authorizer result is
cached.
"securityDefinitions" : {
"test-authorizer" : {
"type" : "apiKey", // Required and the value must be "apiKey"
for an API Gateway API.
"name" : "Authorization", // The name of the header containing the
authorization token.
"in" : "header", // Required and the value must be "header"
for an API Gateway API.
"x-amazon-apigateway-authtype" : "oauth2", // Specifies the authorization mechanism
for the client.
"x-amazon-apigateway-authorizer" : { // An API Gateway Lambda authorizer
definition
"type" : "token", // Required property and the value must
"token"
"authorizerUri" : "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:account-id:function:function-name/invocations",
"authorizerCredentials" : "arn:aws:iam::account-id:role",
"identityValidationExpression" : "^x-[a-z]+",
"authorizerResultTtlInSeconds" : 60
}
}
}
The following OpenAPI operation object snippet sets the GET /http to use the preceding Lambda
authorizer.
"/http" : {
"get" : {
"responses" : { },
"security" : [ {
"test-authorizer" : [ ]
} ],
"x-amazon-apigateway-integration" : {
"type" : "http",
"responses" : {
"default" : {
"statusCode" : "200"
}
},
"httpMethod" : "GET",
"uri" : "http://api.example.com"
}
}
}
750
Amazon API Gateway Developer Guide
x-amazon-apigateway-authorizer examples for REST APIs
The following OpenAPI security definitions example specifies a Lambda authorizer of the "request" type,
with a single header parameter (auth) as the identity source. The securityDefinitions is named
request_authorizer_single_header.
"securityDefinitions": {
"request_authorizer_single_header" : {
"type" : "apiKey",
"name" : "auth", // The name of a single header or query parameter as
the identity source.
"in" : "header", // The location of the single identity source request
parameter. The valid value is "header" or "query"
"x-amazon-apigateway-authtype" : "custom",
"x-amazon-apigateway-authorizer" : {
"type" : "request",
"identitySource" : "method.request.header.auth", // Request parameter mapping
expression of the identity source. In this example, it is the 'auth' header.
"authorizerCredentials" : "arn:aws:iam::123456789012:role/AWSepIntegTest-CS-
LambdaRole",
"authorizerUri" : "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:123456789012:function:APIGateway-Request-Authorizer:vtwo/
invocations",
"authorizerResultTtlInSeconds" : 300
}
}
}
The following OpenAPI security definitions example specifies a Lambda authorizer of the "request" type,
with one header (HeaderAuth1) and one query string parameter QueryString1 as the identity sources.
"securityDefinitions": {
"request_authorizer_header_query" : {
"type" : "apiKey",
"name" : "Unused", // Must be "Unused" for multiple identity sources or
non header or query type of request parameters.
"in" : "header", // Must be "header" for multiple identity sources or
non header or query type of request parameters.
"x-amazon-apigateway-authtype" : "custom",
"x-amazon-apigateway-authorizer" : {
"type" : "request",
"identitySource" : "method.request.header.HeaderAuth1,
method.request.querystring.QueryString1", // Request parameter mapping expressions of
the identity sources.
"authorizerCredentials" : "arn:aws:iam::123456789012:role/AWSepIntegTest-CS-
LambdaRole",
"authorizerUri" : "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:123456789012:function:APIGateway-Request-Authorizer:vtwo/
invocations",
"authorizerResultTtlInSeconds" : 300
}
}
}
The following OpenAPI security definitions example specifies an API Gateway Lambda authorizer of the
"request" type, with a single stage variable (stage) as the identity source.
"securityDefinitions": {
"request_authorizer_single_stagevar" : {
"type" : "apiKey",
"name" : "Unused", // Must be "Unused", for multiple identity sources or
non header or query type of request parameters.
"in" : "header", // Must be "header", for multiple identity sources or
non header or query type of request parameters.
751
Amazon API Gateway Developer Guide
x-amazon-apigateway-authorizer examples for HTTP APIs
"x-amazon-apigateway-authtype" : "custom",
"x-amazon-apigateway-authorizer" : {
"type" : "request",
"identitySource" : "stageVariables.stage", // Request parameter mapping
expression of the identity source. In this example, it is the stage variable.
"authorizerCredentials" : "arn:aws:iam::123456789012:role/AWSepIntegTest-CS-
LambdaRole",
"authorizerUri" : "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:123456789012:function:APIGateway-Request-Authorizer:vtwo/
invocations",
"authorizerResultTtlInSeconds" : 300
}
}
}
"securitySchemes": {
"jwt-authorizer-oauth": {
"type": "oauth2",
"x-amazon-apigateway-authorizer": {
"type": "jwt",
"jwtConfiguration": {
"issuer": "https://cognito-idp.region.amazonaws.com/userPoolId",
"audience": [
"audience1",
"audience2"
]
},
"identitySource": "$request.header.Authorization"
}
}
}
The following OpenAPI 3.0 example produces the same JWT authorizer as the previous example.
However, this example uses the OpenAPI openIdConnectUrl property to automatically detect the
issuer. The openIdConnectUrl must be fully formed.
"securitySchemes": {
"jwt-authorizer-autofind": {
"type": "openIdConnect",
"openIdConnectUrl": "https://cognito-idp.region.amazonaws.com/userPoolId/.well-known/
openid-configuration",
"x-amazon-apigateway-authorizer": {
"type": "jwt",
"jwtConfiguration": {
"audience": [
"audience1",
"audience2"
]
},
"identitySource": "$request.header.Authorization"
}
}
}
752
Amazon API Gateway Developer Guide
x-amazon-apigateway-authtype
The following example creates a Lambda authorizer for an HTTP API. This example authorizer uses the
Authorization header as its identity source. The authorizer uses the 2.0 payload format version, and
returns Boolean value, because enableSimpleResponses is set to true.
"securitySchemes" : {
"lambda-authorizer" : {
"type" : "apiKey",
"name" : "Authorization",
"in" : "header",
"x-amazon-apigateway-authorizer" : {
"type" : "request",
"identitySource" : "$request.header.Authorization",
"authorizerUri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-west-2:123456789012:function:function-name/invocations",
"authorizerPayloadFormatVersion" : "2.0",
"authorizerResultTtlInSeconds" : 300,
"enableSimpleResponses" : true
}
}
}
x-amazon-apigateway-authtype property
For REST APIs, this extension can be used to define a custom type of a Lambda authorizer. In this case,
the value is free-form. For example, an API may have multiple Lambda authorizers that use different
internal schemes. You can use this extension to identify the internal scheme of a Lambda authorizer.
More commonly, in HTTP APIs and REST APIs, it can also be used as a way to define IAM authorization
across several operations that share the same security scheme. In this case, the term awsSigv4 is a
reserved term, along with any term prefixed by aws.
This extension applies to the apiKey type security scheme in OpenAPI 2 and OpenAPI 3.
x-amazon-apigateway-authtype example
The following OpenAPI 3 example defines IAM authorization across multiple resources in a REST API or
HTTP API:
{
"openapi" : "3.0.1",
"info" : {
"title" : "openapi3",
"version" : "1.0"
},
"paths" : {
"/operation1" : {
"get" : {
"responses" : {
"default" : {
"description" : "Default response"
}
},
"security" : [ {
"sigv4Reference" : [ ]
} ]
}
},
"/operation2" : {
"get" : {
"responses" : {
753
Amazon API Gateway Developer Guide
x-amazon-apigateway-authtype example
"default" : {
"description" : "Default response"
}
},
"security" : [ {
"sigv4Reference" : [ ]
} ]
}
}
},
"components" : {
"securitySchemes" : {
"sigv4Reference" : {
"type" : "apiKey",
"name" : "Authorization",
"in" : "header",
"x-amazon-apigateway-authtype": "awsSigv4"
}
}
}
}
The following OpenAPI 3 example defines a Lambda authorizer with a custom scheme for a REST API:
{
"openapi" : "3.0.1",
"info" : {
"title" : "openapi3 for REST API",
"version" : "1.0"
},
"paths" : {
"/protected-by-lambda-authorizer" : {
"get" : {
"responses" : {
"200" : {
"description" : "Default response"
}
},
"security" : [ {
"myAuthorizer" : [ ]
} ]
}
}
},
"components" : {
"securitySchemes" : {
"myAuthorizer" : {
"type" : "apiKey",
"name" : "Authorization",
"in" : "header",
"x-amazon-apigateway-authorizer" : {
"identitySource" : "method.request.header.Authorization",
"authorizerUri" : "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-1:account-id:function:function-name/invocations",
"authorizerResultTtlInSeconds" : 300,
"type" : "request",
"enableSimpleResponses" : false
},
"x-amazon-apigateway-authtype": "Custom scheme with corporate claims"
}
}
},
"x-amazon-apigateway-importexport-version" : "1.0"
}
754
Amazon API Gateway Developer Guide
See also
See also
authorizer.authType
x-amazon-apigateway-binary-media-types
property
Specifies the list of binary media types to be supported by API Gateway, such as application/octet-
stream and image/jpeg. This extension is a JSON array. It should be included as a top-level vendor
extension to the OpenAPI document.
x-amazon-apigateway-binary-media-types example
The following example shows the encoding lookup order of an API.
x-amazon-apigateway-documentation object
Defines the documentation parts to be imported into API Gateway. This object is a JSON object
containing an array of the DocumentationPart instances.
Properties
Property name Type Description
x-amazon-apigateway-documentation example
The following example of the API Gateway extension to OpenAPI defines DocumentationParts
instances to be imported to or exported from an API in API Gateway.
{ ...
"x-amazon-apigateway-documentation": {
"version": "1.0.3",
"documentationParts": [
{
"location": {
"type": "API"
},
"properties": {
"description": "API description",
"info": {
"description": "API info description 4",
"version": "API info version 3"
755
Amazon API Gateway Developer Guide
x-amazon-apigateway-endpoint-configuration
}
}
},
{
… // Another DocumentationPart instance
}
]
}
}
x-amazon-apigateway-endpoint-configuration
object
Specifies details of the endpoint configuration for an API. This extension is an extended property of the
OpenAPI Operation object. This object should be present in top-level vendor extensions for Swagger 2.0.
For OpenAPI 3.0, it should be present under the vendor extensions of the Server object.
Properties
Property name Type Description
x-amazon-apigateway-endpoint-configuration
examples
The following example associates specified VPC endpoints to the REST API.
"x-amazon-apigateway-endpoint-configuration": {
"vpcEndpointIds": ["vpce-0212a4ababd5b8c3e", "vpce-01d622316a7df47f9"]
}
"x-amazon-apigateway-endpoint-configuration": {
"disableExecuteApiEndpoint": true
}
756
Amazon API Gateway Developer Guide
x-amazon-apigateway-gateway-responses
x-amazon-apigateway-gateway-responses object
Defines the gateway responses for an API as a string-to-GatewayResponse map of key-value pairs. The
extension applies to the root-level OpenAPI structure.
Properties
x-amazon-apigateway-gateway-responses example
The following API Gateway extension to OpenAPI example defines a GatewayResponses map that
contains two GatewayResponse instances—one for the DEFAULT_4XX type and another for the
INVALID_API_KEY type.
{
"x-amazon-apigateway-gateway-responses": {
"DEFAULT_4XX": {
"responseParameters": {
"gatewayresponse.header.Access-Control-Allow-Origin": "'domain.com'"
},
"responseTemplates": {
"application/json": "{\"message\": test 4xx b }"
}
},
"INVALID_API_KEY": {
"statusCode": "429",
"responseTemplates": {
"application/json": "{\"message\": test forbidden }"
}
}
}
}
x-amazon-apigateway-gateway-
responses.gatewayResponse object
Defines a gateway response of a given response type, including the status code, any applicable response
parameters, or response templates.
Properties
757
Amazon API Gateway Developer Guide
x-amazon-apigateway-gateway-
responses.gatewayResponse example
x-amazon-apigateway-gateway-
responses.gatewayResponse example
The following example of the API Gateway extension to OpenAPI defines a GatewayResponse to
customize the INVALID_API_KEY response to return the status code of 456, the incoming request's
api-key header value, and a "Bad api-key" message.
"INVALID_API_KEY": {
"statusCode": "456",
"responseParameters": {
"gatewayresponse.header.api-key": "method.request.header.api-key"
},
"responseTemplates": {
"application/json": "{\"message\": \"Bad api-key\" }"
}
}
x-amazon-apigateway-gateway-
responses.responseParameters object
Defines a string-to-string map of key-value pairs to generate gateway response parameters from the
incoming request parameters or using literal strings. Supported only for REST APIs.
Properties
x-amazon-apigateway-gateway-
responses.responseParameters example
The following OpenAPI extensions example shows a GatewayResponse response parameter mapping
expression to enable CORS support for resources on the *.example.domain domains.
758
Amazon API Gateway Developer Guide
x-amazon-apigateway-gateway-
responses.responseTemplates
"responseParameters": {
"gatewayresponse.header.Access-Control-Allow-Origin": '*.example.domain',
"gatewayresponse.header.from-request-header" : method.request.header.Accept,
"gatewayresponse.header.from-request-path" : method.request.path.petId,
"gatewayresponse.header.from-request-query" : method.request.querystring.qname
}
x-amazon-apigateway-gateway-
responses.responseTemplates object
Defines GatewayResponse mapping templates, as a string-to-string map of key-value pairs, for a given
gateway response. For each key-value pair, the key is the content type. For example, "application/json"
and the value is a stringified mapping template for simple variable substitutions. A GatewayResponse
mapping template isn't processed by the Velocity Template Language (VTL) engine.
Properties
x-amazon-apigateway-gateway-
responses.responseTemplates example
The following OpenAPI extensions example shows a GatewayResponse mapping template to customize
an API Gateway–generated error response into an app-specific format.
"responseTemplates": {
"application/json": "{ \"message\": $context.error.messageString, \"type\":
$context.error.responseType, \"statusCode\": '488' }
}
The following OpenAPI extensions example shows a GatewayResponse mapping template to override an
API Gateway–generated error response with a static error message.
"responseTemplates": {
"application/json": "{ \"message\": 'API-specific errors' }" }
}
x-amazon-apigateway-importexport-version
Specifies the version of the API Gateway import and export algorithm for HTTP APIs. Currently, the only
supported value is 1.0. To learn more, see exportVersion in the API Gateway Version 2 API Reference.
759
Amazon API Gateway Developer Guide
x-amazon-apigateway-importexport-version example
x-amazon-apigateway-importexport-version example
The following example sets the import and export version to 1.0.
{
"openapi": "3.0.1",
"x-amazon-apigateway-importexport-version": "1.0",
"info": { ...
x-amazon-apigateway-integration object
Specifies details of the backend integration used for this method. This extension is an extended property
of the OpenAPI Operation object. The result is an API Gateway integration object.
Properties
760
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration
761
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration
762
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration examples
x-amazon-apigateway-integration examples
For HTTP APIs, you can define integrations in the components section of your OpenAPI definition. To
learn more, see x-amazon-apigateway-integrations object (p. 764).
"x-amazon-apigateway-integration": {
"$ref": "#/components/x-amazon-apigateway-integrations/integration1"
}
The following example creates an integration with a Lambda function. 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>.
763
Amazon API Gateway Developer Guide
x-amazon-apigateway-integrations
"x-amazon-apigateway-integration" : {
"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-lambda-exec-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 (") for the JSON string in the mapping templates must be string-escaped (\").
x-amazon-apigateway-integrations object
Defines a collection of integrations. You can define integrations in the components section of your
OpenAPI definition, and reuse the integrations for multiple routes. Supported only for HTTP APIs.
764
Amazon API Gateway Developer Guide
x-amazon-apigateway-integrations example
Properties
x-amazon-apigateway-integrations example
The following example creates an HTTP API that defines two integrations, and references
the integrations by using $ref": "#/components/x-amazon-apigateway-
integrations/integration-name.
{
"openapi": "3.0.1",
"info":
{
"title": "Integrations",
"description": "An API that reuses integrations",
"version": "1.0"
},
"servers": [
{
"url": "https://example.com/{basePath}",
"description": "The production API server",
"variables":
{
"basePath":
{
"default": "example/path"
}
}
}],
"paths":
{
"/":
{
"get":
{
"x-amazon-apigateway-integration":
{
"$ref": "#/components/x-amazon-apigateway-integrations/integration1"
}
}
},
"/pets":
{
"get":
{
"x-amazon-apigateway-integration":
{
"$ref": "#/components/x-amazon-apigateway-integrations/integration1"
}
}
},
"/checkout":
{
"get":
{
"x-amazon-apigateway-integration":
765
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration.requestTemplates
{
"$ref": "#/components/x-amazon-apigateway-integrations/integration2"
}
}
}
},
"components": {
"x-amazon-apigateway-integrations":
{
"integration1":
{
"type": "aws_proxy",
"httpMethod": "POST",
"uri": "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-2:123456789012:function:my-function/invocations",
"passthroughBehavior": "when_no_templates",
"payloadFormatVersion": "1.0"
},
"integration2":
{
"type": "aws_proxy",
"httpMethod": "POST",
"uri": "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/
arn:aws:lambda:us-east-2:123456789012:function:example-function/invocations",
"passthroughBehavior": "when_no_templates",
"payloadFormatVersion" : "1.0"
}
}
}
}
x-amazon-apigateway-
integration.requestTemplates object
Specifies mapping templates for a request payload of the specified MIME types.
Properties
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.
766
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration.requestParameters
"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
For REST APIs, specifies mappings from named method request parameters to integration request
parameters. The method request parameters must be defined before being referenced.
For HTTP APIs, specifies parameters that are passed to AWS_PROXY integrations with a specified
integrationSubtype.
Properties
767
Amazon API Gateway Developer Guide
x-amazon-apigateway-
integration.requestParameters example
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.
Note
If you're creating resources through OpenAPI or AWS CloudFormation, static values should be
enclosed in single quotes.
To add this value from the console, enter application/json in the box, without quotation
marks.
"requestParameters" : {
"integration.request.querystring.stage" : "method.request.querystring.version",
"integration.request.header.x-userid" : "method.request.header.x-user-id",
"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
768
Amazon API Gateway Developer Guide
x-amazon-apigateway-
integration.responses example
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" : {
"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
769
Amazon API Gateway Developer Guide
x-amazon-apigateway-
integration.response example
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 backend. The response uses the
supplied mapping templates and returns the redirect URL from the integration response in the method's
Location header.
{
"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"
}
}
770
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration.responseTemplates
x-amazon-apigateway-
integration.responseTemplates object
Specifies mapping templates for a response payload of the specified MIME types.
Properties
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. You
can map header, body, or static values to the header type of the method response. Supported only for
REST APIs.
Properties
method.response.header.<param-
string The named parameter value can
name> be derived from the header and
body types of the integration
response parameters.
771
Amazon API Gateway Developer Guide
x-amazon-apigateway-
integration.responseParameters example
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.x-userid"
}
x-amazon-apigateway-integration.tlsConfig object
Specifies the TLS configuration for an integration.
Properties
772
Amazon API Gateway Developer Guide
x-amazon-apigateway-integration.tlsConfig examples
x-amazon-apigateway-integration.tlsConfig examples
The following OpenAPI 3.0 example enables insecureSkipVerification for a REST API HTTP proxy
integration.
"x-amazon-apigateway-integration": {
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"responses": {
default": {
"statusCode": "200"
}
},
"passthroughBehavior": "when_no_match",
"httpMethod": "ANY",
"tlsConfig" : {
"insecureSkipVerification" : true
}
"type": "http_proxy",
}
The following OpenAPI 3.0 example specifies a serverNameToVerify for an HTTP API private
integration.
"x-amazon-apigateway-integration" : {
"payloadFormatVersion" : "1.0",
"connectionId" : "abc123",
"type" : "http_proxy",
"httpMethod" : "ANY",
"uri" : "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-
balancer/50dc6c495c0c9188/0467ef3c8400ae65",
"connectionType" : "VPC_LINK",
"tlsConfig" : {
"serverNameToVerify" : "example.com"
}
}
x-amazon-apigateway-minimum-compression-size
Specifies the minimum compression size for a REST API. To enable compression, specify an integer
between 0 and 10485760. To learn more, see Enabling payload compression for an API (p. 544).
x-amazon-apigateway-minimum-compression-size
example
The following example specifies a minimum compression size of 5242880 bytes for a REST API.
"x-amazon-apigateway-minimum-compression-size": 5242880
x-amazon-apigateway-policy
Specifies a resource policy for a REST API. To learn more about resource policies, see Controlling access
to an API with API Gateway resource policies (p. 274). For resource policy examples, see API Gateway
resource policy examples (p. 285).
773
Amazon API Gateway Developer Guide
x-amazon-apigateway-policy example
x-amazon-apigateway-policy example
The following example specifies a resource policy for a REST API. The resource policy denies (blocks)
incoming traffic to an API from a specified source IP address block. On import, "execute-api:/*" is
converted to arn:aws:execute-api:region:account-id:api-id/*, using the current Region,
your AWS account ID, and the current REST API ID.
"x-amazon-apigateway-policy": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
]
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": [
"execute-api:/*"
],
"Condition" : {
"IpAddress": {
"aws:SourceIp": "192.0.2.0/24"
}
}
}
]
}
x-amazon-apigateway-request-validator property
Specifies a request validator, by referencing a request_validator_name of the x-amazon-apigateway-
request-validators object (p. 775) map, to enable request validation on the containing API or a method.
The value of this extension is a JSON string.
This extension can be specified at the API level or at the method level. The API-level validator applies to
all of the methods unless it is overridden by the method-level validator.
x-amazon-apigateway-request-validator
example
The following example applies the basic request validator at the API level while applying the
parameter-only request validator on the POST /validation request.
OpenAPI 2.0
{
"swagger": "2.0",
"x-amazon-apigateway-request-validators" : {
"basic" : {
"validateRequestBody" : true,
"validateRequestParameters" : true
774
Amazon API Gateway Developer Guide
x-amazon-apigateway-request-validators
},
"params-only" : {
"validateRequestBody" : false,
"validateRequestParameters" : true
}
},
"x-amazon-apigateway-request-validator" : "basic",
"paths": {
"/validation": {
"post": {
"x-amazon-apigateway-request-validator" : "params-only",
...
}
}
x-amazon-apigateway-request-validators object
Defines the supported request validators for the containing API as a map between a validator name and
the associated request validation rules. This extension applies to a REST API.
Properties
"basic" : {
"validateRequestBody" :
true,
"validateRequestParameters" :
true
},
x-amazon-apigateway-request-validators
example
The following example shows a set of request validators for an API as a map between a validator name
and the associated request validation rules.
OpenAPI 2.0
775
Amazon API Gateway Developer Guide
x-amazon-apigateway-request-validators.requestValidator
"swagger": "2.0",
...
"x-amazon-apigateway-request-validators" : {
"basic" : {
"validateRequestBody" : true,
"validateRequestParameters" : true
},
"params-only" : {
"validateRequestBody" : false,
"validateRequestParameters" : true
}
},
...
}
x-amazon-apigateway-request-
validators.requestValidator object
Specifies the validation rules of a request validator as part of the x-amazon-apigateway-request-
validators object (p. 775) map definition.
Properties
x-amazon-apigateway-request-
validators.requestValidator example
The following example shows a parameter-only request validator:
"params-only": {
"validateRequestBody" : false,
"validateRequestParameters" : true
}
x-amazon-apigateway-tag-value property
Specifies the value of an AWS tag for an HTTP API. You can use the x-amazon-apigateway-tag-
value property as part of the root-level OpenAPI tag object to specify AWS tags for an HTTP API. If you
specify a tag name without the x-amazon-apigateway-tag-value property, API Gateway creates a
tag with an empty string for a value.
To learn more about tagging, see Tagging your API Gateway resources (p. 806).
776
Amazon API Gateway Developer Guide
x-amazon-apigateway-tag-value example
Properties
x-amazon-apigateway-tag-value example
The following example specifies two tags for an HTTP API:
• "Owner": "Admin"
• "Prod": ""
"tags": [
{
"name": "Owner",
"x-amazon-apigateway-tag-value": "Admin"
},
{
"name": "Prod"
}
]
777
Amazon API Gateway Developer Guide
Data protection
Security is a shared responsibility between AWS and you. The shared responsibility model describes this
as security of the cloud and security in the cloud:
• Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in
the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors
regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To
learn about the compliance programs that apply to Amazon API Gateway;, see AWS services in scope
by compliance program.
• Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also
responsible for other factors including the sensitivity of your data, your company’s requirements, and
applicable laws and regulations.
This documentation helps you understand how to apply the shared responsibility model when using
API Gateway. The following topics show you how to configure API Gateway to meet your security and
compliance objectives. You also learn how to use other AWS services that help you to monitor and secure
your API Gateway resources.
Topics
• Data protection in Amazon API Gateway (p. 778)
• Identity and access management for Amazon API Gateway (p. 780)
• Logging and monitoring in Amazon API Gateway (p. 798)
• Compliance validation for Amazon API Gateway (p. 803)
• Resilience in Amazon API Gateway (p. 803)
• Infrastructure security in Amazon API Gateway (p. 803)
• Vulnerability analysis in Amazon API Gateway (p. 804)
• Security best practices in Amazon API Gateway (p. 804)
For data protection purposes, we recommend that you protect AWS account credentials and set up
individual user accounts with AWS Identity and Access Management (IAM). That way each user is given
only the permissions necessary to fulfill their job duties. We also recommend that you secure your data
in the following ways:
778
Amazon API Gateway Developer Guide
Data encryption
We strongly recommend that you never put confidential or sensitive information, such as your
customers' email addresses, into tags or free-form fields such as a Name field. This includes when you
work with API Gateway or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data
that you enter into tags or free-form fields used for names may be used for billing or diagnostic logs.
If you provide a URL to an external server, we strongly recommend that you do not include credentials
information in the URL to validate your request to that server.
For more information about data protection, see the AWS Shared Responsibility Model and GDPR blog
post on the AWS Security Blog.
For greater security, you can choose a minimum Transport Layer Security (TLS) protocol version to be
enforced for your API Gateway custom domain. You can choose either a TLS version 1.2 or TLS version
1.0 security policy. WebSocket APIs and HTTP APIs support only TLS 1.2. To learn more, see Choosing a
minimum TLS version for a custom domain in API Gateway (p. 523).
You can also set up a Amazon CloudFront distribution with a custom SSL certificate in your account and
use it with Regional APIs. You can then configure the security policy for the CloudFront distribution with
TLS 1.1 or higher based on your security and compliance requirements.
For more information about data protection, see Protecting your REST API (p. 630) and the AWS Shared
Responsibility Model and GDPR blog post on the AWS Security Blog.
779
Amazon API Gateway Developer Guide
Identity and access management
a connection from an on-premises network to Amazon VPC and access your private API over that
connection. In all cases, traffic to your private API uses secure connections and does not leave the
Amazon network; it is isolated from the public internet. To learn more, see the section called “Private
APIs” (p. 665).
Topics
• Audience (p. 780)
• Authenticating with identities (p. 780)
• Managing access using policies (p. 782)
• How Amazon API Gateway works with IAM (p. 784)
• Amazon API Gateway identity-based policy examples (p. 787)
• Amazon API Gateway resource-based policy examples (p. 793)
• Troubleshooting Amazon API Gateway identity and access (p. 793)
• Using service-linked roles for API Gateway (p. 795)
Audience
How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in
API Gateway.
Service user – If you use the API Gateway service to do your job, then your administrator provides you
with the credentials and permissions that you need. As you use more API Gateway features to do your
work, you might need additional permissions. Understanding how access is managed can help you
request the right permissions from your administrator. If you cannot access a feature in API Gateway, see
Troubleshooting Amazon API Gateway identity and access (p. 793).
Service administrator – If you're in charge of API Gateway resources at your company, you probably
have full access to API Gateway. It's your job to determine which API Gateway features and resources
your employees should access. You must then submit requests to your IAM administrator to change the
permissions of your service users. Review the information on this page to understand the basic concepts
of IAM. To learn more about how your company can use IAM with API Gateway, see How Amazon API
Gateway works with IAM (p. 784).
IAM administrator – If you're an IAM administrator, you might want to learn details about how you can
write policies to manage access to API Gateway. To view example API Gateway identity-based policies
that you can use in IAM, see Amazon API Gateway identity-based policy examples (p. 787).
780
Amazon API Gateway Developer Guide
Authenticating with identities
You must be authenticated (signed in to AWS) as the AWS account root user, an IAM user, or by assuming
an IAM role. You can also use your company's single sign-on authentication or even sign in using Google
or Facebook. In these cases, your administrator previously set up identity federation using IAM roles.
When you access AWS using credentials from another company, you are assuming a role indirectly.
To sign in directly to the AWS Management Console, use your password with your root user email
address or your IAM user name. You can access AWS programmatically using your root user or IAM
users access keys. AWS provides SDK and command line tools to cryptographically sign your request
using your credentials. If you don't use AWS tools, you must sign the request yourself. Do this using
Signature Version 4, a protocol for authenticating inbound API requests. For more information about
authenticating requests, see Signature Version 4 signing process in the AWS General Reference.
Regardless of the authentication method that you use, you might also be required to provide additional
security information. For example, AWS recommends that you use multi-factor authentication (MFA) to
increase the security of your account. To learn more, see Using multi-factor authentication (MFA) in AWS
in the IAM User Guide.
An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You
can use groups to specify permissions for multiple users at a time. Groups make permissions easier to
manage for large sets of users. For example, you could have a group named IAMAdmins and give that
group permissions to administer IAM resources.
Users are different from roles. A user is uniquely associated with one person or application, but a role
is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but
roles provide temporary credentials. To learn more, see When to create an IAM user (instead of a role) in
the IAM User Guide.
IAM roles
An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM
user, but is not associated with a specific person. You can temporarily assume an IAM role in the AWS
Management Console by switching roles. You can assume a role by calling an AWS CLI or AWS API
operation or by using a custom URL. For more information about methods for using roles, see Using IAM
roles in the IAM User Guide.
IAM roles with temporary credentials are useful in the following situations:
• Temporary IAM user permissions – An IAM user can assume an IAM role to temporarily take on
different permissions for a specific task.
781
Amazon API Gateway Developer Guide
Managing access using policies
• Federated user access – Instead of creating an IAM user, you can use existing identities from AWS
Directory Service, your enterprise user directory, or a web identity provider. These are known as
federated users. AWS assigns a role to a federated user when access is requested through an identity
provider. For more information about federated users, see Federated users and roles in the IAM User
Guide.
• Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different
account to access resources in your account. Roles are the primary way to grant cross-account access.
However, with some AWS services, you can attach a policy directly to a resource (instead of using a role
as a proxy). To learn the difference between roles and resource-based policies for cross-account access,
see How IAM roles differ from resource-based policies in the IAM User Guide.
• Cross-service access – Some AWS services use features in other AWS services. For example, when you
make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects
in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or
using a service-linked role.
• Principal permissions – When you use an IAM user or role to perform actions in AWS, you are
considered a principal. Policies grant permissions to a principal. When you use some services, you
might perform an action that then triggers another action in a different service. In this case, you
must have permissions to perform both actions. To see whether an action requires additional
dependent actions in a policy, see Actions, Resources, and Condition Keys for Amazon API Gateway
in the Service Authorization Reference.
• Service role – A service role is an IAM role that a service assumes to perform actions on your behalf.
An IAM administrator can create, modify, and delete a service role from within IAM. For more
information, see Creating a role to delegate permissions to an AWS service in the IAM User Guide.
• Service-linked role – A service-linked role is a type of service role that is linked to an AWS service.
The service can assume the role to perform an action on your behalf. Service-linked roles appear
in your IAM account and are owned by the service. An IAM administrator can view, but not edit the
permissions for service-linked roles.
• Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials
for applications that are running on an EC2 instance and making AWS CLI or AWS API requests.
This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2
instance and make it available to all of its applications, you create an instance profile that is attached
to the instance. An instance profile contains the role and enables programs that are running on the
EC2 instance to get temporary credentials. For more information, see Using an IAM role to grant
permissions to applications running on Amazon EC2 instances in the IAM User Guide.
To learn whether to use IAM roles or IAM users, see When to create an IAM role (instead of a user) in the
IAM User Guide.
Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can
perform actions on what resources, and under what conditions.
Every IAM entity (user or role) starts with no permissions. In other words, by default, users can
do nothing, not even change their own password. To give a user permission to do something, an
administrator must attach a permissions policy to a user. Or the administrator can add the user to a
782
Amazon API Gateway Developer Guide
Managing access using policies
group that has the intended permissions. When an administrator gives permissions to a group, all users
in that group are granted those permissions.
IAM policies define permissions for an action regardless of the method that you use to perform the
operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with
that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API.
Identity-based policies
Identity-based policies are JSON permissions policy documents that you can attach to an identity, such
as an IAM user, group of users, or role. These policies control what actions users and roles can perform,
on which resources, and under what conditions. To learn how to create an identity-based policy, see
Creating IAM policies in the IAM User Guide.
Identity-based policies can be further categorized as inline policies or managed policies. Inline policies
are embedded directly into a single user, group, or role. Managed policies are standalone policies that
you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS
managed policies and customer managed policies. To learn how to choose between a managed policy or
an inline policy, see Choosing between managed policies and inline policies in the IAM User Guide.
Resource-based policies
Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-
based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-
based policies, service administrators can use them to control access to a specific resource. For the
resource where the policy is attached, the policy defines what actions a specified principal can perform
on that resource and under what conditions. You must specify a principal in a resource-based policy.
Principals can include accounts, users, roles, federated users, or AWS services.
Resource-based policies are inline policies that are located in that service. You can't use AWS managed
policies from IAM in a resource-based policy.
Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about
ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide.
• Permissions boundaries – A permissions boundary is an advanced feature in which you set the
maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role).
You can set a permissions boundary for an entity. The resulting permissions are the intersection of
entity's identity-based policies and its permissions boundaries. Resource-based policies that specify
the user or role in the Principal field are not limited by the permissions boundary. An explicit deny
in any of these policies overrides the allow. For more information about permissions boundaries, see
Permissions boundaries for IAM entities in the IAM User Guide.
• Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for
an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for
grouping and centrally managing multiple AWS accounts that your business owns. If you enable all
features in an organization, then you can apply service control policies (SCPs) to any or all of your
783
Amazon API Gateway Developer Guide
How Amazon API Gateway works with IAM
accounts. The SCP limits permissions for entities in member accounts, including each AWS account
root user. For more information about Organizations and SCPs, see How SCPs work in the AWS
Organizations User Guide.
• Session policies – Session policies are advanced policies that you pass as a parameter when you
programmatically create a temporary session for a role or federated user. The resulting session's
permissions are the intersection of the user or role's identity-based policies and the session policies.
Permissions can also come from a resource-based policy. An explicit deny in any of these policies
overrides the allow. For more information, see Session policies in the IAM User Guide.
Topics
• API Gateway identity-based policies (p. 784)
• API Gateway resource-based policies (p. 787)
• Authorization based on API Gateway tags (p. 787)
• API Gateway IAM roles (p. 787)
The following example shows an identity-based policy that allows a user to create or update only private
REST APIs. For more examples, see the section called “Identity-based policy examples” (p. 787).
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ScopeToPrivateApis",
"Effect": "Allow",
"Action": [
"apigateway:PATCH",
"apigateway:POST",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis",
"arn:aws:apigateway:us-east-1::/restapis/??????????"
],
784
Amazon API Gateway Developer Guide
How Amazon API Gateway works with IAM
"Condition": {
"ForAllValues:StringEqualsIfExists": {
"apigateway:Request/EndpointType": "PRIVATE",
"apigateway:Resource/EndpointType": "PRIVATE"
}
}
},
{
"Sid": "AllowResourcePolicyUpdates",
"Effect": "Allow",
"Action": [
"apigateway:UpdateRestApiPolicy"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/*"
]
}
]
}
Actions
The Action element of a JSON policy describes the actions that you can use to allow or deny access in a
policy.
Policy actions in API Gateway use the following prefix before the action: apigateway:. Policy
statements must include either an Action or NotAction element. API Gateway defines its own set of
actions that describe tasks that you can perform with this service.
The API-managing Action expression has the format apigateway:action, where action is one of
the following API Gateway actions: GET, POST, PUT, DELETE, PATCH (to update resources), or *, which is
all of the previous actions.
To specify multiple actions in a single statement, separate them with commas as follows:
"Action": [
"apigateway:action1",
"apigateway:action2"
For information about HTTP verbs to use for specific API Gateway operations, see Amazon API Gateway
Version 1 API Reference (REST APIs) and Amazon API Gateway Version 2 API Reference (WebSocket and
HTTP APIs).
For more information, see the section called “Identity-based policy examples” (p. 787).
Resources
Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can
perform actions on what resources, and under what conditions.
The Resource JSON policy element specifies the object or objects to which the action applies.
Statements must include either a Resource or a NotResource element. As a best practice, specify
a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific
resource type, known as resource-level permissions.
785
Amazon API Gateway Developer Guide
How Amazon API Gateway works with IAM
For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to
indicate that the statement applies to all resources.
"Resource": "*"
arn:aws:apigateway:region::resource-path-specifier
For example, to specify a REST API with the id api-id and its sub-resources, such as authorizers in your
statement, use the following ARN:
"Resource": "arn:aws:apigateway:us-east-2::/restapis/api-id/*"
To specify all REST APIs and sub-resources that belong to a specific account, use the wildcard (*):
"Resource": "arn:aws:apigateway:us-east-2::/restapis/*"
For a list of API Gateway resource types and their ARNs, see API Gateway Amazon Resource Name (ARN)
reference (p. 739).
Condition keys
Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can
perform actions on what resources, and under what conditions.
The Condition element (or Condition block) lets you specify conditions in which a statement is in
effect. The Condition element is optional. You can create conditional expressions that use condition
operators, such as equals or less than, to match the condition in the policy with values in the request.
If you specify multiple Condition elements in a statement, or multiple keys in a single Condition
element, AWS evaluates them using a logical AND operation. If you specify multiple values for a single
condition key, AWS evaluates the condition using a logical OR operation. All of the conditions must be
met before the statement's permissions are granted.
You can also use placeholder variables when you specify conditions. For example, you can grant an IAM
user permission to access a resource only if it is tagged with their IAM user name. For more information,
see IAM policy elements: variables and tags in the IAM User Guide.
AWS supports global condition keys and service-specific condition keys. To see all AWS global condition
keys, see AWS global condition context keys in the IAM User Guide.
API Gateway defines its own set of condition keys and also supports using some global condition keys.
For a list of API Gateway condition keys, see Condition Keys for Amazon API Gateway in the IAM User
Guide. For information about which actions and resources you can use with a condition key, see Actions
Defined by Amazon API Gateway.
For information about tagging, including attribute-based access control, see Tagging (p. 806).
Examples
For examples of API Gateway identity-based policies, see Amazon API Gateway identity-based policy
examples (p. 787).
786
Amazon API Gateway Developer Guide
Identity-based policy examples
Examples
For examples of API Gateway resource-based policies, see API Gateway resource policy examples (p. 285).
For an examples of identity-based policies for limiting access to a resource based on the tags on that
resource, see Using tags to control access to API Gateway resources (p. 808).
Service-linked roles
Service-linked roles allow AWS services to access resources in other services to complete an action on
your behalf. Service-linked roles appear in your IAM account and are owned by the service. An IAM
administrator can view but not edit the permissions for service-linked roles.
API Gateway supports service-linked roles. For information about creating or managing API Gateway
service-linked roles, see Using service-linked roles for API Gateway (p. 795).
Service roles
A service can assume a service role on your behalf. A service role allows the service to access resources
in other services to complete an action on your behalf. Service roles appear in your IAM account and are
owned by the account, so an IAM administrator can change the permissions for this role. However, doing
so might break the functionality of the service.
787
Amazon API Gateway Developer Guide
Identity-based policy examples
administrator must create IAM policies that grant users and roles permission to perform specific API
operations on the specified resources they need. The administrator must then attach those policies to
the IAM users or groups that require those permissions.
For information about how to create IAM policies, see Creating Policies on the JSON Tab in the IAM
User Guide. For information about the actions, resources, and conditions specific to API Gateway, see
Actions, resources, and condition keys for Amazon API Gateway Management and Actions, resources, and
condition keys for Amazon API Gateway Management V2.
Topics
• Policy best practices (p. 788)
• Allow users to view their own permissions (p. 788)
• Simple read permissions (p. 789)
• Create only REQUEST or JWT authorizers (p. 789)
• Require that the default execute-api endpoint is disabled (p. 790)
• Allow users to create or update only private REST APIs (p. 791)
• Require that API routes have authorization (p. 792)
• Prevent a user from creating or updating a VPC link (p. 792)
• Get started using AWS managed policies – To start using API Gateway quickly, use AWS managed
policies to give your employees the permissions they need. These policies are already available in
your account and are maintained and updated by AWS. For more information, see Get started using
permissions with AWS managed policies in the IAM User Guide.
• Grant least privilege – When you create custom policies, grant only the permissions required
to perform a task. Start with a minimum set of permissions and grant additional permissions as
necessary. Doing so is more secure than starting with permissions that are too lenient and then trying
to tighten them later. For more information, see Grant least privilege in the IAM User Guide.
• Enable MFA for sensitive operations – For extra security, require IAM users to use multi-factor
authentication (MFA) to access sensitive resources or API operations. For more information, see Using
multi-factor authentication (MFA) in AWS in the IAM User Guide.
• Use policy conditions for extra security – To the extent that it's practical, define the conditions under
which your identity-based policies allow access to a resource. For example, you can write conditions to
specify a range of allowable IP addresses that a request must come from. You can also write conditions
to allow requests only within a specified date or time range, or to require the use of SSL or MFA. For
more information, see IAM JSON policy elements: Condition in the IAM User Guide.
{
"Version": "2012-10-17",
"Statement": [
{
788
Amazon API Gateway Developer Guide
Identity-based policy examples
"Sid": "ViewOwnUserInfo",
"Effect": "Allow",
"Action": [
"iam:GetUserPolicy",
"iam:ListGroupsForUser",
"iam:ListAttachedUserPolicies",
"iam:ListUserPolicies",
"iam:GetUser"
],
"Resource": ["arn:aws:iam::*:user/${aws:username}"]
},
{
"Sid": "NavigateInConsole",
"Effect": "Allow",
"Action": [
"iam:GetGroupPolicy",
"iam:GetPolicyVersion",
"iam:GetPolicy",
"iam:ListAttachedGroupPolicies",
"iam:ListGroupPolicies",
"iam:ListPolicyVersions",
"iam:ListPolicies",
"iam:ListUsers"
],
"Resource": "*"
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"apigateway:GET"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/apis/a123456789/*"
]
}
]
}
789
Amazon API Gateway Developer Guide
Identity-based policy examples
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OnlyAllowSomeAuthorizerTypes",
"Effect": "Allow",
"Action": [
"apigateway:PUT",
"apigateway:POST",
"apigateway:PATCH"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/apis",
"arn:aws:apigateway:us-east-1::/apis/??????????",
"arn:aws:apigateway:us-east-1::/apis/*/authorizers",
"arn:aws:apigateway:us-east-1::/apis/*/authorizers/*"
],
"Condition": {
"ForAllValues:StringEqualsIfExists": {
"apigateway:Request/AuthorizerType": [
"REQUEST",
"JWT"
]
}
}
}
]
}
We use the BoolIfExisits condition to handle a call to update an API that doesn't have the
DisableExecuteApiEndpoint condition key populated. When a user attempts to create or import an
API, the DisableExecuteApiEndpoint condition key is always populated.
Because the apis/* resource also captures sub resources such as authorizers or methods, we explicitly
scope it to just APIs with a Deny statement.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DisableExecuteApiEndpoint",
"Effect": "Allow",
"Action": [
"apigateway:PATCH",
"apigateway:POST",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/apis",
"arn:aws:apigateway:us-east-1::/apis/*"
],
"Condition": {
"BoolIfExists": {
"apigateway:Request/DisableExecuteApiEndpoint": true
}
}
},
{
790
Amazon API Gateway Developer Guide
Identity-based policy examples
"Sid": "ScopeDownToJustApis",
"Effect": "Deny",
"Action": [
"apigateway:PATCH",
"apigateway:POST",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/apis/*/*"
]
}
]
}
We use ForAllValues to require that every EndpointType added to an API is PRIVATE. We use a
resource condition key to allow any update to an API as long as it's PRIVATE. ForAllValues applies
only if a condition key is present. For create operations, a Resource condition key is not present. For
delete operations, a Request key is not present.
We use the non-greedy matcher (?) to explicitly match against API IDs to prevent allowing non-API
resources such as authorizers.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ScopeToPrivateApis",
"Effect": "Allow",
"Action": [
"apigateway:DELETE",
"apigateway:PATCH",
"apigateway:POST",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis",
"arn:aws:apigateway:us-east-1::/restapis/??????????"
],
"Condition": {
"ForAllValues:StringEqualsIfExists": {
"apigateway:Request/EndpointType": "PRIVATE",
"apigateway:Resource/EndpointType": "PRIVATE"
}
}
},
{
"Sid": "AllowResourcePolicyUpdates",
"Effect": "Allow",
"Action": [
"apigateway:UpdateRestApiPolicy"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/restapis/*"
]
}
]
}
791
Amazon API Gateway Developer Guide
Identity-based policy examples
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowUpdatesOnApisAndRoutes",
"Effect": "Allow",
"Action": [
"apigateway:POST",
"apigateway:PATCH",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/apis",
"arn:aws:apigateway:us-east-1::/apis/??????????",
"arn:aws:apigateway:us-east-1::/apis/*/routes",
"arn:aws:apigateway:us-east-1::/apis/*/routes/*"
]
},
{
"Sid": "DenyUnauthorizedRoutes",
"Effect": "Deny",
"Action": [
"apigateway:POST",
"apigateway:PATCH",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:us-east-1::/apis",
"arn:aws:apigateway:us-east-1::/apis/*"
],
"Condition": {
"ForAnyValue:StringEqualsIgnoreCase": {
"apigateway:Request/RouteAuthorizationType": "NONE"
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyVPCLink",
"Effect": "Deny",
"Action": [
"apigateway:POST",
"apigateway:PUT",
"apigateway:PATCH"
],
"Resource": [
792
Amazon API Gateway Developer Guide
Resource-based policy examples
"arn:aws:apigateway:us-east-1::/vpclinks",
"arn:aws:apigateway:us-east-1::/vpclinks/*"
]
}
]
}
Topics
• I am not authorized to perform an action in API Gateway (p. 793)
• I am not authorized to perform iam:PassRole (p. 793)
• I want to view my access keys (p. 794)
• I'm an administrator and want to allow others to access API Gateway (p. 794)
• I want to allow people outside of my AWS account to access my API Gateway resources (p. 794)
The following example error occurs when the mateojackson IAM user tries to use the console to view
details about an API but does not have apigateway:GET permissions.
In this case, Mateo asks his administrator to update his policies to allow him to access the API resource
using the apigateway:GET action.
Some AWS services allow you to pass an existing role to that service, instead of creating a new service
role or service-linked role. To do this, you must have permissions to pass the role to the service.
The following example error occurs when an IAM user named marymajor tries to use the console to
perform an action in API Gateway. However, the action requires the service to have permissions granted
by a service role. Mary does not have permissions to pass the role to the service.
793
Amazon API Gateway Developer Guide
Troubleshooting
In this case, Mary asks her administrator to update her policies to allow her to perform the
iam:PassRole action.
Access keys consist of two parts: an access key ID (for example, AKIAIOSFODNN7EXAMPLE) and a secret
access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY). Like a user name and
password, you must use both the access key ID and secret access key together to authenticate your
requests. Manage your access keys as securely as you do your user name and password.
Important
Do not provide your access keys to a third party, even to help find your canonical user ID. By
doing this, you might give someone permanent access to your account.
When you create an access key pair, you are prompted to save the access key ID and secret access key in
a secure location. The secret access key is available only at the time you create it. If you lose your secret
access key, you must add new access keys to your IAM user. You can have a maximum of two access keys.
If you already have two, you must delete one key pair before creating a new one. To view instructions,
see Managing access keys in the IAM User Guide.
To get started right away, see Creating your first IAM delegated user and group in the IAM User Guide.
• To learn whether API Gateway supports these features, see How Amazon API Gateway works with
IAM (p. 784).
• To learn how to provide access to your resources across AWS accounts that you own, see Providing
access to an IAM user in another AWS account that you own in the IAM User Guide.
• To learn how to provide access to your resources to third-party AWS accounts, see Providing access to
AWS accounts owned by third parties in the IAM User Guide.
• To learn how to provide access through identity federation, see Providing access to externally
authenticated users (identity federation) in the IAM User Guide.
• To learn the difference between using roles and resource-based policies for cross-account access, see
How IAM roles differ from resource-based policies in the IAM User Guide.
794
Amazon API Gateway Developer Guide
Using service-linked roles
A service-linked role makes setting up API Gateway easier because you don't have to manually add
the necessary permissions. API Gateway defines the permissions of its service-linked roles, and unless
defined otherwise, only API Gateway can assume its roles. The defined permissions include the trust
policy and the permissions policy, and that permissions policy cannot be attached to any other IAM
entity.
You can delete a service-linked role only after first deleting the related resources. This protects your API
Gateway resources because you can't inadvertently remove permission to access the resources.
For information about other services that support service-linked roles, see AWS Services That Work with
IAM and look for the services that have Yes in the Service-Linked Role column. Choose a Yes with a link
to view the service-linked role documentation for that service.
The AWSServiceRoleForAPIGateway service-linked role trusts the following services to assume the role:
• ops.apigateway.amazonaws.com
The role permissions policy allows API Gateway to complete the following actions on the specified
resources:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"elasticloadbalancing:AddListenerCertificates",
"elasticloadbalancing:RemoveListenerCertificates",
"elasticloadbalancing:ModifyListener",
"elasticloadbalancing:DescribeListeners",
"elasticloadbalancing:DescribeLoadBalancers",
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingTargets",
"xray:GetSamplingRules",
"logs:CreateLogDelivery",
"logs:GetLogDelivery",
"logs:UpdateLogDelivery",
"logs:DeleteLogDelivery",
"logs:ListLogDeliveries",
"servicediscovery:DiscoverInstances"
],
"Resource": [
"*"
]
},
795
Amazon API Gateway Developer Guide
Using service-linked roles
{
"Effect": "Allow",
"Action": [
"firehose:DescribeDeliveryStream",
"firehose:PutRecord",
"firehose:PutRecordBatch"
],
"Resource": "arn:aws:firehose:*:*:deliverystream/amazon-apigateway-*"
},
{
"Effect": "Allow",
"Action": [
"acm:DescribeCertificate",
"acm:GetCertificate"
],
"Resource": "arn:aws:acm:*:*:certificate/*"
},
{
"Effect": "Allow",
"Action": "ec2:CreateNetworkInterfacePermission",
"Resource": "arn:aws:ec2:*:*:network-interface/*"
},
{
"Effect": "Allow",
"Action": "ec2:CreateTags",
"Resource": "arn:aws:ec2:*:*:network-interface/*",
"Condition": {
"ForAllValues:StringEquals": {
"aws:TagKeys": [
"Owner",
"VpcLinkId"
]
}
}
},
{
"Effect": "Allow",
"Action": [
"ec2:ModifyNetworkInterfaceAttribute",
"ec2:DeleteNetworkInterface",
"ec2:AssignPrivateIpAddresses",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterfacePermission",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeAvailabilityZones",
"ec2:DescribeNetworkInterfaceAttribute",
"ec2:DescribeVpcs",
"ec2:DescribeNetworkInterfacePermissions",
"ec2:UnassignPrivateIpAddresses",
"ec2:DescribeSubnets",
"ec2:DescribeRouteTables",
"ec2:DescribeSecurityGroups"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "servicediscovery:GetNamespace",
"Resource": "arn:aws:servicediscovery:*:*:namespace/*"
},
{
"Effect": "Allow",
"Action": "servicediscovery:GetService",
"Resource": "arn:aws:servicediscovery:*:*:service/*"
}
]
796
Amazon API Gateway Developer Guide
Using service-linked roles
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or
delete a service-linked role. For more information, see Service-Linked Role Permissions in the IAM User
Guide.
If you delete this service-linked role, and then need to create it again, you can use the same process
to recreate the role in your account. When you create an API, custom domain name, or VPC link, API
Gateway creates the service-linked role for you again.
Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForAPIGateway service-
linked role. For more information, see Deleting a Service-Linked Role in the IAM User Guide.
797
Amazon API Gateway Developer Guide
Logging and monitoring
API Gateway started tracking API Gateway started tracking July 12, 2021
changes changes for its AWS managed
policies.
To help debug issues related to request execution or client access to your API, you can enable
CloudWatch Logs to log API calls. For more information, see the section called “CloudWatch
logs” (p. 678).
Amazon CloudWatch Alarms
Using CloudWatch alarms, you watch a single metric over a time period that you specify. If the
metric exceeds a given threshold, a notification is sent to an Amazon Simple Notification Service
topic or AWS Auto Scaling policy. CloudWatch alarms do not invoke actions when a metric is in a
particular state. Rather the state must have changed and been maintained for a specified number of
periods. For more information, see the section called “CloudWatch metrics” (p. 672).
Access Logging to Kinesis Data Firehose
To help debug issues related to client access to your API, you can enable Kinesis Data Firehose to log
API calls. For more information, see the section called “Kinesis Data Firehose” (p. 681).
AWS CloudTrail
CloudTrail provides a record of actions taken by a user, role, or an AWS service in API Gateway.
Using the information collected by CloudTrail, you can determine the request that was made to
API Gateway, the IP address from which the request was made, who made the request, when it
was made, and additional details. For more information, see the section called “Working with AWS
CloudTrail” (p. 799).
AWS X-Ray
X-Ray is an AWS service that gathers data about the requests that your application serves, and
uses it to construct a service map that you can use to identify issues with your application and
opportunities for optimization. For more information, see the section called “Setting up AWS X-
Ray” (p. 682).
AWS Config
AWS Config provides a detailed view of the configuration of AWS resources in your account. You
can see how resources are related, get a history of configuration changes, and see how relationships
and configurations change over time. You can use AWS Config to define rules that evaluate resource
configurations for data compliance. AWS Config rules represent the ideal configuration settings for
your API Gateway resources. If a resource violates a rule and is flagged as noncompliant, AWS Config
798
Amazon API Gateway Developer Guide
Working with AWS CloudTrail
can alert you using an Amazon Simple Notification Service (Amazon SNS) topic. For details, see the
section called “Working with AWS Config” (p. 800).
If you create a trail, you can enable continuous delivery of CloudTrail events to an Amazon S3 bucket,
including events for API Gateway. If you don't configure a trail, you can still view the most recent events
in the CloudTrail console in Event history.
Using the information collected by CloudTrail, you can determine the request that was made to API
Gateway, the IP address from which the request was made, who made the request, when it was made,
and additional details.
To learn more about CloudTrail, see the AWS CloudTrail User Guide.
For an ongoing record of events in your AWS account, including events for API Gateway, create a trail.
A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create a
trail in the console, the trail applies to all AWS Regions. The trail logs events from all Regions in the
AWS partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can
configure other AWS services to further analyze and act upon the event data collected in CloudTrail logs.
For more information, see:
All Amazon API Gateway actions are logged by CloudTrail and are documented in the API
references (p. 812). For example, calls to create a new API, resource, or method in API Gateway
generate entries in CloudTrail log files.
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
• Whether the request was made with root or IAM user credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
799
Amazon API Gateway Developer Guide
Working with AWS Config
The following example shows a CloudTrail log entry that demonstrates the API Gateway GetResource
action:
{
Records: [
{
eventVersion: "1.03",
userIdentity: {
type: "Root",
principalId: "AKIAI44QH8DHBEXAMPLE",
arn: "arn:aws:iam::123456789012:root",
accountId: "123456789012",
accessKeyId: "AKIAIOSFODNN7EXAMPLE",
sessionContext: {
attributes: {
mfaAuthenticated: "false",
creationDate: "2015-06-16T23:37:58Z"
}
}
},
eventTime: "2015-06-17T00:47:28Z",
eventSource: "apigateway.amazonaws.com",
eventName: "GetResource",
awsRegion: "us-east-1",
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 ...
]
}
800
Amazon API Gateway Developer Guide
Working with AWS Config
In addition, the AWS Config Rules feature enables you to define configuration rules and automatically
detect, track, and alert violations to these rules. By tracking changes to these resource configuration
properties, you can also author change-triggered AWS Config rules for your API Gateway resources, and
test your resource configurations against best practices.
You can enable AWS Config in your account by using the AWS Config console or the AWS CLI. Select the
resource types for which you want to track changes. If you previously configured AWS Config to record
all resource types, then these API Gateway resources will be automatically recorded in your account.
Support for Amazon API Gateway in AWS Config is available in all AWS public regions and AWS GovCloud
(US). For the full list of supported Regions, see Amazon API Gateway Endpoints and Quotas in the AWS
General Reference.
Topics
• Supported resource types (p. 801)
• Setting up AWS Config (p. 802)
• Configuring AWS Config to record API Gateway resources (p. 802)
• Viewing API Gateway configuration details in the AWS Config console (p. 802)
• Evaluating API Gateway resources using AWS Config rules (p. 802)
For more information about AWS Config, see the AWS Config Developer Guide. For pricing information,
see the AWS Config pricing information page.
Important
If you change any of the following API properties after the API is deployed, you must
redeploy (p. 490) the API to propagate the changes. Otherwise, you'll see the attribute changes
in the AWS Config console, but the previous property settings will still be in effect; the API's
runtime behavior will be unchanged.
801
Amazon API Gateway Developer Guide
Working with AWS Config
• AWS::ApiGatewayV2::Api – apiKeySelectionExpression
To learn about regional vs. global resources and learn how to customize your AWS Config configuration,
see Selecting which Resources AWS Config Records.
To learn more ways to find a resource and view information on this page, see Viewing AWS Resource
Configurations and History in the AWS Config Developer Guide.
If a resource violates a rule and is flagged as noncompliant, AWS Config can alert you using an Amazon
Simple Notification Service Developer Guide (Amazon SNS) topic. To programmatically consume the
data in these AWS Config alerts, use an Amazon Simple Queue Service (Amazon SQS) queue as the
notification endpoint for the Amazon SNS topic.
802
Amazon API Gateway Developer Guide
Compliance validation
To learn more about setting up and using rules, see Evaluating Resources with Rules in the AWS Config
Developer Guide.
For a list of AWS services in scope of specific compliance programs, see AWS Services in Scope by
Compliance Program. For general information, see AWS Compliance Programs.
You can download third-party audit reports using AWS Artifact. For more information, see Downloading
Reports in AWS Artifact.
Your compliance responsibility when using API Gateway is determined by the sensitivity of your data,
your company's compliance objectives, and applicable laws and regulations. AWS provides the following
resources to help with compliance:
• Security and Compliance Quick Start Guides – These deployment guides discuss architectural
considerations and provide steps for deploying security- and compliance-focused baseline
environments on AWS.
• Architecting for HIPAA Security and Compliance Whitepaper – This whitepaper describes how
companies can use AWS to create HIPAA-compliant applications.
• AWS Compliance Resources – This collection of workbooks and guides might apply to your industry
and location.
• Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses
how well your resource configurations comply with internal practices, industry guidelines, and
regulations.
• AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS
that helps you check your compliance with security industry standards and best practices.
For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.
To prevent your APIs from being overwhelmed by too many requests, API Gateway throttles requests to
your APIs. Specifically, API Gateway sets a limit on a steady-state rate and a burst of request submissions
against all APIs in your account. You can configure custom throttling for your APIs. To learn more, see
Throttle API requests for better throughput (p. 663).
803
Amazon API Gateway Developer Guide
Configuration and vulnerability analysis
You use AWS published API calls to access API Gateway through the network. Clients must support
Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. Clients must also support
cipher suites with perfect forward secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve
Ephemeral Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support these modes.
Additionally, requests must be signed by using an access key ID and a secret access key that is associated
with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary
security credentials to sign requests.
You can call these API operations from any network location, but API Gateway does support resource-
based access policies, which can include restrictions based on the source IP address. You can also use
resource-based policies to control access from specific Amazon Virtual Private Cloud (Amazon VPC)
endpoints or specific VPCs. Effectively, this isolates network access to a given API Gateway resource from
only the specific VPC within the AWS network.
Use IAM policies to implement least privilege access for creating, reading, updating, or deleting
API Gateway APIs. To learn more, see Identity and access management for Amazon API
Gateway (p. 780). API Gateway offers several options to control access to APIs that you create. To
learn more, see Controlling and managing access to a REST API in API Gateway (p. 273), Controlling
and managing access to a WebSocket API in API Gateway (p. 708), and Controlling access to HTTP
APIs with JWT authorizers (p. 195).
Implement logging
Use CloudWatch Logs or Amazon Kinesis Data Firehose to log requests to your APIs. To learn
more, see Monitoring REST APIs (p. 672), Configuring logging for a WebSocket API (p. 735), and
Configuring logging for an HTTP API (p. 233).
Implement Amazon CloudWatch alarms
Using CloudWatch alarms, you watch a single metric over a time period that you specify. If the
metric exceeds a given threshold, a notification is sent to an Amazon Simple Notification Service
topic or AWS Auto Scaling policy. CloudWatch alarms do not invoke actions when a metric is in a
particular state. Rather, the state must have changed and been maintained for a specified number of
periods. For more information, see the section called “CloudWatch metrics” (p. 672).
Enable AWS CloudTrail
CloudTrail provides a record of actions taken by a user, role, or an AWS service in API Gateway.
Using the information collected by CloudTrail, you can determine the request that was made to
API Gateway, the IP address from which the request was made, who made the request, when it
was made, and additional details. For more information, see the section called “Working with AWS
CloudTrail” (p. 799).
804
Amazon API Gateway Developer Guide
Best practices
AWS Config provides a detailed view of the configuration of AWS resources in your account. You
can see how resources are related, get a history of configuration changes, and see how relationships
and configurations change over time. You can use AWS Config to define rules that evaluate resource
configurations for data compliance. AWS Config rules represent the ideal configuration settings for
your API Gateway resources. If a resource violates a rule and is flagged as noncompliant, AWS Config
can alert you using an Amazon Simple Notification Service (Amazon SNS) topic. For details, see the
section called “Working with AWS Config” (p. 800).
805
Amazon API Gateway Developer Guide
API Gateway resources that can be tagged
• A tag key (for example, CostCenter, Environment, or Project). Tag keys are case sensitive.
• An optional field known as a tag value (for example, 111122223333 or Production). Omitting the
tag value is the same as using an empty string. Like tag keys, tag values are case-sensitive.
• Control access to your resources based on the tags that are assigned to them. You control access by
specifying tag keys and values in the conditions for an AWS Identity and Access Management (IAM)
policy. For more information about tag-based access control, see Controlling Access Using Tags in the
IAM User Guide.
• Track your AWS costs. You activate these tags on the AWS Billing and Cost Management dashboard.
AWS uses the tags to categorize your costs and deliver a monthly cost allocation report to you. For
more information, see Use Cost Allocation Tags in the AWS Billing and Cost Management User Guide.
• Identify and organize your AWS resources. Many AWS services support tagging, so you can assign the
same tag to resources from different services to indicate that the resources are related. For example,
you could assign the same tag to an API Gateway stage that you assign to a CloudWatch Events rule.
For tips on using tags, see the AWS Tagging Strategies post on the AWS Answers blog.
The following sections provide more information about tags for Amazon API Gateway.
Topics
• API Gateway resources that can be tagged (p. 806)
• Using tags to control access to API Gateway resources (p. 808)
• Api
• DomainName
• Stage
• VpcLink
In addition, tags can be set on the following REST API resources in the Amazon API Gateway V1 API:
• ApiKey
• ClientCertificate
• DomainName
806
Amazon API Gateway Developer Guide
Tag inheritance in the Amazon API Gateway V1 API
• RestApi
• Stage
• UsagePlan
• VpcLink
Tags cannot be set directly on other resources. However, in the Amazon API Gateway V1 API, child
resources inherit the tags that are set on parent resources. For example:
• If a tag is set on a RestApi resource, that tag is inherited by the following child resources of that
RestApi for Attribute-based access control:
• Authorizer
• Deployment
• Documentation
• GatewayResponse
• Integration
• Method
• Model
• Resource
• ResourcePolicy
• Setting
• Stage
• If a tag is set on a DomainName, that tag is inherited by any BasePathMapping resources under it.
• If a tag is set on a UsagePlan, that tag is inherited by any UsagePlanKey resources under it.
Note
Tag inheritance applies only to attribute-based access control. For example, you can't use
inherited tags to monitor costs in AWS Cost Explorer. API Gateway doesn't return inherited tags
when you call GetTags for a resource.
If a stage receives a tag both ways, the tag that was set directly on the stage takes precedence. For
example, suppose a stage inherits the following tags from its parent REST API:
{
'foo': 'bar',
'x':'y'
}
{
'foo': 'bar2',
'hello': 'world'
807
Amazon API Gateway Developer Guide
Tag restrictions and usage conventions
The net effect would be for the stage to have the following tags, with the following values:
{
'foo': 'bar2',
'hello': 'world'
'x':'y'
}
• Which users can perform actions on an API Gateway resource, based on tags that the resource already
has.
• Which tags can be passed in an action's request.
• Whether specific tag keys can be used in a request.
Using tags for attribute-based access control can allow for finer control than API-level control, as well
as more dynamic control than resource-based access control. IAM policies can be created that allow or
disallow an operation based on tags provided in the request (request tags), or tags on the resource that is
being operated on (resource tags). In general, resource tags are for resources that already exist. Request
tags are for when you're creating new resources.
For the complete syntax and semantics of tag condition keys, see Controlling Access Using Tags in the
IAM User Guide.
The following examples demonstrate how to specify tag conditions in policies for API Gateway users.
808
Amazon API Gateway Developer Guide
Example 1: Limit actions based on resource tags
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "apigateway:GET",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "apigateway:*",
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/iamrole": "readWrite"
}
}
}
]
}
• When the user creates a new stage, the request to create the stage must contain a tag named stage.
• The value of the stage tag must be beta, gamma, or prod. Otherwise, the request to create the stage
is denied.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"apigateway:*"
],
"Resource": [
"*"
]
},
{
"Effect": "Deny",
"Action": "apigateway:POST",
"Resource": "arn:aws:apigateway:*::/restapis/*/stages",
"Condition": {
"Null": {
"aws:RequestTag/stage": "true"
}
}
},
{
"Effect": "Deny",
809
Amazon API Gateway Developer Guide
Example 3: Deny actions based on resource tags
"Action": "apigateway:POST",
"Resource": "arn:aws:apigateway:*::/restapis/*/stages",
"Condition": {
"ForAnyValue:StringNotEquals": {
"aws:RequestTag/stage": [
"beta",
"gamma",
"prod"
]
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "apigateway:*",
"Resource": "*"
},
{
"Effect": "Deny",
"Action": [
"apigateway:PATCH",
"apigateway:PUT",
"apigateway:POST",
"apigateway:DELETE"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/stage": "prod"
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "apigateway:*",
"Resource": "*"
810
Amazon API Gateway Developer Guide
Example 5: Allow actions based on resource tag keys
},
{
"Effect": "Deny",
"Action": [
"apigateway:*"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/environment": "prod"
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "apigateway:*",
"Resource": "*"
},
{
"Effect": "Deny",
"Action": [
"apigateway:PATCH",
"apigateway:PUT",
"apigateway:POST",
"apigateway:DELETE"
],
"Resource": "*",
"Condition": {
"Null": {
"aws:ResourceTag/prod": "false"
}
}
}
]
}
811
Amazon API Gateway Developer Guide
API references
Amazon API Gateway provides APIs for creating and deploying your own HTTP and WebSocket APIs. In
addition, API Gateway APIs are available in standard AWS SDKs.
If you are using a language for which an AWS SDK exists, you may prefer to use the SDK rather than
using the API Gateway REST APIs directly. The SDKs make authentication simpler, integrate easily with
your development environment, and provide easy access to API Gateway commands.
Here's where to find the AWS SDKs and API Gateway REST API reference documentation:
812
Amazon API Gateway Developer Guide
API Gateway account-level quotas, per Region
Unless noted otherwise, the quotas can be increased upon request. To request a quota increase, you can
use Service Quotas or contact the AWS Support Center.
When authorization is enabled on a method, the maximum length of the method's ARN (for example,
arn:aws:execute-api:{region-id}:{account-id}:{api-id}/{stage-id}/{method}/
{resource}/{path}) is 1600 bytes. The path parameter values (whose size is determined at runtime)
can cause the ARN length to exceed the limit. When this happens, the API client receives a 414 Request
URI too long response.
Note
This limits URI length when resource policies are used. In the case of private APIs where a
resource policy is required, this limits the URI length of all private APIs.
Throttle quota 10,000 requests per second (RPS) with an additional burst capacity Yes
per account, per provided by the token bucket algorithm, using a maximum bucket
Region across HTTP capacity of 5,000 requests. *
APIs, REST APIs,
Note
WebSocket APIs, and
The burst quota is determined by the API Gateway service
WebSocket callback
team based on the overall RPS quota for the account in
APIs
the Region. It is not a quota that a customer can control or
request changes to.
813
Amazon API Gateway Developer Guide
HTTP API quotas
* For the Africa (Cape Town) and Europe (Milan) Regions, the default throttle quota is 2500 RPS and the
default burst quota is 1250 RPS.
Maximum 30 seconds No
integration timeout
Payload size 10 MB No
Amazon CloudWatch 1 MB No
Logs log entry
Audiences per 50 No
authorizer
814
Amazon API Gateway Developer Guide
API Gateway quotas for configuring
and running a WebSocket API
AWS Lambda 8 KB No
authorizer result size
WebSocket frame 32 KB No
size
* API Gateway doesn't enforce a quota on concurrent connections. The maximum number of concurrent
connections is determined by the rate of new connections per second and maximum connection duration
of two hours. For example, with the default quota of 500 new connections per second, if clients connect
at the maximum rate over two hours, API Gateway can serve up to 3,600,000 concurrent connections.
** Because of the WebSocket frame-size quota of 32 KB, a message larger than 32 KB must be split
into multiple frames, each 32 KB or smaller. If a larger message (or larger frame size) is received, the
connection is closed with code 1009.
815
Amazon API Gateway Developer Guide
API Gateway quotas for configuring
and running a REST API
Length, in 8192 No
characters, of the
URL for an edge-
optimized API
Length, in 10240 No
characters, of the
URL for a regional
API
Length, in 64 No
characters, of the
key in a stage
variable
Length, in 512 No
characters, of the
816
Amazon API Gateway Developer Guide
API Gateway quotas for configuring
and running a REST API
API caching TTL 300 seconds by default and configurable between 0 and 3600 by an Not
API owner. for the
upper
bound
(3600)
Cached response size 1048576 Bytes. Cache data encryption may increase the size of the No
item that is being cached.
Integration timeout 50 milliseconds - 29 seconds for all integration types, including Not for
Lambda, Lambda proxy, HTTP, HTTP proxy, and AWS integrations. the lower
or upper
bounds.
Payload size 10 MB No
Method-level 20 Yes
throttling settings
for a stage in a usage
plan
For restapi:import or restapi:put, the maximum size of the API definition file is 6 MB.
817
Amazon API Gateway Developer Guide
API Gateway quotas for creating,
deploying and managing an API
Edge-optimized API
818
Amazon API Gateway Developer Guide
Important notes
Edge-optimized API
819
Amazon API Gateway Developer Guide
Important notes for WebSocket APIs
names, including API name, label (stage) name, and resource name. When choosing these names, be
careful not to exceed CloudWatch Metrics limits.
• The maximum size of a mapping template is 300 KB.
"elementId": {
"description": "Working Element Id",
"format": "int32",
"type": "number"
}
• Decimal number format type ("format": "decimal") is not supported in a schema definition.
• In method responses, schema definition must be of an object type and cannot be of primitive types.
For example, "schema": { "type": "string"} is not supported. However, you can work around
this using the following object type:
"schema": {
"$ref": "#/definitions/StringResponse"
}
"definitions": {
"StringResponse": {
"type": "string"
}
}
• API Gateway doesn't use root level security defined in the OpenAPI specification. Hence security
needs to be defined at an operation level to be appropriately applied.
• The default keyword is not supported.
• API Gateway enacts the following restrictions and limitations when handling methods with either
Lambda integration or HTTP integration.
• Header names and query parameters are processed in a case-sensitive way.
• The following table lists the headers that may be dropped, remapped, or otherwise modified when
sent to your integration endpoint or sent back by your integration endpoint. In this table:
• Remapped means that the header name is changed from <string> to X-Amzn-
Remapped-<string>.
Remapped Overwritten means that the header name is changed from <string> to X-Amzn-
Remapped-<string> and the value is overwritten.
TE Dropped Dropped
822
Amazon API Gateway Developer Guide
Important notes for REST APIs
• The Android SDK of an API generated by API Gateway uses the java.net.HttpURLConnection
class. This class will throw an unhandled exception, on devices running Android 4.4 and earlier, for a
401 response resulted from remapping of the WWW-Authenticate header to X-Amzn-Remapped-
WWW-Authenticate.
• Unlike API Gateway-generated Java, Android and iOS SDKs of an API, the JavaScript SDK of an API
generated by API Gateway does not support retries for 500-level errors.
• The test invocation of a method uses the default content type of application/json and ignores
specifications of any other content types.
• When sending requests to an API by passing the X-HTTP-Method-Override header, API Gateway
overrides the method. So in order to pass the header to the backend, the header needs to be added to
the integration request.
• When a request contains multiple media types in its Accept header, API Gateway only honors the first
Accept media type. In the situation where you cannot control the order of the Accept media types
and the media type of your binary content is not the first in the list, you can add the first Accept
media type in the binaryMediaTypes list of your API, API Gateway will return your content as
binary. For example, to send a JPEG file using an <img> element in a browser, the browser might
send Accept:image/webp,image/*,*/*;q=0.8 in a request. By adding image/webp to the
binaryMediaTypes list, the endpoint will receive the JPEG file as binary.
• Customizing the default gateway response for 413 REQUEST_TOO_LARGE isn't currently supported.
823
Amazon API Gateway Developer Guide
Document history
The following table describes the important changes to the documentation since the last release of
Amazon API Gateway. For notification about updates to this documentation, you can subscribe to an RSS
feed by choosing the RSS button in the top menu panel.
Parameter mapping for HTTP Added support for parameter January 7, 2021
APIs (p. 824) mapping for HTTP APIs.
For more information, see
Transforming API requests and
responses.
Disable the default endpoint for Added support for disabling October 29, 2020
a REST API (p. 824) the default endpoint for REST
APIs. For more information, see
Disabling the default endpoint
for a REST API.
HTTP API AWS Lambda Added support for AWS Lambda September 9, 2020
authorizers (p. 824) authorizers for HTTP APIs. For
more information, see Working
with AWS Lambda authorizers
for HTTP APIs.
HTTP API AWS service Added support for AWS service August 20, 2020
integrations (p. 824) integrations for HTTP APIs. For
more information, see Working
with AWS service integrations
for HTTP APIs.
HTTP API wildcard custom Added support for wildcard August 10, 2020
domains (p. 824) custom domain names for HTTP
APIs. For more information, see
Wildcard custom domain names.
824
Amazon API Gateway Developer Guide
Serverless developer portal Added user management to the June 25, 2020
improvements (p. 824) administrator panel and support
for exporting API definitions. For
more information, see Use the
serverless developer portal to
catalog your API Gateway APIs.
WebSocket API Sec- Added support for the Sec- June 16, 2020
WebSocket-Protocol WebSocket-Protocol field.
support (p. 824) For more information, see
Setting up a $connect route
that requires a WebSocket
subprotocol.
HTTP API export (p. 824) Added support for exporting April 20, 2020
OpenAPI 3.0 definitions of HTTP
APIs. For more information, see
Exporting an HTTP API from API
Gateway.
HTTP API logging (p. 824) Added support for February 26, 2020
$context.integrationErrorMessage
in HTTP API logs. For more
information, see HTTP API
Logging Variables.
AWS variables for OpenAPI Added support for AWS variables February 17, 2020
import (p. 824) in OpenAPI definitions. For more
information, see AWS Variables
for OpenAPI Import.
HTTP APIs (p. 824) Released HTTP APIs in beta. For December 4, 2019
more information, see HTTP
APIs.
Wildcard custom domain Added support for wildcard October 21, 2019
names (p. 824) custom domain names. For
more information, see Wildcard
Custom Domain Names.
Amazon Kinesis Data Firehose Added support for Amazon October 15, 2019
logging (p. 824) Kinesis Data Firehose as a
destination for access logging
data. For more information,
see Using Amazon Kinesis Data
Firehose as a Destination for API
Gateway Access Logging.
825
Amazon API Gateway Developer Guide
Route53 aliases for invoking Added support for additional September 18, 2019
private APIs (p. 824) Route53 alias DNS records for
invoking private APIs. For more
information, see Accessing Your
Private API Using Route53 Alias.
Tag-based access control for Added support for tag-based June 27, 2019
WebSocket APIs (p. 824) access control for WebSocket
APIs. For more information, see
API Gateway Resources That Can
Be Tagged.
TLS version selection for custom Added support for Transport June 20, 2019
domains (p. 824) Layer Security (TLS) version
selection for APIs that are
deployed to custom domains.
See the note in Choose a
Minimum TLS Version for a
Custom Domain in API Gateway.
VPC endpoint policies for private Added support for improving June 4, 2019
APIs (p. 824) the security of private APIs by
attaching endpoint policies to
interface VPC endpoints. For
more information, see Use VPC
Endpoint Policies for Private
APIs in API Gateway.
Tag-based access control for Added support for tag-based May 23, 2019
REST APIs (p. 824) access control for REST APIs.
For more information, see
Using Tags with IAM Policies to
Control Access to API Gateway
Resources.
826
Amazon API Gateway Developer Guide
Serverless developer portal Added administrator panel and March 28, 2019
improvements (p. 824) other improvements to make
it easier to publish APIs in the
Amazon API Gateway developer
portal. For more information,
see Use a Developer Portal to
Catalog Your APIs.
Support for AWS Added support for AWS Config. March 20, 2019
Config (p. 824) For more information, see
Monitoring API Gateway API
Configuration with AWS Config.
Support for WebSocket Added support for WebSocket December 18, 2018
APIs (p. 824) APIs. For more information, see
Creating a WebSocket API in
Amazon API Gateway.
Serverless developer portal The Amazon API Gateway November 16, 2018
available through AWS developer portal serverless
Serverless Application application is now available from
Repository (p. 824) the AWS Serverless Application
Repository (in addition to
GitHub). For more information,
see Use a Developer Portal to
Catalog Your API Gateway APIs.
Support for AWS WAF (p. 824) Added support for AWS WAF November 5, 2018
(Web Application Firewall). For
more information, see Control
Access to an API Using AWS
WAF.
827
Amazon API Gateway Developer Guide
OpenAPI support (p. 824) Amazon API Gateway now September 27, 2018
supports OpenAPI 3.0 as well as
OpenAPI (Swagger) 2.0.
Active AWS X-Ray You can now use AWS X-Ray September 6, 2018
integration (p. 824) to trace and analyze latencies
in user requests as they travel
through your APIs to the
underlying services. For more
information, see Trace API
Gateway API Execution with AWS
X-Ray.
Caching improvements (p. 824) Only GET methods will have August 20, 2018
caching enabled by default
when you enable caching for an
API stage. This helps to ensure
the safety of your API. You
can enable caching for other
methods by overriding method
settings. For more information,
see Enable API Caching to
Enhance Responsiveness.
Service limits revised (p. 824) Several limits have been revised: July 13, 2018
Increased number of APIs per
account. Increased API rate limits
for Create/Import/Deploy APIs.
Corrected some rates from per
minute to per second. For more
information, see Limits.
Overriding API request and Added support for overriding July 12, 2018
response parameters and request headers, query strings,
headers (p. 824) and paths, as well as response
headers and status codes. For
more information, see Use a
Mapping Template to Override
an API's Request and Response
Parameters and Headers.
Method-level throttling for Added support for setting July 11, 2018
usage plans (p. 824) default per-method throttling
limits, as well as setting
throttling limits for individual
API methods in usage plan
settings. These settings are
in addition to the existing
account-level throttling and
default method-level throttling
limits that you can set in stage
settings. For more information,
see Throttle API Requests for
Better Throughput.
828
Amazon API Gateway Developer Guide
Earlier updates
API Gateway Developer Guide The HTML version of the API June 27, 2018
update notifications now Gateway Developer Guide now
available through RSS (p. 824) supports an RSS feed of updates
that are documented on this
Document History page. The
RSS feed includes updates
made June 27, 2018, and later.
Previously announced updates
are still available on this page.
Use the RSS button in the top
menu panel to subscribe to the
feed.
Earlier updates
The following table describes important changes in each release of the API Gateway Developer Guide
before June 27, 2018.
Private APIs Added support for private APIs (p. 665), which you expose June 14,
via interface VPC endpoints. Traffic to your private APIs does 2018
not leave the Amazon network; it is isolated from the public
internet.
Cross-Account Use an AWS Lambda function from a different AWS account April 2, 2018
Lambda Authorizers as a Lambda authorizer function or as an API integration
and Integrations backend. Or use an Amazon Cognito user pool as an
and Cross-Account authorizer. The other account can be in any region where
Amazon Cognito User Amazon API Gateway is available. For more information,
Pool Authorizers see the section called “Configure a cross-account Lambda
authorizer” (p. 313), the section called “Tutorial: Build an API
with cross-account Lambda proxy integration” (p. 36), and
the section called “Configure cross-account Amazon Cognito
authorizer for a REST API” (p. 322).
Resource Policies for Use API Gateway resource policies to enable users from a April 2, 2018
APIs different AWS account to securely access your API or to allow
the API to be invoked only from specified source IP address
ranges or CIDR blocks. For more information, see the section
called “Use API Gateway resource policies” (p. 274).
Tagging for API Tag an API stage with up to 50 tags for cost allocation of API December 19,
Gateway resources requests and caching in API Gateway. For more information 2017
see the section called “Set up tags” (p. 497).
Payload compression Enable calling your API with compressed payloads using December 19,
and decompression one of the supported content codings. The compressed 2017
payloads are subject to mapping if a body-mapping template
is specified. For more information, see the section called
“Content encoding” (p. 544).
API key sourced from Return an API key from a custom authorizer to API Gateway to December 19,
a custom authorizer apply a usage plan for API methods that require the key. For 2017
829
Amazon API Gateway Developer Guide
Earlier updates
Authorization with Enable authorization of method invocation by using OAuth 2 December 14,
OAuth 2 scopes scopes with the COGNITO_USER_POOLS authorizer. For more 2017
information, see the section called “Use Amazon Cognito user
pool as authorizer for a REST API” (p. 315).
Private Integration Create an API with the API Gateway private integration to November 30,
and VPC Link provide clients with access to HTTP/HTTPS resources in an 2017
Amazon VPC from outside of the VPC through a VpcLink
resource. For more information, see the section called
“Tutorial: Build an API with private integration” (p. 87) and the
section called “Private integration” (p. 354).
Deploy a Canary for Add a canary release to an existing API deployment to test November 28,
API testing a newer version of the API while keeping the current version 2017
in operation on the same stage. You can set a percentage of
stage traffic for the canary release and enable canary-specific
execution and access logged in separate CloudWatch Logs
logs. For more information, see the section called “Set up a
canary release deployment” (p. 507).
Access Logging Log client access to your API with data derived from $context November 21,
variables (p. 410) in a format of your choosing. For more 2017
information, see the section called “CloudWatch logs” (p. 678).
Ruby SDK of an API Generate a Ruby SDK for your API and use it to invoke your November 20,
API methods. For more information, see the section called 2017
“Generate the Ruby SDK of an API” (p. 607) and the section
called “Use a Ruby SDK generated by API Gateway for a REST
API” (p. 467).
Regional API Specify a regional API endpoint to create an API for non- November 2,
endpoint mobile clients. A non-mobile client, such as an EC2 instance, 2017
runs in the same AWS Region where the API is deployed. As
with an edge-optimized API, you can create a custom domain
name for a regional API. For more information, see the section
called “Set up a regional API” (p. 259) and the section called
“Setting up a regional custom domain name” (p. 531).
830
Amazon API Gateway Developer Guide
Earlier updates
Mapping Lambda Map individual custom error properties returned from June 6, 2017
custom error Lambda to the method response header parameters using
properties to method the integration.response.body parameter, relying API
response headers Gateway to deserialize the stringified custom error object at
run time. For more information, see Handle custom Lambda
errors in API Gateway (p. 348).
Throttling limits Increase the account-level steady-state request rate limit to June 6, 2017
increase 10,000 requests per second (rps) and the bust limit to 5000
concurrent requests. For more information, see Throttle API
requests for better throughput (p. 663).
Validating method Configure basic request validators on the API level or method April 11,
requests levels so that API Gateway can validate incoming requests. 2017
API Gateway verifies that required parameters are set and
not blank, and verifies that the format of applicable payloads
conforms to the configured model. For more information, see
Enable request validation in API Gateway (p. 364).
Integrating with ACM Use ACM Certificates for your API's custom domain names. You March 9,
can create a certificate in AWS Certificate Manager or import 2017
an existing PEM-formatted certificate into ACM. You then refer
to the certificate's ARN when setting a custom domain name
for your APIs. For more information, see Setting up custom
domain names for REST APIs (p. 518).
Generating and Let API Gateway generate the Java SDK for your API and January 13,
calling a Java SDK of use the SDK to call the API in your Java client. For more 2017
an API information, see Use a Java SDK generated by API Gateway for
a REST API (p. 460).
Integrating with AWS Sell your API in a usage plan as a SaaS product through AWS December 1,
Marketplace Marketplace. Use AWS Marketplace to extend the reach of 2016
your API. Rely on AWS Marketplace for customer billing on
your behalf. Let API Gateway handle user authorization and
usage metering. For more information, see Sell your APIs as
SaaS (p. 627).
Updated custom A customer authorizer Lambda function now returns the December 1,
authorizer caller's principal identifier. The function also can return other 2016
information as key-value pairs of the context map and an
IAM policy. For more information, see Output from an Amazon
API Gateway Lambda authorizer (p. 309).
831
Amazon API Gateway Developer Guide
Earlier updates
Supporting binary Set binaryMediaTypes on your API to support binary payloads November 17,
payloads of a request or response. Set the contentHandling property 2016
on an Integration or IntegrationResponse to specify whether
to handle a binary payload as the native binary blob, as
a Base64-enocded string, or as a passthrough without
modifications. For more information, see Working with binary
media types for REST APIs (p. 436).
Enabling a proxy Create a proxy resource with a greedy path parameter of the September
integration with an form {proxy+} and the catch-all ANY method. The proxy 20, 2016
HTTP or Lambda resource is integrated with an HTTP or Lambda backend
backend through a using the HTTP or Lambda proxy integration, respectively. For
proxy resource of an more information, see Set up a proxy integration with a proxy
API. resource (p. 327).
Extending selected Create a usage plan in API Gateway to enable selected API August 11,
APIs in API Gateway clients to access specified API stages at agreed-upon request 2016
as product offerings rates and quotas. For more information, see Creating and
for your customers using usage plans with API keys (p. 549).
by providing one or
more usage plans.
Enabling method- Create a user pool in Amazon Cognito and use it as your July 28, 2016
level authorization own identity provider. You can configure the user pool as a
with a user pool in method-level authorizer to grant access for users who are
Amazon Cognito registered with the user pool. For more information, see
Control access to a REST API using Amazon Cognito user pools
as authorizer (p. 315).
Enabling Amazon The API Gateway metrics are now standardized under the July 28, 2016
CloudWatch metrics CloudWatch namespace of AWS/ApiGateway. You can view
and dimensions them in both the API Gateway console and the Amazon
under the AWS/ CloudWatch console. For more information, see Amazon API
ApiGateway Gateway dimensions and metrics (p. 673).
namespace.
Enabling certificate Certificate rotation allows you to upload and renew April 27,
rotation for a custom an expiring certificate for a custom domain name. For 2016
domain name more information, see Rotate a certificate imported into
ACM (p. 530).
Documenting Learn how to create and set up an API using the updated API April 5, 2016
changes for the Gateway console. For more information, see Tutorial: Create a
updated Amazon API REST API by importing an example (p. 46) and Tutorial: Build a
Gateway console. REST API with HTTP non-proxy integration (p. 59).
Enabling the Import With the Import API features, you can create a new API or April 5, 2016
API feature to create update an existing one by uploading an external API definition
a new or update expressed in Swagger 2.0 with the API Gateway extensions.
an existing API For more information about the Import API, see Configuring a
from external API REST API using OpenAPI (p. 480).
definitions.
832
Amazon API Gateway Developer Guide
Earlier updates
Exposing the For more information about $input.body and April 5, 2016
$input.body $util.parseJson(), see API Gateway mapping template
variable to access and access logging variable reference (p. 410).
the raw payload
as string and the
$util.parseJson()
function to turn a
JSON string into a
JSON object in a
mapping template.
Enabling client Flush API stage-level cache and invalidate individual cache March 25,
requests with entry. For more information, see Flush the API stage cache 2016
method-level in API Gateway (p. 542) and Invalidate an API Gateway cache
cache invalidation, entry (p. 543). Improve the console experience for managing
and improving API request throttling. For more information, see Throttle API
request throttling requests for better throughput (p. 663).
management.
Enabling and calling Create and configure an AWS Lambda function to implement February 11,
API Gateway API custom authorization. The function returns an IAM policy 2016
using custom document that grants the Allow or Deny permissions to client
authorization requests of an API Gateway API. For more information, see Use
API Gateway Lambda authorizers (p. 299).
Importing and Create and update your API Gateway API using the Swagger December 18,
exporting API specification with the API Gateway extensions. Import 2015
Gateway API using a the Swagger definitions using the API Gateway Importer.
Swagger definition Export an API Gateway API to a Swagger definition file
file and extensions using the API Gateway console or API Gateway Export
API. For more information, see Configuring a REST API
using OpenAPI (p. 480) and Export a REST API from API
Gateway (p. 487).
Mapping request or Map method request body or its JSON fields into integration December 18,
response body or request's path, query string, or headers. Map integration 2015
body's JSON fields to response body or its JSON fields into request response's
request or response headers. For more information, see Amazon API Gateway API
parameters. request and response data mapping reference (p. 405).
Working with Stage Learn how to associate configuration attributes with a November 5,
Variables in Amazon deployment stage of an API in Amazon API Gateway. For more 2015
API Gateway information, see Setting up stage variables for a REST API
deployment (p. 499).
How to: Enable CORS It is now easier to enable cross-origin resource sharing (CORS) November 3,
for a Method for methods in Amazon API Gateway. For more information, 2015
see Enabling CORS for a REST API resource (p. 429).
How to: Use Use Amazon API Gateway to generate SSL certificates that you September
Client Side SSL can use to authenticate calls to your HTTP backend. For more 22, 2015
Authentication information, see Generate and configure an SSL certificate for
backend authentication (p. 635).
833
Amazon API Gateway Developer Guide
Earlier updates
Mock integration of Learn how to mock-integrate an API with Amazon API September 1,
methods Gateway (p. 361). This feature enables developers to generate 2015
API responses from API Gateway directly without the need for
a final integration backend beforehand.
Amazon Cognito Amazon API Gateway has expanded the scope of the August 28,
Identity support $context variable so that it now returns information about 2015
Amazon Cognito Identity when requests are signed with
Amazon Cognito credentials. In addition, we have added a
$util variable for escaping characters in JavaScript and
encoding URLs and strings. For more information, see API
Gateway mapping template and access logging variable
reference (p. 410).
Swagger integration Use the Swagger import tool on GitHub to import Swagger July 21, 2015
API definitions into Amazon API Gateway. Learn more about
Working with API Gateway extensions to OpenAPI (p. 744) to
create and deploy APIs and methods using the import tool.
With the Swagger importer tool you can also update existing
APIs.
Mapping Template Read about the $input parameter and its functions in the July 18, 2015
Reference API Gateway mapping template and access logging variable
reference (p. 410).
Initial public release This is the initial public release of the API Gateway Developer July 9, 2015
Guide.
834
Amazon API Gateway Developer Guide
AWS glossary
For the latest AWS terminology, see the AWS glossary in the AWS General Reference.
835