Amazon API Gateway
Developer Guide
Amazon API Gateway: Developer Guide
Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.
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.
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 ... 17
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
Working with HTTP APIs ... 182
Develop ... 182
Creating an HTTP API ... 182
Routes ... 183
Access control ... 185
Integrations ... 193
CORS ... 205
Parameter mapping ... 206
OpenAPI ... 211
Publish ... 217
Stages ... 217
Custom domain names ... 218
Protect ... 222
Throttling ... 223
Mutual TLS ... 223
Monitor ... 227
Metrics ... 228
Logging ... 229
Troubleshooting ... 235
Lambda integrations ... 235
JWT authorizers ... 237
Working with REST APIs ... 238
Develop ... 238
Create and configure ... 238
Access control ... 269
Integrations ... 319
Request validation ... 360
Data transformations ... 372
Gateway responses ... 418
CORS ... 425
Binary media types ... 432
Invoke ... 454
OpenAPI ... 476
Publish ... 486
Deploying a REST API ... 486
Custom domain names ... 514
Optimize ... 535
Cache settings ... 535
Content encoding ... 540
Distribute ... 544
Usage plans ... 545
API documentation ... 558
SDK generation ... 600
Developer portal ... 616
Sell your APIs as SaaS ... 623
Protect ... 626
Mutual TLS ... 627
Client certificates ... 631
AWS WAF ... 658
Throttling ... 659
Private APIs ... 661
Monitor ... 668
CloudWatch metrics ... 668
CloudWatch logs ... 674
Kinesis Data Firehose ... 677
X-Ray ... 678
Working with WebSocket APIs ... 689
About WebSocket APIs ... 689
Managing connected users and client apps ... 690
Invoking your backend integration ... 691
Sending data from backend services to connected clients ... 693
WebSocket selection expressions ... 693
Develop ... 698
Create and configure ... 698
Routes ... 699
Access control ... 704
Integrations ... 708
Request validation ... 712
Data transformations ... 712
Binary media types ... 720
Invoke ... 720
Publish ... 722
Stages ... 722
Deploy a WebSocket API ... 723
Custom domain names ... 725
Protect ... 729
Account-level throttling per Region ... 729
Route-level throttling ... 729
Monitor ... 729
Metrics ... 730
Logging ... 731
API Gateway ARNs ... 735
HTTP API and WebSocket API resources ... 735
REST API resources ... 737
execute-api (HTTP APIs, WebSocket APIs, and REST APIs) ... 739
OpenAPI extensions ... 740
x-amazon-apigateway-any-method ... 741
x-amazon-apigateway-any-method examples ... 741
x-amazon-apigateway-cors ... 742
x-amazon-apigateway-cors example ... 742
x-amazon-apigateway-api-key-source ... 743
x-amazon-apigateway-api-key-source example ... 743
x-amazon-apigateway-auth ... 743
x-amazon-apigateway-auth example ... 744
x-amazon-apigateway-authorizer ... 744
x-amazon-apigateway-authorizer examples for REST APIs ... 746
x-amazon-apigateway-authorizer examples for HTTP APIs ... 748
x-amazon-apigateway-authtype ... 749
x-amazon-apigateway-authtype example ... 749
See also ... 751
x-amazon-apigateway-binary-media-type ... 751
x-amazon-apigateway-binary-media-types example ... 751
x-amazon-apigateway-documentation ... 751
x-amazon-apigateway-documentation example ... 751
x-amazon-apigateway-endpoint-configuration ... 752
x-amazon-apigateway-endpoint-configuration examples ... 752
x-amazon-apigateway-gateway-responses ... 753
x-amazon-apigateway-gateway-responses example ... 753
x-amazon-apigateway-gateway-responses.gatewayResponse ... 753
x-amazon-apigateway-gateway-responses.gatewayResponse example ... 754
x-amazon-apigateway-gateway-responses.responseParameters ... 754
x-amazon-apigateway-gateway-responses.responseParameters example ... 754
x-amazon-apigateway-gateway-responses.responseTemplates ... 755
x-amazon-apigateway-gateway-responses.responseTemplates example ... 755
x-amazon-apigateway-importexport-version ... 755
x-amazon-apigateway-importexport-version example ... 756
x-amazon-apigateway-integration ... 756
x-amazon-apigateway-integration examples ... 759
x-amazon-apigateway-integrations ... 760
x-amazon-apigateway-integrations example ... 761
x-amazon-apigateway-integration.requestTemplates ... 762
x-amazon-apigateway-integration.requestTemplates example ... 762
x-amazon-apigateway-integration.requestParameters ... 763
x-amazon-apigateway-integration.requestParameters example ... 764
x-amazon-apigateway-integration.responses ... 764
x-amazon-apigateway-integration.responses example ... 765
x-amazon-apigateway-integration.response ... 765
x-amazon-apigateway-integration.response example ... 766
x-amazon-apigateway-integration.responseTemplates ... 767
x-amazon-apigateway-integration.responseTemplate example ... 767
x-amazon-apigateway-integration.responseParameters ... 767
x-amazon-apigateway-integration.responseParameters example ... 768
x-amazon-apigateway-integration.tlsConfig ... 768
x-amazon-apigateway-integration.tlsConfig examples ... 769
x-amazon-apigateway-minimum-compression-size ... 769
x-amazon-apigateway-minimum-compression-size example ... 769
x-amazon-apigateway-policy ... 769
x-amazon-apigateway-policy example ... 770
x-amazon-apigateway-request-validator ... 770
x-amazon-apigateway-request-validator example ... 770
x-amazon-apigateway-request-validators ... 771
x-amazon-apigateway-request-validators example ... 771
x-amazon-apigateway-request-validators.requestValidator ... 772
x-amazon-apigateway-request-validators.requestValidator example ... 772
x-amazon-apigateway-tag-value ... 772
x-amazon-apigateway-tag-value example ... 773
Security ... 774
Data protection ... 774
Data encryption ... 775
Internetwork traffic privacy ... 775
Identity and access management ... 776
Audience ... 776
Authenticating with identities ... 776
Managing access using policies ... 778
How Amazon API Gateway works with IAM ... 780
Identity-based policy examples ... 783
Resource-based policy examples ... 789
Troubleshooting ... 789
Using service-linked roles ... 791
Logging and monitoring ... 794
Working with AWS CloudTrail ... 795
Working with AWS Config ... 796
Compliance validation ... 799
Resilience ... 799
Infrastructure security ... 799
Configuration and vulnerability analysis ... 800
Best practices ... 800
Tagging ... 802
API Gateway resources that can be tagged ... 802
Tag inheritance in the Amazon API Gateway V1 API ... 803
Tag restrictions and usage conventions ... 804
Attribute-based access control ... 804
Example 1: Limit actions based on resource tags ... 805
Example 2: Limit actions based on tags in the request ... 805
Example 3: Deny actions based on resource tags ... 806
Example 4: Allow actions based on resource tags ... 806
Example 5: Allow actions based on resource tag keys ... 807
API references ... 808
Quotas and important notes ... 809
API Gateway account-level quotas, per Region ... 809
HTTP API quotas ... 810
... 810
API Gateway quotas for configuring and running a WebSocket API ... 811
API Gateway quotas for configuring and running a REST API ... 812
API Gateway quotas for creating, deploying and managing an API ... 814
Important notes ... 815
Important notes for REST and WebSocket APIs ... 815
Important notes for WebSocket APIs ... 816
Important notes for REST APIs ... 816
Document history ... 820
Earlier updates ... 825 AWS glossary ... 831
Architecture of API Gateway
What is Amazon API Gateway?
Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at any scale. API developers can create APIs that access AWS or other web services, as well as data stored in the AWS Cloud. As an API Gateway API developer, you can create APIs for use in your own client applications. Or you can make your APIs available to third-party app developers. For more information, see the section called “Who uses API Gateway?” (p. 4).
API Gateway creates RESTful APIs that:
• 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. 182), the section called “Use API
Gateway to create REST APIs” (p. 3), and the section called “Create and configure” (p. 238).
API Gateway creates WebSocket APIs that:
• 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. 689).
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)
Architecture of API Gateway
The following diagram shows API Gateway architecture.
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.
Features of API Gateway
Amazon API Gateway offers features such as the following:
• Support for stateful (WebSocket (p. 689)) and stateless (HTTP (p. 182) and REST (p. 238)) APIs.
• Powerful, flexible authentication (p. 269) mechanisms, such as AWS Identity and Access Management policies, Lambda authorizer functions, and Amazon Cognito user pools.
• Developer portal (p. 616) for publishing your APIs.
• Canary release deployments (p. 503) for safely rolling out changes.
• CloudTrail (p. 795) 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. 668) and the section called
“Metrics” (p. 730).
• 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. 514).
• Integration with AWS WAF (p. 658) for protecting your APIs against common web exploits.
• Integration with AWS X-Ray (p. 678) for understanding and triaging performance latencies.
For a complete list of API Gateway feature releases, see Document history (p. 820).
API Gateway use cases
API Gateway use cases
Topics
• Use API Gateway to create HTTP APIs (p. 3)
• Use API Gateway to create REST APIs (p. 3)
• Use API Gateway to create WebSocket APIs (p. 4)
• Who uses API Gateway? (p. 4)
Use API Gateway to create HTTP APIs
HTTP APIs enable you to create RESTful APIs with lower latency and lower cost than REST APIs.
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).
Use API Gateway to create REST APIs
An API Gateway REST API is made up of resources and methods. A resource is a logical entity that an app can access through a resource path. A method corresponds to a REST API request that is submitted by the user of your API and the response returned to the user.
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
Use API Gateway to create WebSocket APIs
• Throttling of HTTP requests
Use API Gateway to create WebSocket APIs
In a WebSocket API, the client and the server can both send messages to each other at any time. Backend servers can easily push data to connected users and devices, avoiding the need to implement complex polling mechanisms.
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:
• Monitoring and throttling of connections and messages
• Using AWS X-Ray to trace messages as they travel through the APIs to backend services
• Easy integration with HTTP/HTTPS endpoints
Who uses API Gateway?
There are two kinds of developers who use API Gateway: API developers and app developers.
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.
Creating and managing an API Gateway API
An API developer works with the API Gateway service component for API management, named apigateway, to create, configure, and deploy an API.
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. 808). 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. 740).
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.
Accessing API Gateway
Calling an API Gateway API
An app developer works with the API Gateway service component for API execution, named execute- api, to invoke an API that was created or deployed in API Gateway. The underlying programming entities are exposed by the created API. There are several ways to call such an API. To learn more, see Invoking a REST API in Amazon API Gateway (p. 454) and Invoking a WebSocket API (p. 720).
Accessing API Gateway
You can access Amazon API Gateway in the following ways:
• 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.
Part of AWS serverless infrastructure
Together with AWS Lambda, API Gateway forms the app-facing part of the AWS serverless infrastructure.
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. 323) with AWS Lambda and HTTP endpoints.
How to get started with Amazon API Gateway
For an introduction to Amazon API Gateway, see the following:
• Getting started (p. 13), which provides a walkthrough for creating an HTTP API.
• Serverless land, which provides instructional videos.
Amazon API Gateway concepts
API Gateway
API Gateway is an AWS service that supports the following:
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. 295) or usage plans (p. 545) to control access to your APIs.
See API endpoints (p. 6).
API owner
See API developer (p. 6).
API stage
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.
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.
See API endpoints (p. 6).
Integration request
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.
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
See Private API endpoint (p. 8).
Private API endpoint
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. 183).
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.
See API endpoints (p. 6).
Route
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.
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. 545) 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.
Choosing between HTTP APIs and REST APIs
HTTP APIs are designed for low-latency, cost-effective integrations with AWS services, including AWS Lambda, and HTTP endpoints. HTTP APIs support OIDC and OAuth 2.0 authorization, and come with built-in support for CORS and automatic deployments. Previous-generation REST APIs currently offer more features.
The following tables summarize core features that are available in HTTP APIs and REST APIs.
Authorizers HTTP API REST API
AWS Lambda ✓ ✓
IAM ✓ ✓
Amazon Cognito ✓ * ✓
Native OpenID Connect / OAuth
2.0 ✓
* You can use Amazon Cognito as a JWT issuer.
Integration HTTP API REST API
Public HTTP endpoints ✓ ✓
Lambda ✓ ✓
AWS services ✓ ✓
Private integrations with
Application Load Balancers ✓
Choosing HTTP API or REST API
Integration HTTP API REST API
Private integrations with
Network Load Balancers ✓ ✓
Private integrations with AWS
Cloud Map ✓
Mock ✓
API management HTTP API REST API
Usage plans ✓
API keys ✓
Custom domain names ✓ * ✓
* HTTP APIs don't support TLS 1.0.
Development HTTP API REST API
API caching ✓
Request parameter
transformation ✓ ✓
Request body transformation ✓
Request / response validation ✓
Test invocation ✓
CORS configuration ✓ ✓ *
Automatic deployments ✓
Default stage ✓
Default route ✓
Custom gateway
responses (p. 418) ✓
Canary release
deployment (p. 503) ✓
* You can combine different features of REST APIs to support CORS. To learn more, see the section called
“CORS” (p. 425).
Security HTTP API REST API
Mutual TLS authentication ✓ ✓
Certificates for backend
authentication (p. 631) ✓
Choosing HTTP API or REST API
Security HTTP API REST API
AWS WAF ✓
Resource policies ✓
API type HTTP API REST API
Regional ✓ ✓
Edge-optimized ✓
Private ✓
Monitoring HTTP API REST API
Access logs to Amazon
CloudWatch Logs ✓ ✓
Access logs to Amazon Kinesis
Data Firehose ✓
Execution logs ✓
Amazon CloudWatch metrics ✓ ✓
AWS X-Ray ✓
Prerequisites for getting started with API Gateway
To use API Gateway and other AWS services, you need an AWS account. If you don't have an account, visit aws.amazon.com and choose Create an AWS Account. For detailed instructions, see Create and activate an AWS account.
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.
Step 1: Create a Lambda function
Getting started with API Gateway
In this getting started exercise, you create a serverless API. Serverless APIs let you focus on your applications, instead of spending time provisioning and managing servers. This exercise takes less than 20 minutes to complete, and is possible within the AWS Free Tier.
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)
Step 1: Create a Lambda function
You use a Lambda function for the backend of your API. Lambda runs your code only when needed and scales automatically, from a few requests per day to thousands per second.
For this example, you use the default Node.js function from the Lambda console.
To create a Lambda function
1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
2. Choose Create function.
3. For Function name, enter my-function.
4. Choose Create function.
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. 196).
The default Lambda function code should look similar to the following:
exports.handler = async (event) => { const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'), };
return response;
};
Step 2: Create an HTTP API
Next, you create an HTTP API. API Gateway also supports REST APIs and WebSocket APIs, but an HTTP API is the best choice for this exercise. HTTP APIs have lower latency and lower cost than REST APIs.
WebSocket APIs maintain persistent connections with clients for full-duplex communication, which isn't required for this example.
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.
To create an HTTP API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Do one of the following:
• To create your first API, for HTTP API, choose Build.
• If you've created an API before, choose Create API, and then choose Build for HTTP API.
3. For Integrations, choose Add integration.
4. Choose Lambda.
5. For Lambda function, enter my-function.
6. For API name, enter my-http-api.
7. Choose Next.
8. Review the route that API Gateway creates for you, and then choose Next.
9. Review the stage that API Gateway creates for you, and then choose Next.
10. Choose Create.
Now you've created an HTTP API with a Lambda integration that's ready to receive requests from clients.
Step 3: Test your API
Next, you test your API to make sure that it's working. For simplicity, use a web browser to invoke your API.
To test your API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
(Optional) Step 4: Clean up
2. Choose your API.
3. Note your API's invoke URL.
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.
The full URL should look like https://abcdef123.execute-api.us- east-2.amazonaws.com/my-function.
Your browser sends a GET request to the API.
5. Verify your API's response. You should see the text "Hello from Lambda!" in your browser.
(Optional) Step 4: 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.
To delete an HTTP API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. On the APIs page, select an API. Choose Actions, and then choose Delete.
3. Choose Delete.
To delete a Lambda function
1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
2. On the Functions page, select a function. Choose Actions, and then choose Delete.
3. Choose Delete.
Next steps
To delete a Lambda function's log group
1. In the Amazon CloudWatch console, open the Log groups page.
2. On the Log groups page, select the function's log group (/aws/lambda/my-function). Choose Actions, and then choose Delete log group.
3. Choose Delete.
To delete a Lambda function's execution role
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.
• Configure additional types of API integrations, (p. 193) including:
• HTTP endpoints (p. 197)
• Private resources in a VPC, such as Amazon ECS services (p. 203)
• AWS services such as Amazon Simple Queue Service, AWS Step Functions, and Kinesis Data Streams (p. 198)
• Control access to your APIs (p. 185)
• Enable logging for your APIs (p. 229)
• Configure throttling for your APIs (p. 223)
• Configure custom domains for your APIs (p. 218)
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.
See also our frequently asked questions (FAQs), or contact us directly.
HTTP API tutorials
Amazon API Gateway tutorials and workshops
The following tutorials and workshops provide hands-on exercises to help you learn about API Gateway.
HTTP API tutorials
• Tutorial: Build a CRUD API with Lambda and DynamoDB (p. 17)
• Tutorial: Building an HTTP API with a private integration to an Amazon ECS service (p. 25)
REST API tutorials
• 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)
Workshops
• Build a serverless web application
• CI/CD for serverless applications
• Serverless security workshop
• Serverless identity management, authentication and authorization
Amazon API Gateway HTTP API tutorials
The following tutorials provide hands-on exercises to help you learn about API Gateway HTTP APIs.
Topics
• Tutorial: Build a CRUD API with Lambda and DynamoDB (p. 17)
• Tutorial: Building an HTTP API with a private integration to an Amazon ECS service (p. 25)
Tutorial: Build a CRUD API with Lambda and DynamoDB
In this tutorial, you create a serverless API that creates, reads, updates, and deletes items from a DynamoDB table. DynamoDB is a fully managed NoSQL database service that provides fast and
CRUD API with Lambda and DynamoDB
predictable performance with seamless scalability. This tutorial takes approximately 30 minutes to complete, and you can do it within the AWS Free Tier.
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. 18)
• 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)
Step 1: Create a DynamoDB table
You use a DynamoDB table to store data for your API.
Each item has a unique ID, which we use as the partition key for the table.
To create a DynamoDB table
1. Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
2. Choose Create table.
3. For Table name, enter http-crud-tutorial-items.
4. For Primary key, enter id.
5. Choose Create.
Step 2: Create a Lambda function
You create a Lambda function for the backend of your API. This Lambda function creates, reads, updates, and deletes items from DynamoDB. The function uses events from API Gateway (p. 194) to determine
CRUD API with Lambda and DynamoDB
how to interact with DynamoDB. For simplicity this tutorial uses a single Lambda function. As a best practice, you should create separate functions for each route.
To create a Lambda function
1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
2. Choose Create function.
3. For Function name, enter http-crud-tutorial-function.
4. Under Permissions choose Change default execution role.
5. Select Create a new role from AWS policy templates.
6. For Role name, enter http-crud-tutorial-role.
7. For Policy templates, choose Simple microservice permissions. This policy grants the Lambda function permission to interact with DynamoDB.
Note
This tutorial uses a managed policy for simplicity. As a best practice, you should create your own IAM policy to grant the minimum permissions required.
8. Choose Create function.
9. Open index.js in the console's code editor, and replace its contents with the following code.
Choose Deploy to update your function.
const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event, context) => { let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json"
};
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;
case "GET /items":
body = await dynamo.scan({ TableName: "http-crud-tutorial-items" }).promise();
break;
case "PUT /items":
CRUD API with Lambda and DynamoDB
let requestJSON = JSON.parse(event.body);
await dynamo .put({
TableName: "http-crud-tutorial-items", Item: {
id: requestJSON.id, price: requestJSON.price, name: requestJSON.name }
})
.promise();
body = `Put item ${requestJSON.id}`;
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) { statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
} return { statusCode, body, headers };};
Step 3: Create an HTTP API
The HTTP API provides an HTTP endpoint for your Lambda function. In this step, you create an empty API. In the following steps, you configure routes and integrations to connect your API and your Lambda function.
To create an HTTP API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose Create API, and then for HTTP API, choose Build.
3. For API name, enter http-crud-tutorial-api.
4. Choose Next.
5. For Configure routes, choose Next to skip route creation. You create routes later.
6. Review the stage that API Gateway creates for you, and then choose Next.
7. Choose Create.
Step 4: Create routes
Routes are a way to send incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path, for example, GET /items. For this example API, we create four routes:
• GET /items/{id}
• GET /items
• PUT /items
CRUD API with Lambda and DynamoDB
• DELETE /items/{id}
To create routes
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Choose Routes.
4. Choose Create.
5. For Method, choose GET.
6. For the path, enter /items/{id}. The {id} at the end of the path is a path parameter that API Gateway retrieves from the request path when a client makes a request.
7. Choose Create.
8. Repeat steps 4-7 for GET /items, DELETE /items/{id}, and PUT /items.
Step 5: Create an integration
You create an integration to connect a route to backend resources. For this example API, you create one Lambda integration that you use for all routes.
To create an integration
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Choose Integrations.
4. Choose Manage integrations and then choose Create.
5. Skip Attach this integration to a route. You complete that in a later step.
6. For Integration type, choose Lambda function.
7. For Lambda function, enter http-crud-tutorial-function.
8. Choose Create.
CRUD API with Lambda and DynamoDB
Step 6: Attach your integration to routes
For this example API, you use the same Lambda integration for all routes. After you attach the integration to all of the API's routes, your Lambda function is invoked when a client calls any of your routes.
To attach integrations to routes
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Choose Integrations.
4. Choose a route.
5. Under Choose an existing integration, choose http-crud-tutorial-function.
6. Choose Attach integration.
7. Repeat steps 4-6 for all routes.
All routes show that an AWS Lambda integration is attached.
Now that you have an HTTP API with routes and integrations, you can test your API.
Step 7: Test your API
To make sure that your API is working, you use curl.
To get the URL to invoke your API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Note your API's invoke URL. It appears under Invoke URL on the Details page.
CRUD API with Lambda and DynamoDB
4. Copy your API's invoke URL.
The full URL looks like https://abcdef123.execute-api.us-west-2.amazonaws.com.
To create or update an item
• 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 -X "PUT" -H "Content-Type: application/json" -d "{\"id\": \"abcdef234\", \"price\": 12345, \"name\": \"myitem\"}" https://abcdef123.execute-api.us- west-2.amazonaws.com/items
To get all items
• Use the following command to list all items.
curl -v https://abcdef123.execute-api.us-west-2.amazonaws.com/items
To get an item
• Use the following command to get an item by its ID.
curl -v https://abcdef123.execute-api.us-west-2.amazonaws.com/items/abcdef234
To delete an item
1. Use the following command to delete an item.
curl -v -X "DELETE" https://abcdef123.execute-api.us-west-2.amazonaws.com/
items/abcdef234
CRUD API with Lambda and DynamoDB
2. Get all items to verify that the item was deleted.
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.
To delete a DynamoDB table
1. Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.
2. Select your table.
3. Choose Delete table.
4. Confirm your choice, and choose Delete.
To delete an HTTP API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. On the APIs page, select an API. Choose Actions, and then choose Delete.
3. Choose Delete.
To delete a Lambda function
1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.
2. On the Functions page, select a function. Choose Actions, and then choose Delete.
3. Choose Delete.
To delete a Lambda function's log group
1. In the Amazon CloudWatch console, open the Log groups page.
2. On the Log groups page, select the function's log group (/aws/lambda/http-crud-tutorial- function). Choose Actions, and then choose Delete log group.
3. Choose Delete.
To delete a Lambda function's execution role
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.
Next steps: Automate with AWS SAM or AWS CloudFormation
You can automate the creation and cleanup of AWS resources by using AWS CloudFormation or AWS SAM. For an example AWS SAM template for this tutorial, see template.yaml.
For example AWS CloudFormation templates, see example AWS CloudFormation templates.
Private integration to Amazon ECS
Tutorial: Building an HTTP API with a private integration to an Amazon ECS service
In this tutorial, you create a serverless API that connects to an Amazon ECS service that runs in an Amazon VPC. Clients outside of your Amazon VPC can use the API to access your Amazon ECS service.
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)
Step 1: Create an Amazon ECS service
Amazon ECS is a container management service that makes it easy to run, stop, and manage Docker containers on a cluster. In this tutorial, you run your cluster on a serverless infrastructure that's managed by Amazon ECS.
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.
Private integration to Amazon ECS
To create a AWS CloudFormation stack
1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation.
2. Choose Create stack and then choose With new resources (standard).
3. For Specify template, choose Upload a template file.
4. Select the template that you downloaded.
5. Choose Next.
6. For Stack name, enter http-api-private-integrations-tutorial and then choose Next.
7. For Configure stack options, choose Next.
8. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account.
9. Choose Create stack.
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.
Step 2: Create a VPC link
A VPC link allows API Gateway to access private resources in an Amazon VPC. You use a VPC link to allow clients to access your Amazon ECS service through your HTTP API.
To create a VPC link
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose VPC links and then choose Create.
3. For Choose a VPC link version, select VPC link for HTTP APIs.
4. For Name, enter private-integrations-tutorial.
5. For VPC, choose the VPC that you created in step 1. The name should start with PrivateIntegrationsStack.
6. For Subnets, select the two private subnets in your VPC. Their names end with PrivateSubnet.
7. Choose Create.
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.
Step 3: Create an HTTP API
The HTTP API provides an HTTP endpoint for your Amazon ECS service. In this step, you create an empty API. In Steps 4 and 5, you configure a route and an integration to connect your API and your Amazon ECS service.
To create an HTTP API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose Create API, and then for HTTP API, choose Build.
3. For API name, enter http-private-integrations-tutorial.
4. Choose Next.
5. For Configure routes, choose Next to skip route creation. You create routes later.
6. Review the stage that API Gateway creates for you. API Gateway creates a $default stage with automatic deployments enabled, which is the best choice for this tutorial. Choose Next.
7. Choose Create.
Private integration to Amazon ECS
Step 4: Create a route
Routes are a way to send incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path, for example, GET /items. For this example API, we create one route.
To create a route
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Choose Routes.
4. Choose Create.
5. For Method, choose ANY.
6. For the path, enter /{proxy+}. The {proxy+} at the end of the path is a greedy path variable. API Gateway sends all requests to your API to this route.
7. Choose Create.
Step 5: Create an integration
You create an integration to connect a route to backend resources.
To create an integration
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Choose Integrations.
4. Choose Manage integrations and then choose Create.
5. For Attach this integration to a route, select the ANY /{proxy+} route that you created earlier.
6. For Integration type, choose Private resource.
7. For Integration details, choose Select manually.
8. For Target service, choose ALB/NLB.
9. For Load balancer, choose the load balancer that you created with the AWS CloudFormation template in Step 1. It's name should start with http-Priva.
10. For Listener, choose HTTP 80.
11. For VPC link, choose the VPC link that you created in Step 2. It's name should be private- integrations-tutorial.
12. Choose Create.
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.
Private integration to Amazon ECS
Now you're ready to test your API.
Step 6: Test your API
Next, you test your API to make sure that it's working. For simplicity, use a web browser to invoke your API.
To test your API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose your API.
3. Note your API's invoke URL.
Private integration to Amazon ECS
4. In a web browser, go to your API's invoke URL.
The full URL should look like https://abcdef123.execute-api.us-east-2.amazonaws.com.
Your browser sends a GET request to the API.
5. Verify that your API's response is a welcome message that tells you that your app is running on 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.
To delete an HTTP API
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. On the APIs page, select an API. Choose Actions, choose Delete, and then confirm your choice.
To delete a VPC link
1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.
2. Choose VPC link.
3. Select your VPC link, choose Delete, and then confirm your choice.
REST API tutorials
To delete an AWS CloudFormation stack
1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation.
2. Select your AWS CloudFormation stack.
3. Choose Delete and then confirm your choice.
Next steps: Automate with AWS CloudFormation
You can automate the creation and cleanup of all AWS resources involved in this tutorial. For a full example AWS CloudFormation template, see template.yaml.
Amazon API Gateway REST API tutorials
The following tutorials provide hands-on exercises to help you learn about API Gateway REST APIs.
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)
Build an API Gateway REST API with Lambda integration
To build an API with Lambda integrations, you can use Lambda proxy integration or Lambda non-proxy integration.
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)
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)
Tutorial: Build a Hello World REST API with Lambda proxy integration
Lambda proxy integration (p. 327) is a lightweight, flexible API Gateway API integration type that allows you to integrate an API method – or an entire API – with a Lambda function. The Lambda function can be written in any language that Lambda supports. Because it's a proxy integration, you can change the Lambda function implementation at any time without needing to redeploy your API.
In this tutorial, you do the following:
• 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)
Create a "Hello, World!" Lambda function
This function returns a greeting to the caller as a JSON object in the following format:
{ "greeting": "Good {time}, {name} of {city}.[ Happy {day}!]"
}
Create a "Hello, World!" Lambda function in the Lambda console
1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda.2. On the AWS navigation bar, choose a region (for example, US East (N. Virginia)).
Note
Note the region where you create the Lambda function. You'll need it when you create the API.3. Choose Functions in the navigation pane.
4. Choose Create function.
5. Choose Author from scratch.
6. Under Basic information, do the following:
a. In Function name, enter GetStartedLambdaProxyIntegration.
b. From the Runtime dropdown list, choose a supported Node.js runtime.
c. Under Permissions, expand Choose or create an execution role. From the Execution role dropdown list, choose Create new role from AWS policy templates.
d. In Role name, enter GetStartedLambdaBasicExecutionRole.
e. Leave the Policy templates field blank.
f. Choose Create function.
7. Under Function code, in the inline code editor, copy/paste the following code: