Package software.amazon.awscdk.services.apigateway
Amazon API Gateway Construct Library
Amazon API Gateway is a fully managed service that makes it easy for developers to publish, maintain, monitor, and secure APIs at any scale. Create an API to access data, business logic, or functionality from your back-end services, such as applications running on Amazon Elastic Compute Cloud (Amazon EC2), code running on AWS Lambda, or any web application.
Table of Contents
- Amazon API Gateway Construct Library
- Table of Contents
- Defining APIs
- AWS Lambda-backed APIs
- AWS StepFunctions backed APIs
- Integration Targets
- Usage Plan & API Keys
- Working with models
- Default Integration and Method Options
- Proxy Routes
- Authorizers
- Mutual TLS (mTLS)
- Deployments
- Custom Domains
- Access Logging
- Cross Origin Resource Sharing (CORS)
- Endpoint Configuration
- Private Integrations
- Gateway response
- OpenAPI Definition
- Metrics
- APIGateway v2
Defining APIs
APIs are defined as a hierarchy of resources and methods. addResource and
addMethod can be used to build this hierarchy. The root resource is
api.root.
For example, the following code defines an API that includes the following HTTP
endpoints: ANY /, GET /books, POST /books, GET /books/{book_id}, DELETE /books/{book_id}.
RestApi api = new RestApi(this, "books-api");
api.root.addMethod("ANY");
Resource books = api.root.addResource("books");
books.addMethod("GET");
books.addMethod("POST");
Resource book = books.addResource("{book_id}");
book.addMethod("GET");
book.addMethod("DELETE");
To give an IAM User or Role permission to invoke a method, use grantExecute:
RestApi api;
User user;
Method method = api.root.addResource("books").addMethod("GET");
method.grantExecute(user);
Breaking up Methods and Resources across Stacks
It is fairly common for REST APIs with a large number of Resources and Methods to hit the CloudFormation limit of 500 resources per stack.
To help with this, Resources and Methods for the same REST API can be re-organized across multiple stacks. A common way to do this is to have a stack per Resource or groups of Resources, but this is not the only possible way. The following example uses sets up two Resources '/pets' and '/books' in separate stacks using nested stacks:
import software.constructs.Construct;
import software.amazon.awscdk.App;
import software.amazon.awscdk.CfnOutput;
import software.amazon.awscdk.NestedStack;
import software.amazon.awscdk.NestedStackProps;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.services.apigateway.Deployment;
import software.amazon.awscdk.services.apigateway.Method;
import software.amazon.awscdk.services.apigateway.MockIntegration;
import software.amazon.awscdk.services.apigateway.PassthroughBehavior;
import software.amazon.awscdk.services.apigateway.RestApi;
import software.amazon.awscdk.services.apigateway.Stage;
/**
* This file showcases how to split up a RestApi's Resources and Methods across nested stacks.
*
* The root stack 'RootStack' first defines a RestApi.
* Two nested stacks BooksStack and PetsStack, create corresponding Resources '/books' and '/pets'.
* They are then deployed to a 'prod' Stage via a third nested stack - DeployStack.
*
* To verify this worked, go to the APIGateway
*/
public class RootStack extends Stack {
public RootStack(Construct scope) {
super(scope, "integ-restapi-import-RootStack");
RestApi restApi = RestApi.Builder.create(this, "RestApi")
.cloudWatchRole(true)
.deploy(false)
.build();
restApi.root.addMethod("ANY");
PetsStack petsStack = new PetsStack(this, new ResourceNestedStackProps()
.restApiId(restApi.getRestApiId())
.rootResourceId(restApi.getRestApiRootResourceId())
);
BooksStack booksStack = new BooksStack(this, new ResourceNestedStackProps()
.restApiId(restApi.getRestApiId())
.rootResourceId(restApi.getRestApiRootResourceId())
);
new DeployStack(this, new DeployStackProps()
.restApiId(restApi.getRestApiId())
.methods(petsStack.methods.concat(booksStack.getMethods()))
);
CfnOutput.Builder.create(this, "PetsURL")
.value(String.format("https://%s.execute-api.%s.amazonaws.com/prod/pets", restApi.getRestApiId(), this.region))
.build();
CfnOutput.Builder.create(this, "BooksURL")
.value(String.format("https://%s.execute-api.%s.amazonaws.com/prod/books", restApi.getRestApiId(), this.region))
.build();
}
}
public class ResourceNestedStackProps extends NestedStackProps {
private String restApiId;
public String getRestApiId() {
return this.restApiId;
}
public ResourceNestedStackProps restApiId(String restApiId) {
this.restApiId = restApiId;
return this;
}
private String rootResourceId;
public String getRootResourceId() {
return this.rootResourceId;
}
public ResourceNestedStackProps rootResourceId(String rootResourceId) {
this.rootResourceId = rootResourceId;
return this;
}
}
public class PetsStack extends NestedStack {
public final Method[] methods;
public PetsStack(Construct scope, ResourceNestedStackProps props) {
super(scope, "integ-restapi-import-PetsStack", props);
IRestApi api = RestApi.fromRestApiAttributes(this, "RestApi", RestApiAttributes.builder()
.restApiId(props.getRestApiId())
.rootResourceId(props.getRootResourceId())
.build());
Method method = api.root.addResource("pets").addMethod("GET", MockIntegration.Builder.create()
.integrationResponses(List.of(IntegrationResponse.builder()
.statusCode("200")
.build()))
.passthroughBehavior(PassthroughBehavior.NEVER)
.requestTemplates(Map.of(
"application/json", "{ \"statusCode\": 200 }"))
.build(), MethodOptions.builder()
.methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
.build());
this.methods.push(method);
}
}
public class BooksStack extends NestedStack {
public final Method[] methods;
public BooksStack(Construct scope, ResourceNestedStackProps props) {
super(scope, "integ-restapi-import-BooksStack", props);
IRestApi api = RestApi.fromRestApiAttributes(this, "RestApi", RestApiAttributes.builder()
.restApiId(props.getRestApiId())
.rootResourceId(props.getRootResourceId())
.build());
Method method = api.root.addResource("books").addMethod("GET", MockIntegration.Builder.create()
.integrationResponses(List.of(IntegrationResponse.builder()
.statusCode("200")
.build()))
.passthroughBehavior(PassthroughBehavior.NEVER)
.requestTemplates(Map.of(
"application/json", "{ \"statusCode\": 200 }"))
.build(), MethodOptions.builder()
.methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
.build());
this.methods.push(method);
}
}
public class DeployStackProps extends NestedStackProps {
private String restApiId;
public String getRestApiId() {
return this.restApiId;
}
public DeployStackProps restApiId(String restApiId) {
this.restApiId = restApiId;
return this;
}
private Method[] methods;
public Method[] getMethods() {
return this.methods;
}
public DeployStackProps methods(Method[] methods) {
this.methods = methods;
return this;
}
}
public class DeployStack extends NestedStack {
public DeployStack(Construct scope, DeployStackProps props) {
super(scope, "integ-restapi-import-DeployStack", props);
Deployment deployment = Deployment.Builder.create(this, "Deployment")
.api(RestApi.fromRestApiId(this, "RestApi", props.getRestApiId()))
.build();
if (props.getMethods()) {
for (Object method : props.getMethods()) {
deployment.node.addDependency(method);
}
}
Stage.Builder.create(this, "Stage").deployment(deployment).build();
}
}
new RootStack(new App());
Warning: In the code above, an API Gateway deployment is created during the initial CDK deployment. However, if there are changes to the resources in subsequent CDK deployments, a new API Gateway deployment is not automatically created. As a result, the latest state of the resources is not reflected. To ensure the latest state of the resources is reflected, a manual deployment of the API Gateway is required after the CDK deployment. See Controlled triggering of deployments for more info.
AWS Lambda-backed APIs
A very common practice is to use Amazon API Gateway with AWS Lambda as the
backend integration. The LambdaRestApi construct makes it easy:
The following code defines a REST API that routes all requests to the specified AWS Lambda function:
Function backend;
LambdaRestApi.Builder.create(this, "myapi")
.handler(backend)
.build();
You can also supply proxy: false, in which case you will have to explicitly
define the API model:
Function backend;
LambdaRestApi api = LambdaRestApi.Builder.create(this, "myapi")
.handler(backend)
.proxy(false)
.build();
Resource items = api.root.addResource("items");
items.addMethod("GET"); // GET /items
items.addMethod("POST"); // POST /items
Resource item = items.addResource("{item}");
item.addMethod("GET"); // GET /items/{item}
// the default integration for methods is "handler", but one can
// customize this behavior per method or even a sub path.
item.addMethod("DELETE", new HttpIntegration("http://amazon.com"));
Additionally, integrationOptions can be supplied to explicitly define
options of the Lambda integration:
Function backend;
LambdaRestApi api = LambdaRestApi.Builder.create(this, "myapi")
.handler(backend)
.integrationOptions(LambdaIntegrationOptions.builder()
.allowTestInvoke(false)
.timeout(Duration.seconds(1))
.build())
.build();
AWS StepFunctions backed APIs
You can use Amazon API Gateway with AWS Step Functions as the backend integration, specifically Synchronous Express Workflows.
The StepFunctionsRestApi only supports integration with Synchronous Express state machine. The StepFunctionsRestApi construct makes this easy by setting up input, output and error mapping.
The construct sets up an API endpoint and maps the ANY HTTP method and any calls to the API endpoint starts an express workflow execution for the underlying state machine.
Invoking the endpoint with any HTTP method (GET, POST, PUT, DELETE, ...) in the example below will send the request to the state machine as a new execution. On success, an HTTP code 200 is returned with the execution output as the Response Body.
If the execution fails, an HTTP 500 response is returned with the error and cause from the execution output as the Response Body. If the request is invalid (ex. bad execution input) HTTP code 400 is returned.
To disable default response models generation use the useDefaultMethodResponses property:
IStateMachine machine;
StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi")
.stateMachine(machine)
.useDefaultMethodResponses(false)
.build();
The response from the invocation contains only the output field from the
StartSyncExecution API.
In case of failures, the fields error and cause are returned as part of the response.
Other metadata such as billing details, AWS account ID and resource ARNs are not returned in the API response.
By default, a prod stage is provisioned.
In order to reduce the payload size sent to AWS Step Functions, headers are not forwarded to the Step Functions execution input. It is possible to choose whether headers, requestContext, path, querystring, and authorizer are included or not. By default, headers are excluded in all requests.
More details about AWS Step Functions payload limit can be found at https://docs.aws.amazon.com/step-functions/latest/dg/limits-overview.html#service-limits-task-executions.
The following code defines a REST API that routes all requests to the specified AWS StepFunctions state machine:
Pass stateMachineDefinition = new Pass(this, "PassState");
IStateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definition(stateMachineDefinition)
.stateMachineType(StateMachineType.EXPRESS)
.build();
StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi")
.deploy(true)
.stateMachine(stateMachine)
.build();
When the REST API endpoint configuration above is invoked using POST, as follows -
curl -X POST -d '{ "customerId": 1 }' https://example.com/
AWS Step Functions will receive the request body in its input as follows:
{
"body": {
"customerId": 1
},
"path": "/",
"querystring": {}
}
When the endpoint is invoked at path '/users/5' using the HTTP GET method as below:
curl -X GET https://example.com/users/5?foo=bar
AWS Step Functions will receive the following execution input:
{
"body": {},
"path": {
"users": "5"
},
"querystring": {
"foo": "bar"
}
}
Additional information around the request such as the request context, authorizer context, and headers can be included as part of the input forwarded to the state machine. The following example enables headers to be included in the input but not query string.
StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi")
.stateMachine(machine)
.headers(true)
.path(false)
.querystring(false)
.authorizer(false)
.requestContext(RequestContext.builder()
.caller(true)
.user(true)
.build())
.build();
In such a case, when the endpoint is invoked as below:
curl -X GET https://example.com/
AWS Step Functions will receive the following execution input:
{
"headers": {
"Accept": "...",
"CloudFront-Forwarded-Proto": "...",
},
"requestContext": {
"accountId": "...",
"apiKey": "...",
},
"body": {}
}
Integration Targets
Methods are associated with backend integrations, which are invoked when this method is called. API Gateway supports the following integrations:
MockIntegration- can be used to test APIs. This is the default integration if one is not specified.AwsIntegration- can be used to invoke arbitrary AWS service APIs.HttpIntegration- can be used to invoke HTTP endpoints.LambdaIntegration- can be used to invoke an AWS Lambda function.SagemakerIntegration- can be used to invoke Sagemaker Endpoints.
The following example shows how to integrate the GET /book/{book_id} method to
an AWS Lambda function:
Function getBookHandler;
Resource book;
LambdaIntegration getBookIntegration = new LambdaIntegration(getBookHandler);
book.addMethod("GET", getBookIntegration);
Integration options can be optionally be specified:
Function getBookHandler;
LambdaIntegration getBookIntegration;
LambdaIntegration getBookIntegration = LambdaIntegration.Builder.create(getBookHandler)
.contentHandling(ContentHandling.CONVERT_TO_TEXT) // convert to base64
.credentialsPassthrough(true)
.build();
Method options can optionally be specified when adding methods:
Resource book;
LambdaIntegration getBookIntegration;
book.addMethod("GET", getBookIntegration, MethodOptions.builder()
.authorizationType(AuthorizationType.IAM)
.apiKeyRequired(true)
.build());
It is possible to also integrate with AWS services in a different region. The following code integrates with Amazon SQS in the
eu-west-1 region.
AwsIntegration getMessageIntegration = AwsIntegration.Builder.create()
.service("sqs")
.path("queueName")
.region("eu-west-1")
.build();
Response Streaming
Integrations support response streaming, which allows responses to be streamed back to clients. This is useful for large payloads or when you want to start sending data before the entire response is ready.
To enable response streaming, set ResponseTransferMode.STREAM to the responseTransferMode option:
Function handler;
LambdaIntegration.Builder.create(handler)
.responseTransferMode(ResponseTransferMode.STREAM)
.build();
Lambda Integration Permissions
By default, creating a LambdaIntegration will add a permission for API Gateway to invoke your AWS Lambda function, scoped to the specific method which uses the integration.
If you reuse the same AWS Lambda function for many integrations, the AWS Lambda permission policy size can be exceeded by adding a separate policy statement for each method which invokes the AWS Lambda function. To avoid this, you can opt to scope permissions to any method on the API by setting scopePermissionToMethod to false, and this will ensure only a single policy statement is added to the AWS Lambda permission policy.
Resource book;
Function backend;
LambdaIntegration getBookIntegration = LambdaIntegration.Builder.create(backend)
.scopePermissionToMethod(false)
.build();
LambdaIntegration createBookIntegration = LambdaIntegration.Builder.create(backend)
.scopePermissionToMethod(false)
.build();
book.addMethod("GET", getBookIntegration);
book.addMethod("POST", createBookIntegration);
In the above example, a single permission is added, shared by both getBookIntegration and createBookIntegration.
Note that setting scopePermissionToMethod to false will always allow test invocations, no matter the value specified for allowTestInvoke.
Usage Plan & API Keys
A usage plan specifies who can access one or more deployed API stages and methods, and the rate at which they can be accessed. The plan uses API keys to identify API clients and meters access to the associated API stages for each key. Usage plans also allow configuring throttling limits and quota limits that are enforced on individual client API keys.
The following example shows how to create and associate a usage plan and an API key:
LambdaIntegration integration;
RestApi api = new RestApi(this, "hello-api");
Resource v1 = api.root.addResource("v1");
Resource echo = v1.addResource("echo");
Method echoMethod = echo.addMethod("GET", integration, MethodOptions.builder().apiKeyRequired(true).build());
UsagePlan plan = api.addUsagePlan("UsagePlan", UsagePlanProps.builder()
.name("Easy")
.throttle(ThrottleSettings.builder()
.rateLimit(10)
.burstLimit(2)
.build())
.build());
IApiKey key = api.addApiKey("ApiKey");
plan.addApiKey(key);
To associate a plan to a given RestAPI stage:
UsagePlan plan;
RestApi api;
Method echoMethod;
plan.addApiStage(UsagePlanPerApiStage.builder()
.stage(api.getDeploymentStage())
.throttle(List.of(ThrottlingPerMethod.builder()
.method(echoMethod)
.throttle(ThrottleSettings.builder()
.rateLimit(10)
.burstLimit(2)
.build())
.build()))
.build());
Existing usage plans can be imported into a CDK app using its id.
IUsagePlan importedUsagePlan = UsagePlan.fromUsagePlanId(this, "imported-usage-plan", "<usage-plan-key-id>");
The name and value of the API Key can be specified at creation; if not provided, a name and value will be automatically generated by API Gateway.
RestApi api;
IApiKey key = api.addApiKey("ApiKey", ApiKeyOptions.builder()
.apiKeyName("myApiKey1")
.value("MyApiKeyThatIsAtLeast20Characters")
.build());
Existing API keys can also be imported into a CDK app using its id.
IApiKey importedKey = ApiKey.fromApiKeyId(this, "imported-key", "<api-key-id>");
The "grant" methods can be used to give prepackaged sets of permissions to other resources. The following code provides read permission to an API key.
ApiKey importedKey; Function lambdaFn; importedKey.grantRead(lambdaFn);
Adding an API Key to an imported RestApi
API Keys are added to ApiGateway Stages, not to the API itself. When you import a RestApi it does not have any information on the Stages that may be associated with it. Since adding an API Key requires a stage, you should instead add the Api Key to the imported Stage.
IRestApi restApi;
IStage importedStage = Stage.fromStageAttributes(this, "imported-stage", StageAttributes.builder()
.stageName("myStageName")
.restApi(restApi)
.build());
importedStage.addApiKey("MyApiKey");
⚠️ Multiple API Keys
It is possible to specify multiple API keys for a given Usage Plan, by calling usagePlan.addApiKey().
When using multiple API keys, a past bug of the CDK prevents API key associations to a Usage Plan to be deleted.
If the CDK app had the feature flag - @aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId - enabled when the API
keys were created, then the app will not be affected by this bug.
If this is not the case, you will need to ensure that the CloudFormation logical ids of the API keys that are not
being deleted remain unchanged.
Make note of the logical ids of these API keys before removing any, and set it as part of the addApiKey() method:
UsagePlan usageplan;
ApiKey apiKey;
usageplan.addApiKey(apiKey, AddApiKeyOptions.builder()
.overrideLogicalId("...")
.build());
Rate Limited API Key
In scenarios where you need to create a single api key and configure rate limiting for it, you can use RateLimitedApiKey.
This construct lets you specify rate limiting properties which should be applied only to the api key being created.
The API key created has the specified rate limits, such as quota and throttles, applied.
The following example shows how to use a rate limited api key :
RestApi api;
RateLimitedApiKey key = RateLimitedApiKey.Builder.create(this, "rate-limited-api-key")
.customerId("hello-customer")
.apiStages(List.of(UsagePlanPerApiStage.builder().stage(api.getDeploymentStage()).build()))
.quota(QuotaSettings.builder()
.limit(10000)
.period(Period.MONTH)
.build())
.build();
Working with models
When you work with Lambda integrations that are not Proxy integrations, you have to define your models and mappings for the request, response, and integration.
Function hello = Function.Builder.create(this, "hello")
.runtime(Runtime.NODEJS_LATEST)
.handler("hello.handler")
.code(Code.fromAsset("lambda"))
.build();
RestApi api = RestApi.Builder.create(this, "hello-api").build();
Resource resource = api.root.addResource("v1");
You can define more parameters on the integration to tune the behavior of API Gateway
Function hello;
LambdaIntegration integration = LambdaIntegration.Builder.create(hello)
.proxy(false)
.requestParameters(Map.of(
// You can define mapping parameters from your method to your integration
// - Destination parameters (the key) are the integration parameters (used in mappings)
// - Source parameters (the value) are the source request parameters or expressions
// @see: https://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html
"integration.request.querystring.who", "method.request.querystring.who"))
.allowTestInvoke(true)
.requestTemplates(Map.of(
// You can define a mapping that will build a payload for your integration, based
// on the integration parameters that you have specified
// Check: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
"application/json", JSON.stringify(Map.of("action", "sayHello", "pollId", "$util.escapeJavaScript($input.params('who'))"))))
// This parameter defines the behavior of the engine is no suitable response template is found
.passthroughBehavior(PassthroughBehavior.NEVER)
.integrationResponses(List.of(IntegrationResponse.builder()
// Successful response from the Lambda function, no filter defined
// - the selectionPattern filter only tests the error message
// We will set the response status code to 200
.statusCode("200")
.responseTemplates(Map.of(
// This template takes the "message" result from the Lambda function, and embeds it in a JSON response
// Check https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
"application/json", JSON.stringify(Map.of("state", "ok", "greeting", "$util.escapeJavaScript($input.body)"))))
.responseParameters(Map.of(
// We can map response parameters
// - Destination parameters (the key) are the response parameters (used in mappings)
// - Source parameters (the value) are the integration response parameters or expressions
"method.response.header.Content-Type", "'application/json'",
"method.response.header.Access-Control-Allow-Origin", "'*'",
"method.response.header.Access-Control-Allow-Credentials", "'true'"))
.build(), IntegrationResponse.builder()
// For errors, we check if the error message is not empty, get the error data
.selectionPattern("(\n|.)+")
// We will set the response status code to 200
.statusCode("400")
.responseTemplates(Map.of(
"application/json", JSON.stringify(Map.of("state", "error", "message", "$util.escapeJavaScript($input.path('$.errorMessage'))"))))
.responseParameters(Map.of(
"method.response.header.Content-Type", "'application/json'",
"method.response.header.Access-Control-Allow-Origin", "'*'",
"method.response.header.Access-Control-Allow-Credentials", "'true'"))
.build()))
.build();
You can define models for your responses (and requests)
RestApi api;
// We define the JSON Schema for the transformed valid response
Model responseModel = api.addModel("ResponseModel", ModelOptions.builder()
.contentType("application/json")
.modelName("ResponseModel")
.schema(JsonSchema.builder()
.schema(JsonSchemaVersion.DRAFT4)
.title("pollResponse")
.type(JsonSchemaType.OBJECT)
.properties(Map.of(
"state", JsonSchema.builder().type(JsonSchemaType.STRING).build(),
"greeting", JsonSchema.builder().type(JsonSchemaType.STRING).build()))
.build())
.build());
// We define the JSON Schema for the transformed error response
Model errorResponseModel = api.addModel("ErrorResponseModel", ModelOptions.builder()
.contentType("application/json")
.modelName("ErrorResponseModel")
.schema(JsonSchema.builder()
.schema(JsonSchemaVersion.DRAFT4)
.title("errorResponse")
.type(JsonSchemaType.OBJECT)
.properties(Map.of(
"state", JsonSchema.builder().type(JsonSchemaType.STRING).build(),
"message", JsonSchema.builder().type(JsonSchemaType.STRING).build()))
.build())
.build());
And reference all on your method definition.
LambdaIntegration integration;
Resource resource;
Model responseModel;
Model errorResponseModel;
resource.addMethod("GET", integration, MethodOptions.builder()
// We can mark the parameters as required
.requestParameters(Map.of(
"method.request.querystring.who", true))
// we can set request validator options like below
.requestValidatorOptions(RequestValidatorOptions.builder()
.requestValidatorName("test-validator")
.validateRequestBody(true)
.validateRequestParameters(false)
.build())
.methodResponses(List.of(MethodResponse.builder()
// Successful response from the integration
.statusCode("200")
// Define what parameters are allowed or not
.responseParameters(Map.of(
"method.response.header.Content-Type", true,
"method.response.header.Access-Control-Allow-Origin", true,
"method.response.header.Access-Control-Allow-Credentials", true))
// Validate the schema on the response
.responseModels(Map.of(
"application/json", responseModel))
.build(), MethodResponse.builder()
// Same thing for the error responses
.statusCode("400")
.responseParameters(Map.of(
"method.response.header.Content-Type", true,
"method.response.header.Access-Control-Allow-Origin", true,
"method.response.header.Access-Control-Allow-Credentials", true))
.responseModels(Map.of(
"application/json", errorResponseModel))
.build()))
.build());
Specifying requestValidatorOptions automatically creates the RequestValidator construct with the given options.
However, if you have your RequestValidator already initialized or imported, use the requestValidator option instead.
If you want to use requestValidatorOptions in multiple addMethod() calls
then you need to set the @aws-cdk/aws-apigateway:requestValidatorUniqueId
feature flag. When this feature flag is set, each RequestValidator will have a unique generated id.
Note if you enable this feature flag when you have already used
addMethod()withrequestValidatorOptionsthe Logical Id of the resource will change causing the resource to be replaced.
LambdaIntegration integration;
Resource resource;
Model responseModel;
Model errorResponseModel;
resource.node.setContext("@aws-cdk/aws-apigateway:requestValidatorUniqueId", true);
resource.addMethod("GET", integration, MethodOptions.builder()
// we can set request validator options like below
.requestValidatorOptions(RequestValidatorOptions.builder()
.requestValidatorName("test-validator")
.validateRequestBody(true)
.validateRequestParameters(false)
.build())
.build());
resource.addMethod("POST", integration, MethodOptions.builder()
// we can set request validator options like below
.requestValidatorOptions(RequestValidatorOptions.builder()
.requestValidatorName("test-validator2")
.validateRequestBody(true)
.validateRequestParameters(false)
.build())
.build());
Default Integration and Method Options
The defaultIntegration and defaultMethodOptions properties can be used to
configure a default integration at any resource level. These options will be
used when defining method under this resource (recursively) with undefined
integration or options.
If not defined, the default integration is
MockIntegration. See reference documentation for default method options.
The following example defines the booksBackend integration as a default
integration. This means that all API methods that do not explicitly define an
integration will be routed to this AWS Lambda function.
LambdaIntegration booksBackend;
RestApi api = RestApi.Builder.create(this, "books")
.defaultIntegration(booksBackend)
.build();
Resource books = api.root.addResource("books");
books.addMethod("GET"); // integrated with `booksBackend`
books.addMethod("POST"); // integrated with `booksBackend`
Resource book = books.addResource("{book_id}");
book.addMethod("GET");
A Method can be configured with authorization scopes. Authorization scopes are used in conjunction with an authorizer that uses Amazon Cognito user pools. Read more about authorization scopes here.
Authorization scopes for a Method can be configured using the authorizationScopes property as shown below -
Resource books;
books.addMethod("GET", new HttpIntegration("http://amazon.com"), MethodOptions.builder()
.authorizationType(AuthorizationType.COGNITO)
.authorizationScopes(List.of("Scope1", "Scope2"))
.build());
Proxy Routes
The addProxy method can be used to install a greedy {proxy+} resource
on a path. By default, this also installs an "ANY" method:
Resource resource;
Function handler;
ProxyResource proxy = resource.addProxy(ProxyResourceOptions.builder()
.defaultIntegration(new LambdaIntegration(handler))
// "false" will require explicitly adding methods on the `proxy` resource
.anyMethod(true)
.build());
Authorizers
API Gateway supports several different authorization types that can be used for controlling access to your REST APIs.
IAM-based authorizer
The following CDK code provides 'execute-api' permission to an IAM user, via IAM policies, for the 'GET' method on the books resource:
Resource books;
User iamUser;
Method getBooks = books.addMethod("GET", new HttpIntegration("http://amazon.com"), MethodOptions.builder()
.authorizationType(AuthorizationType.IAM)
.build());
iamUser.attachInlinePolicy(Policy.Builder.create(this, "AllowBooks")
.statements(List.of(
PolicyStatement.Builder.create()
.actions(List.of("execute-api:Invoke"))
.effect(Effect.ALLOW)
.resources(List.of(getBooks.getMethodArn()))
.build()))
.build());
Lambda-based token authorizer
API Gateway also allows lambda functions to be used as authorizers.
This module provides support for token-based Lambda authorizers. When a client makes a request to an API's methods configured with such an authorizer, API Gateway calls the 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.
API Gateway interacts with the authorizer Lambda function handler by passing input and expecting the output in a specific format.
The event object that the handler is called with contains the authorizationToken and the methodArn from the request to the
API Gateway endpoint. The handler is expected to return the principalId (i.e. the client identifier) and a policyDocument stating
what the client is authorizer to perform.
See here for a detailed specification on
inputs and outputs of the Lambda handler.
The following code attaches a token-based Lambda authorizer to the 'GET' Method of the Book resource:
Function authFn;
Resource books;
TokenAuthorizer auth = TokenAuthorizer.Builder.create(this, "booksAuthorizer")
.handler(authFn)
.build();
books.addMethod("GET", new HttpIntegration("http://amazon.com"), MethodOptions.builder()
.authorizer(auth)
.build());
A full working example is shown below.
public class MyStack extends Stack {
public MyStack(Construct scope, String id) {
super(scope, id);
Function authorizerFn = Function.Builder.create(this, "MyAuthorizerFunction")
.runtime(Runtime.NODEJS_LATEST)
.handler("index.handler")
.code(AssetCode.fromAsset(join(__dirname, "integ.token-authorizer.handler")))
.build();
TokenAuthorizer authorizer = TokenAuthorizer.Builder.create(this, "MyAuthorizer")
.handler(authorizerFn)
.build();
RestApi restapi = RestApi.Builder.create(this, "MyRestApi")
.cloudWatchRole(true)
.defaultMethodOptions(MethodOptions.builder()
.authorizer(authorizer)
.build())
.defaultCorsPreflightOptions(CorsOptions.builder()
.allowOrigins(Cors.ALL_ORIGINS)
.build())
.build();
restapi.root.addMethod("ANY", MockIntegration.Builder.create()
.integrationResponses(List.of(IntegrationResponse.builder().statusCode("200").build()))
.passthroughBehavior(PassthroughBehavior.NEVER)
.requestTemplates(Map.of(
"application/json", "{ \"statusCode\": 200 }"))
.build(), MethodOptions.builder()
.methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
.build());
}
}
By default, the TokenAuthorizer looks for the authorization token in the request header with the key 'Authorization'. This can,
however, be modified by changing the identitySource property.
Authorizers can also be passed via the defaultMethodOptions property within the RestApi construct or the Method construct. Unless
explicitly overridden, the specified defaults will be applied across all Methods across the RestApi or across all Resources,
depending on where the defaults were specified.
Lambda-based request authorizer
This module provides support for request-based Lambda authorizers. When a client makes a request to an API's methods configured with such an authorizer, API Gateway calls the Lambda authorizer, which takes specified parts of the request, known as identity sources, as input and returns an IAM policy as output. A request-based Lambda authorizer (also called a request authorizer) receives the identity sources in a series of values pulled from the request, from the headers, stage variables, query strings, and the context.
API Gateway interacts with the authorizer Lambda function handler by passing input and expecting the output in a specific format.
The event object that the handler is called with contains the body of the request and the methodArn from the request to the
API Gateway endpoint. The handler is expected to return the principalId (i.e. the client identifier) and a policyDocument stating
what the client is authorizer to perform.
See here for a detailed specification on
inputs and outputs of the Lambda handler.
The following code attaches a request-based Lambda authorizer to the 'GET' Method of the Book resource:
Function authFn;
Resource books;
RequestAuthorizer auth = RequestAuthorizer.Builder.create(this, "booksAuthorizer")
.handler(authFn)
.identitySources(List.of(IdentitySource.header("Authorization")))
.build();
books.addMethod("GET", new HttpIntegration("http://amazon.com"), MethodOptions.builder()
.authorizer(auth)
.build());
A full working example is shown below.
import path.*;
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.services.apigateway.MockIntegration;
import software.amazon.awscdk.services.apigateway.PassthroughBehavior;
import software.amazon.awscdk.services.apigateway.RestApi;
import software.amazon.awscdk.services.apigateway.RequestAuthorizer;
import software.amazon.awscdk.services.apigateway.IdentitySource;
// Against the RestApi endpoint from the stack output, run
// `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>?allow=yes` should return 403
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>?allow=yes` should return 200
App app = new App();
Stack stack = new Stack(app, "RequestAuthorizerInteg");
Function authorizerFn = Function.Builder.create(stack, "MyAuthorizerFunction")
.runtime(Runtime.NODEJS_LATEST)
.handler("index.handler")
.code(AssetCode.fromAsset(join(__dirname, "integ.request-authorizer.handler")))
.build();
RestApi restapi = RestApi.Builder.create(stack, "MyRestApi").cloudWatchRole(true).build();
RequestAuthorizer authorizer = RequestAuthorizer.Builder.create(stack, "MyAuthorizer")
.handler(authorizerFn)
.identitySources(List.of(IdentitySource.header("Authorization"), IdentitySource.queryString("allow")))
.build();
RequestAuthorizer secondAuthorizer = RequestAuthorizer.Builder.create(stack, "MySecondAuthorizer")
.handler(authorizerFn)
.identitySources(List.of(IdentitySource.header("Authorization"), IdentitySource.queryString("allow")))
.build();
restapi.root.addMethod("ANY", MockIntegration.Builder.create()
.integrationResponses(List.of(IntegrationResponse.builder().statusCode("200").build()))
.passthroughBehavior(PassthroughBehavior.NEVER)
.requestTemplates(Map.of(
"application/json", "{ \"statusCode\": 200 }"))
.build(), MethodOptions.builder()
.methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
.authorizer(authorizer)
.build());
restapi.root.resourceForPath("auth").addMethod("ANY", MockIntegration.Builder.create()
.integrationResponses(List.of(IntegrationResponse.builder().statusCode("200").build()))
.passthroughBehavior(PassthroughBehavior.NEVER)
.requestTemplates(Map.of(
"application/json", "{ \"statusCode\": 200 }"))
.build(), MethodOptions.builder()
.methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
.authorizer(secondAuthorizer)
.build());
By default, the RequestAuthorizer does not pass any kind of information from the request. This can,
however, be modified by changing the identitySource property, and is required when specifying a value for caching.
Authorizers can also be passed via the defaultMethodOptions property within the RestApi construct or the Method construct. Unless
explicitly overridden, the specified defaults will be applied across all Methods across the RestApi or across all Resources,
depending on where the defaults were specified.
Cognito User Pools authorizer
API Gateway also allows Amazon Cognito user pools as authorizer
The following snippet configures a Cognito user pool as an authorizer:
Resource books;
UserPool userPool = new UserPool(this, "UserPool");
CognitoUserPoolsAuthorizer auth = CognitoUserPoolsAuthorizer.Builder.create(this, "booksAuthorizer")
.cognitoUserPools(List.of(userPool))
.build();
books.addMethod("GET", new HttpIntegration("http://amazon.com"), MethodOptions.builder()
.authorizer(auth)
.authorizationType(AuthorizationType.COGNITO)
.build());
Mutual TLS (mTLS)
Mutual TLS can be configured to limit access to your API based by using client certificates instead of (or as an extension of) using authorization headers.
Object acm;
DomainName.Builder.create(this, "domain-name")
.domainName("example.com")
.certificate(acm.Certificate.fromCertificateArn(this, "cert", "arn:aws:acm:us-east-1:1111111:certificate/11-3336f1-44483d-adc7-9cd375c5169d"))
.mtls(MTLSConfig.builder()
.bucket(new Bucket(this, "bucket"))
.key("truststore.pem")
.version("version")
.build())
.build();
Instructions for configuring your trust store can be found here.
Deployments
By default, the RestApi construct will automatically create an API Gateway
Deployment and a "prod" Stage which represent the API configuration you
defined in your CDK app. This means that when you deploy your app, your API will
have open access from the internet via the stage URL.
The URL of your API can be obtained from the attribute restApi.url, and is
also exported as an Output from your stack, so it's printed when you cdk deploy your app:
$ cdk deploy ... books.booksapiEndpointE230E8D5 = https://6lyktd4lpk.execute-api.us-east-1.amazonaws.com/prod/
To disable this behavior, you can set { deploy: false } when creating your
API. This means that the API will not be deployed and a stage will not be
created for it. You will need to manually define a apigateway.Deployment and
apigateway.Stage resources.
Use the deployOptions property to customize the deployment options of your
API.
The following example will configure API Gateway to emit logs and data traces to AWS CloudWatch for all API calls:
Note: whether or not this is enabled or disabled by default is controlled by the
@aws-cdk/aws-apigateway:disableCloudWatchRolefeature flag. When this feature flag is set tofalsethe default behavior will setcloudWatchRole=true
This is controlled via the @aws-cdk/aws-apigateway:disableCloudWatchRole feature flag and
is disabled by default. When enabled (or @aws-cdk/aws-apigateway:disableCloudWatchRole=false),
an IAM role will be created and associated with API Gateway to allow it to write logs and metrics to AWS CloudWatch.
RestApi api = RestApi.Builder.create(this, "books")
.cloudWatchRole(true)
.deployOptions(StageOptions.builder()
.loggingLevel(MethodLoggingLevel.INFO)
.dataTraceEnabled(true)
.build())
.build();
Note: there can only be a single apigateway.CfnAccount per AWS environment so if you create multiple
RestApis withcloudWatchRole=trueeach newRestApiwill overwrite theCfnAccount. It is recommended to setcloudWatchRole=false(the default behavior if@aws-cdk/aws-apigateway:disableCloudWatchRoleis enabled) and only create a single CloudWatch role and account per environment.
You can specify the CloudWatch Role and Account sub-resources removal policy with the
cloudWatchRoleRemovalPolicy property, which defaults to RemovalPolicy.RETAIN.
This option requires cloudWatchRole to be enabled.
import software.amazon.awscdk.*;
RestApi api = RestApi.Builder.create(this, "books")
.cloudWatchRole(true)
.cloudWatchRoleRemovalPolicy(RemovalPolicy.DESTROY)
.build();
Deploying to an existing stage
Using RestApi
If you want to use an existing stage to deploy your RestApi, first set { deploy: false } so the construct doesn't automatically create new Deployment and Stage resources. Then you can manually define a apigateway.Deployment resource and specify the stage name for your existing stage using the stageName property.
Note that as long as the deployment's logical ID doesn't change, it will represent the snapshot in time when the resource was created. To ensure your deployment reflects changes to the RestApi model, see Controlled triggering of deployments.
RestApi restApi = RestApi.Builder.create(this, "my-rest-api")
.deploy(false)
.build();
// Use `stageName` to deploy to an existing stage
Deployment deployment = Deployment.Builder.create(this, "my-deployment")
.api(restApi)
.stageName("dev")
.retainDeployments(true)
.build();
Using SpecRestApi
If you want to use an existing stage to deploy your SpecRestApi, first set { deploy: false } so the construct doesn't automatically create new Deployment and Stage resources. Then you can manually define a apigateway.Deployment resource and specify the stage name for your existing stage using the stageName property.
To automatically create a new deployment that reflects the latest API changes, you can use the addToLogicalId() method and pass in your OpenAPI definition.
AssetApiDefinition myApiDefinition = ApiDefinition.fromAsset("path-to-file.json");
SpecRestApi specRestApi = SpecRestApi.Builder.create(this, "my-specrest-api")
.deploy(false)
.apiDefinition(myApiDefinition)
.build();
// Use `stageName` to deploy to an existing stage
Deployment deployment = Deployment.Builder.create(this, "my-deployment")
.api(specRestApi)
.stageName("dev")
.retainDeployments(true)
.build();
// Trigger a new deployment on OpenAPI definition updates
deployment.addToLogicalId(myApiDefinition);
Note: If the
stageNameproperty is set but a stage with the corresponding name does not exist, a new stage resource will be created with the provided stage name.
Note: If you update the
stageNameproperty, you should be triggering a new deployment (i.e. with an updated logical ID and API changes). Otherwise, an error will occur during deployment.
Controlled triggering of deployments
By default, the RestApi construct deploys changes immediately. If you want to
control when deployments happen, set { deploy: false } and create a Deployment construct yourself. Add a revision counter to the construct ID, and update it in your source code whenever you want to trigger a new deployment:
RestApi restApi = RestApi.Builder.create(this, "my-api")
.deploy(false)
.build();
Number deploymentRevision = 5; // Bump this counter to trigger a new deployment
// Bump this counter to trigger a new deployment
Deployment.Builder.create(this, String.format("Deployment%s", deploymentRevision))
.api(restApi)
.build();
Deep dive: Invalidation of deployments
API Gateway deployments are an immutable snapshot of the API. This means that we want to automatically create a new deployment resource every time the API model defined in our CDK app changes.
In order to achieve that, the AWS CloudFormation logical ID of the
AWS::ApiGateway::Deployment resource is dynamically calculated by hashing the
API configuration (resources, methods). This means that when the configuration
changes (i.e. a resource or method are added, configuration is changed), a new
logical ID will be assigned to the deployment resource. This will cause
CloudFormation to create a new deployment resource.
By default, old deployments are deleted. You can set retainDeployments: true
to allow users revert the stage to an old deployment manually.
In order to also create a new deployment when changes are made to any authorizer attached to the API,
the @aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId feature flag can be enabled. This can be set
in the cdk.json file.
{
"context": {
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true
}
}
Custom Domains
To associate an API with a custom domain, use the domainName configuration when
you define your API:
Object acmCertificateForExampleCom;
RestApi api = RestApi.Builder.create(this, "MyDomain")
.domainName(DomainNameOptions.builder()
.domainName("example.com")
.certificate(acmCertificateForExampleCom)
.build())
.build();
This will define a DomainName resource for you, along with a BasePathMapping
from the root of the domain to the deployment stage of the API. This is a common
set up.
To route domain traffic to an API Gateway API, use Amazon Route 53 to create an
alias record. An alias record is a Route 53 extension to DNS. It's similar to a
CNAME record, but you can create an alias record both for the root domain, such
as example.com, and for subdomains, such as www.example.com. (You can create
CNAME records only for subdomains.)
import software.amazon.awscdk.services.route53.*;
import software.amazon.awscdk.services.route53.targets.*;
RestApi api;
Object hostedZoneForExampleCom;
ARecord.Builder.create(this, "CustomDomainAliasRecord")
.zone(hostedZoneForExampleCom)
.target(RecordTarget.fromAlias(new ApiGateway(api)))
.build();
You can also define a DomainName resource directly in order to customize the default behavior:
Object acmCertificateForExampleCom;
DomainName.Builder.create(this, "custom-domain")
.domainName("example.com")
.certificate(acmCertificateForExampleCom)
.endpointType(EndpointType.EDGE) // default is REGIONAL
.securityPolicy(SecurityPolicy.TLS_1_2)
.build();
Once you have a domain, you can map base paths of the domain to APIs.
The following example will map the URL https://example.com/go-to-api1
to the api1 API and https://example.com/boom to the api2 API.
DomainName domain;
RestApi api1;
RestApi api2;
domain.addBasePathMapping(api1, BasePathMappingOptions.builder().basePath("go-to-api1").build());
domain.addBasePathMapping(api2, BasePathMappingOptions.builder().basePath("boom").build());
By default, the base path URL will map to the deploymentStage of the RestApi.
You can specify a different API Stage to which the base path URL will map to.
DomainName domain;
RestApi restapi;
Deployment betaDeploy = Deployment.Builder.create(this, "beta-deployment")
.api(restapi)
.build();
Stage betaStage = Stage.Builder.create(this, "beta-stage")
.deployment(betaDeploy)
.build();
domain.addBasePathMapping(restapi, BasePathMappingOptions.builder().basePath("api/beta").stage(betaStage).build());
It is possible to create a base path mapping without associating it with a
stage by using the attachToStage property. When set to false, the stage must be
included in the URL when invoking the API. For example,
https://example.com/myapi/prod will invoke the stage named prod from the
myapi base path mapping.
DomainName domain;
RestApi api;
domain.addBasePathMapping(api, BasePathMappingOptions.builder().basePath("myapi").attachToStage(false).build());
If you don't specify basePath, all URLs under this domain will be mapped
to the API, and you won't be able to map another API to the same domain:
DomainName domain; RestApi api; domain.addBasePathMapping(api);
This can also be achieved through the mapping configuration when defining the
domain as demonstrated above.
Base path mappings can also be created with the BasePathMapping resource.
RestApi api;
IDomainName domainName = DomainName.fromDomainNameAttributes(this, "DomainName", DomainNameAttributes.builder()
.domainName("domainName")
.domainNameAliasHostedZoneId("domainNameAliasHostedZoneId")
.domainNameAliasTarget("domainNameAliasTarget")
.build());
BasePathMapping.Builder.create(this, "BasePathMapping")
.domainName(domainName)
.restApi(api)
.build();
If you wish to setup this domain with an Amazon Route53 alias, use the targets.ApiGatewayDomain:
Object hostedZoneForExampleCom;
DomainName domainName;
import software.amazon.awscdk.services.route53.*;
import software.amazon.awscdk.services.route53.targets.*;
ARecord.Builder.create(this, "CustomDomainAliasRecord")
.zone(hostedZoneForExampleCom)
.target(RecordTarget.fromAlias(new ApiGatewayDomain(domainName)))
.build();
Custom Domains with multi-level api mapping
Additional requirements for creating multi-level path mappings for RestApis:
(both are defaults)
- Must use
SecurityPolicy.TLS_1_2 - DomainNames must be
EndpointType.REGIONAL
Object acmCertificateForExampleCom;
RestApi restApi;
DomainName.Builder.create(this, "custom-domain")
.domainName("example.com")
.certificate(acmCertificateForExampleCom)
.mapping(restApi)
.basePath("orders/v1/api")
.build();
To then add additional mappings to a domain you can use the addApiMapping method.
Object acmCertificateForExampleCom;
RestApi restApi;
RestApi secondRestApi;
DomainName domain = DomainName.Builder.create(this, "custom-domain")
.domainName("example.com")
.certificate(acmCertificateForExampleCom)
.mapping(restApi)
.build();
domain.addApiMapping(secondRestApi.getDeploymentStage(), ApiMappingOptions.builder()
.basePath("orders/v2/api")
.build());
Access Logging
Access logging creates logs every time an API method is accessed. Access logs can have information on who has accessed the API, how the caller accessed the API and what responses were generated. Access logs are configured on a Stage of the RestApi. Access logs can be expressed in a format of your choosing, and can contain any access details, with a minimum that it must include either 'requestId' or 'extendedRequestId'. The list of variables that can be expressed in the access log can be found here. Read more at Setting Up CloudWatch API Logging in API Gateway
// production stage
LogGroup prodLogGroup = new LogGroup(this, "PrdLogs");
RestApi api = RestApi.Builder.create(this, "books")
.deployOptions(StageOptions.builder()
.accessLogDestination(new LogGroupLogDestination(prodLogGroup))
.accessLogFormat(AccessLogFormat.jsonWithStandardFields())
.build())
.build();
Deployment deployment = Deployment.Builder.create(this, "Deployment").api(api).build();
// development stage
LogGroup devLogGroup = new LogGroup(this, "DevLogs");
Stage.Builder.create(this, "dev")
.deployment(deployment)
.accessLogDestination(new LogGroupLogDestination(devLogGroup))
.accessLogFormat(AccessLogFormat.jsonWithStandardFields(JsonWithStandardFieldProps.builder()
.caller(false)
.httpMethod(true)
.ip(true)
.protocol(true)
.requestTime(true)
.resourcePath(true)
.responseLength(true)
.status(true)
.user(true)
.build()))
.build();
The following code will generate the access log in the CLF format.
LogGroup logGroup = new LogGroup(this, "ApiGatewayAccessLogs");
RestApi api = RestApi.Builder.create(this, "books")
.deployOptions(StageOptions.builder()
.accessLogDestination(new LogGroupLogDestination(logGroup))
.accessLogFormat(AccessLogFormat.clf())
.build())
.build();
You can also configure your own access log format by using the AccessLogFormat.custom() API.
AccessLogField provides commonly used fields. The following code configures access log to contain.
LogGroup logGroup = new LogGroup(this, "ApiGatewayAccessLogs");
RestApi.Builder.create(this, "books")
.deployOptions(StageOptions.builder()
.accessLogDestination(new LogGroupLogDestination(logGroup))
.accessLogFormat(AccessLogFormat.custom(String.format("%s %s %s%n %s %s", AccessLogField.contextRequestId(), AccessLogField.contextErrorMessage(), AccessLogField.contextErrorMessageString(), AccessLogField.contextAuthorizerError(), AccessLogField.contextAuthorizerIntegrationStatus())))
.build())
.build();
You can use the methodOptions property to configure
default method throttling
for a stage. The following snippet configures the a stage that accepts
100 requests per minute, allowing burst up to 200 requests per minute.
RestApi api = new RestApi(this, "books");
Deployment deployment = Deployment.Builder.create(this, "my-deployment").api(api).build();
Stage stage = Stage.Builder.create(this, "my-stage")
.deployment(deployment)
.methodOptions(Map.of(
"/*/*", MethodDeploymentOptions.builder() // This special path applies to all resource paths and all HTTP methods
.throttlingRateLimit(100)
.throttlingBurstLimit(200).build()))
.build();
Configuring methodOptions on the deployOptions of RestApi will set the
throttling behaviors on the default stage that is automatically created.
RestApi api = RestApi.Builder.create(this, "books")
.deployOptions(StageOptions.builder()
.methodOptions(Map.of(
"/*/*", MethodDeploymentOptions.builder() // This special path applies to all resource paths and all HTTP methods
.throttlingRateLimit(100)
.throttlingBurstLimit(1000).build()))
.build())
.build();
To write access log files to a Firehose delivery stream destination use the FirehoseLogDestination class:
Bucket destinationBucket = new Bucket(this, "Bucket");
Role deliveryStreamRole = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("firehose.amazonaws.com"))
.build();
CfnDeliveryStream stream = CfnDeliveryStream.Builder.create(this, "MyStream")
.deliveryStreamName("amazon-apigateway-delivery-stream")
.s3DestinationConfiguration(S3DestinationConfigurationProperty.builder()
.bucketArn(destinationBucket.getBucketArn())
.roleArn(deliveryStreamRole.getRoleArn())
.build())
.build();
RestApi api = RestApi.Builder.create(this, "books")
.deployOptions(StageOptions.builder()
.accessLogDestination(new FirehoseLogDestination(stream))
.accessLogFormat(AccessLogFormat.jsonWithStandardFields())
.build())
.build();
Note: The delivery stream name must start with amazon-apigateway-.
Visit Logging API calls to Amazon Data Firehose for more details.
Cross Origin Resource Sharing (CORS)
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.
You can add the CORS preflight OPTIONS
HTTP method to any API resource via the defaultCorsPreflightOptions option or by calling the addCorsPreflight on a specific resource.
The following example will enable CORS for all methods and all origins on all resources of the API:
RestApi.Builder.create(this, "api")
.defaultCorsPreflightOptions(CorsOptions.builder()
.allowOrigins(Cors.ALL_ORIGINS)
.allowMethods(Cors.ALL_METHODS)
.build())
.build();
The following example will add an OPTIONS method to the myResource API resource, which
only allows GET and PUT HTTP requests from the origin https://amazon.com.
Resource myResource;
myResource.addCorsPreflight(CorsOptions.builder()
.allowOrigins(List.of("https://amazon.com"))
.allowMethods(List.of("GET", "PUT"))
.build());
See the
CorsOptions
API reference for a detailed list of supported configuration options.
You can specify defaults this at the resource level, in which case they will be applied to the entire resource sub-tree:
Resource resource;
Resource subtree = resource.addResource("subtree", ResourceOptions.builder()
.defaultCorsPreflightOptions(CorsOptions.builder()
.allowOrigins(List.of("https://amazon.com"))
.build())
.build());
This means that all resources under subtree (inclusive) will have a preflight
OPTIONS added to them.
See #906 for a list of CORS features which are not yet supported.
Endpoint Configuration
API gateway allows you to specify an
API Endpoint Type.
To define an endpoint type for the API gateway, use endpointConfiguration property:
RestApi api = RestApi.Builder.create(this, "api")
.endpointConfiguration(EndpointConfiguration.builder()
.types(List.of(EndpointType.EDGE))
.build())
.build();
You can also configure endpoint IP address type.
The default value is IpAddressType.DUAL_STACK for private API, and IpAddressType.IPV4 for regional and edge-optimized API.
RestApi api = RestApi.Builder.create(this, "api")
.endpointConfiguration(EndpointConfiguration.builder()
.types(List.of(EndpointType.REGIONAL))
.ipAddressType(IpAddressType.DUAL_STACK)
.build())
.build();
Note: If creating a private API, the IPV4 IP address type is not supported.
You can also create an association between your Rest API and a VPC endpoint. By doing so, API Gateway will generate a new Route53 Alias DNS record which you can use to invoke your private APIs. More info can be found here.
Here is an example:
IVpcEndpoint someEndpoint;
RestApi api = RestApi.Builder.create(this, "api")
.endpointConfiguration(EndpointConfiguration.builder()
.types(List.of(EndpointType.PRIVATE))
.vpcEndpoints(List.of(someEndpoint))
.build())
.build();
By performing this association, we can invoke the API gateway using the following format:
https://{rest-api-id}-{vpce-id}.execute-api.{region}.amazonaws.com/{stage}
To restrict access to the API Gateway to only the VPC endpoint, you can use the grantInvokeFromVpcEndpointsOnly method to add resource policies to the API Gateway:
IVpcEndpoint apiGwVpcEndpoint;
RestApi api = RestApi.Builder.create(this, "PrivateApi")
.endpointConfiguration(EndpointConfiguration.builder()
.types(List.of(EndpointType.PRIVATE))
.vpcEndpoints(List.of(apiGwVpcEndpoint))
.build())
.build();
api.grantInvokeFromVpcEndpointsOnly(List.of(apiGwVpcEndpoint));
Private Integrations
A private integration makes it simple to expose HTTP/HTTPS resources behind an
Amazon VPC for access by clients outside of the VPC. The private integration uses
an API Gateway resource of VpcLink to encapsulate connections between API
Gateway and targeted VPC resources.
The VpcLink is then attached to the Integration of a specific API Gateway
Method. The following code sets up a private integration with a network load
balancer -
import software.amazon.awscdk.services.elasticloadbalancingv2.*;
Vpc vpc = new Vpc(this, "VPC");
NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "NLB")
.vpc(vpc)
.build();
VpcLink link = VpcLink.Builder.create(this, "link")
.targets(List.of(nlb))
.build();
Integration integration = Integration.Builder.create()
.type(IntegrationType.HTTP_PROXY)
.integrationHttpMethod("ANY")
.options(IntegrationOptions.builder()
.connectionType(ConnectionType.VPC_LINK)
.vpcLink(link)
.build())
.build();
The uri for the private integration, in the case of a VpcLink, will be set to the DNS name of
the VPC Link's NLB. If the VPC Link has multiple NLBs or the VPC Link is imported or the DNS
name cannot be determined for any other reason, the user is expected to specify the uri
property.
Any existing VpcLink resource can be imported into the CDK app via the VpcLink.fromVpcLinkId().
IVpcLink awesomeLink = VpcLink.fromVpcLinkId(this, "awesome-vpc-link", "us-east-1_oiuR12Abd");
Gateway response
If the Rest API fails to process an incoming request, it returns to the client an error response without forwarding the request to the integration backend. API Gateway has a set of standard response messages that are sent to the client for each type of error. These error responses can be configured on the Rest API. The list of Gateway responses that can be configured can be found here. Learn more about Gateway Responses.
The following code configures a Gateway Response when the response is 'access denied':
RestApi api = new RestApi(this, "books-api");
api.addGatewayResponse("test-response", GatewayResponseOptions.builder()
.type(ResponseType.ACCESS_DENIED)
.statusCode("500")
.responseHeaders(Map.of(
// Note that values must be enclosed within a pair of single quotes
"Access-Control-Allow-Origin", "'test.com'",
"test-key", "'test-value'"))
.templates(Map.of(
"application/json", "{ \"message\": $context.error.messageString, \"statusCode\": \"488\", \"type\": \"$context.error.responseType\" }"))
.build());
OpenAPI Definition
CDK supports creating a REST API by importing an OpenAPI definition file. It currently supports OpenAPI v2.0 and OpenAPI v3.0 definition files. Read more about Configuring a REST API using OpenAPI.
The following code creates a REST API using an external OpenAPI definition JSON file -
Integration integration;
SpecRestApi api = SpecRestApi.Builder.create(this, "books-api")
.apiDefinition(ApiDefinition.fromAsset("path-to-file.json"))
.build();
Resource booksResource = api.root.addResource("books");
booksResource.addMethod("GET", integration);
It is possible to use the addResource() API to define additional API Gateway Resources.
Note: Deployment will fail if a Resource of the same name is already defined in the Open API specification.
Note: Any default properties configured, such as defaultIntegration, defaultMethodOptions, etc. will only be
applied to Resources and Methods defined in the CDK, and not the ones defined in the spec. Use the API Gateway
extensions to OpenAPI
to configure these.
There are a number of limitations in using OpenAPI definitions in API Gateway. Read the Amazon API Gateway important notes for REST APIs for more details.
Note: When starting off with an OpenAPI definition using SpecRestApi, it is not possible to configure some
properties that can be configured directly in the OpenAPI specification file. This is to prevent people duplication
of these properties and potential confusion.
However, you can control how API Gateway handles resource updates using the mode property. Valid values are:
overwrite- The new API definition replaces the existing one. The existing API identifier remains unchanged.merge- The new API definition is merged with the existing API.
If you don't specify this property, a default value is chosen:
- For REST APIs created before March 29, 2021, the default is
overwrite - For REST APIs created after March 29, 2021, the new API definition takes precedence, but any container types such as endpoint configurations and binary media types are merged with the existing API.
Use the default mode to define top-level RestApi properties in addition to using OpenAPI. Generally, it's preferred to use API Gateway's OpenAPI extensions to model these properties.
SpecRestApi api = SpecRestApi.Builder.create(this, "books-api")
.apiDefinition(ApiDefinition.fromAsset("path-to-file.json"))
.mode(RestApiMode.MERGE)
.build();
SpecRestApi also supports binary media types, similar to RestApi:
SpecRestApi api = SpecRestApi.Builder.create(this, "books-api")
.apiDefinition(ApiDefinition.fromAsset("path-to-file.json"))
.binaryMediaTypes(List.of("image/png", "application/pdf"))
.build();
Endpoint configuration
By default, SpecRestApi will create an edge optimized endpoint.
This can be modified as shown below:
ApiDefinition apiDefinition;
SpecRestApi api = SpecRestApi.Builder.create(this, "ExampleRestApi")
.apiDefinition(apiDefinition)
.endpointTypes(List.of(EndpointType.PRIVATE))
.build();
Note: For private endpoints you will still need to provide the
x-amazon-apigateway-policy and
x-amazon-apigateway-endpoint-configuration
in your openApi file.
Metrics
The API Gateway service sends metrics around the performance of Rest APIs to Amazon CloudWatch.
These metrics can be referred to using the metric APIs available on the RestApi, Stage and Method constructs.
Note that detailed metrics must be enabled for a stage to use the Method metrics.
Read more about API Gateway metrics, including enabling detailed metrics.
The APIs with the metric prefix can be used to get reference to specific metrics for this API. For example:
RestApi api = new RestApi(this, "my-api");
Stage stage = api.getDeploymentStage();
Method method = api.root.addMethod("GET");
Metric clientErrorApiMetric = api.metricClientError();
Metric serverErrorStageMetric = stage.metricServerError();
Metric latencyMethodMetric = method.metricLatency(stage);
APIGateway v2
APIGateway v2 APIs are now moved to its own package named aws-apigatewayv2. Previously, these APIs were marked
deprecated but retained for backwards compatibility. The deprecated usage of APIGateway v2 APIs within this module
aws-apigateway has now been removed from the codebase.
The reason for the removal of these deprecated Constructs is that CloudFormation team is releasing AWS resources
like AWS::APIGateway::DomainNameV2 and this would cause compatibility issue with the deprecated CfnDomainNameV2
resource defined in apigatewayv2.ts file during the L1 generation.
Move to using aws-apigatewayv2 to get the latest APIs and updates.
This module is part of the AWS Cloud Development Kit project.
-
ClassDescriptionOptions when binding a log destination to a RestApi Stage.A builder for
AccessLogDestinationConfigAn implementation forAccessLogDestinationConfig$context variables that can be used to customize access log pattern.factory methods for access log format.Options to the UsagePlan.addApiKey() method.A builder forAddApiKeyOptionsAn implementation forAddApiKeyOptionsRepresents an OpenAPI definition asset.Post-Binding Configuration for a CDK construct.A builder forApiDefinitionConfigAn implementation forApiDefinitionConfigS3 location of the API definition file.A builder forApiDefinitionS3LocationAn implementation forApiDefinitionS3LocationAn API Gateway ApiKey.A fluent builder forApiKey.Collection of grant methods for a IApiKeyRef.The options for creating an API Key.A builder forApiKeyOptionsAn implementation forApiKeyOptionsApiKey Properties.A builder forApiKeyPropsAn implementation forApiKeyPropsOptions for creating an api mapping.A builder forApiMappingOptionsAn implementation forApiMappingOptionsOpenAPI specification from a local file.A fluent builder forAssetApiDefinition.Example:Base class for all custom authorizers.This type of integration lets an API expose AWS service actions.A fluent builder forAwsIntegration.Example:A builder forAwsIntegrationPropsAn implementation forAwsIntegrationPropsThis resource creates a base path that clients who call your API must use in the invocation URL.A fluent builder forBasePathMapping.Example:A builder forBasePathMappingOptionsAn implementation forBasePathMappingOptionsExample:A builder forBasePathMappingPropsAn implementation forBasePathMappingPropsTheAWS::ApiGateway::Accountresource specifies the IAM role that Amazon API Gateway uses to write API logs to Amazon CloudWatch Logs.A fluent builder forCfnAccount.Properties for defining aCfnAccount.A builder forCfnAccountPropsAn implementation forCfnAccountPropsTheAWS::ApiGateway::ApiKeyresource creates a unique key that you can distribute to clients who are executing API GatewayMethodresources that require an API key.A fluent builder forCfnApiKey.StageKeyis a property of the AWS::ApiGateway::ApiKey resource that specifies the stage to associate with the API key.A builder forCfnApiKey.StageKeyPropertyAn implementation forCfnApiKey.StageKeyPropertyProperties for defining aCfnApiKey.A builder forCfnApiKeyPropsAn implementation forCfnApiKeyPropsTheAWS::ApiGateway::Authorizerresource creates an authorization layer that API Gateway activates for methods that have authorization enabled.A fluent builder forCfnAuthorizer.Properties for defining aCfnAuthorizer.A builder forCfnAuthorizerPropsAn implementation forCfnAuthorizerPropsTheAWS::ApiGateway::BasePathMappingresource creates a base path that clients who call your API must use in the invocation URL.A fluent builder forCfnBasePathMapping.Properties for defining aCfnBasePathMapping.A builder forCfnBasePathMappingPropsAn implementation forCfnBasePathMappingPropsTheAWS::ApiGateway::BasePathMappingV2resource creates a base path that clients who call your API must use in the invocation URL.A fluent builder forCfnBasePathMappingV2.Properties for defining aCfnBasePathMappingV2.A builder forCfnBasePathMappingV2PropsAn implementation forCfnBasePathMappingV2PropsTheAWS::ApiGateway::ClientCertificateresource creates a client certificate that API Gateway uses to configure client-side SSL authentication for sending requests to the integration endpoint.A fluent builder forCfnClientCertificate.Properties for defining aCfnClientCertificate.A builder forCfnClientCertificatePropsAn implementation forCfnClientCertificatePropsTheAWS::ApiGateway::Deploymentresource deploys an API GatewayRestApiresource to a stage so that clients can call the API over the internet.TheAccessLogSettingproperty type specifies settings for logging access in this stage.A builder forCfnDeployment.AccessLogSettingPropertyAn implementation forCfnDeployment.AccessLogSettingPropertyA fluent builder forCfnDeployment.TheCanarySettingproperty type specifies settings for the canary deployment in this stage.A builder forCfnDeployment.CanarySettingPropertyAn implementation forCfnDeployment.CanarySettingPropertyTheDeploymentCanarySettingsproperty type specifies settings for the canary deployment.A builder forCfnDeployment.DeploymentCanarySettingsPropertyAn implementation forCfnDeployment.DeploymentCanarySettingsPropertyTheMethodSettingproperty type configures settings for all methods in a stage.A builder forCfnDeployment.MethodSettingPropertyAn implementation forCfnDeployment.MethodSettingPropertyStageDescriptionis a property of the AWS::ApiGateway::Deployment resource that configures a deployment stage.A builder forCfnDeployment.StageDescriptionPropertyAn implementation forCfnDeployment.StageDescriptionPropertyProperties for defining aCfnDeployment.A builder forCfnDeploymentPropsAn implementation forCfnDeploymentPropsTheAWS::ApiGateway::DocumentationPartresource creates a documentation part for an API.A fluent builder forCfnDocumentationPart.TheLocationproperty specifies the location of the Amazon API Gateway API entity that the documentation applies to.A builder forCfnDocumentationPart.LocationPropertyAn implementation forCfnDocumentationPart.LocationPropertyProperties for defining aCfnDocumentationPart.A builder forCfnDocumentationPartPropsAn implementation forCfnDocumentationPartPropsTheAWS::ApiGateway::DocumentationVersionresource creates a snapshot of the documentation for an API.A fluent builder forCfnDocumentationVersion.Properties for defining aCfnDocumentationVersion.A builder forCfnDocumentationVersionPropsAn implementation forCfnDocumentationVersionPropsTheAWS::ApiGateway::DomainNameresource specifies a public custom domain name for your API in API Gateway.A fluent builder forCfnDomainName.TheEndpointConfigurationproperty type specifies the endpoint types and IP address types of an Amazon API Gateway domain name.A builder forCfnDomainName.EndpointConfigurationPropertyAn implementation forCfnDomainName.EndpointConfigurationPropertyThe mutual TLS authentication configuration for a custom domain name.A builder forCfnDomainName.MutualTlsAuthenticationPropertyAn implementation forCfnDomainName.MutualTlsAuthenticationPropertyTheAWS::ApiGateway::DomainNameAccessAssociationresource creates a domain name access association between an access association source and a private custom domain name.A fluent builder forCfnDomainNameAccessAssociation.Properties for defining aCfnDomainNameAccessAssociation.A builder forCfnDomainNameAccessAssociationPropsAn implementation forCfnDomainNameAccessAssociationPropsProperties for defining aCfnDomainName.A builder forCfnDomainNamePropsAn implementation forCfnDomainNamePropsTheAWS::ApiGateway::DomainNameV2resource specifies a custom domain name for your private APIs in API Gateway.A fluent builder forCfnDomainNameV2.The endpoint configuration to indicate the types of endpoints an API (RestApi) or its custom domain name (DomainName) has and the IP address types that can invoke it.A builder forCfnDomainNameV2.EndpointConfigurationPropertyAn implementation forCfnDomainNameV2.EndpointConfigurationPropertyProperties for defining aCfnDomainNameV2.A builder forCfnDomainNameV2PropsAn implementation forCfnDomainNameV2PropsTheAWS::ApiGateway::GatewayResponseresource creates a gateway response for your API.A fluent builder forCfnGatewayResponse.Properties for defining aCfnGatewayResponse.A builder forCfnGatewayResponsePropsAn implementation forCfnGatewayResponsePropsTheAWS::ApiGateway::Methodresource creates API Gateway methods that define the parameters and body that clients must send in their requests.A fluent builder forCfnMethod.Integrationis a property of the AWS::ApiGateway::Method resource that specifies information about the target backend that a method calls.A builder forCfnMethod.IntegrationPropertyAn implementation forCfnMethod.IntegrationPropertyIntegrationResponseis a property of the Amazon API Gateway Method Integration property type that specifies the response that API Gateway sends after a method's backend finishes processing a request.A builder forCfnMethod.IntegrationResponsePropertyAn implementation forCfnMethod.IntegrationResponsePropertyRepresents a method response of a given HTTP status code returned to the client.A builder forCfnMethod.MethodResponsePropertyAn implementation forCfnMethod.MethodResponsePropertyProperties for defining aCfnMethod.A builder forCfnMethodPropsAn implementation forCfnMethodPropsTheAWS::ApiGateway::Modelresource defines the structure of a request or response payload for an API method.A fluent builder forCfnModel.Properties for defining aCfnModel.A builder forCfnModelPropsAn implementation forCfnModelPropsTheAWS::ApiGateway::RequestValidatorresource sets up basic validation rules for incoming requests to your API.A fluent builder forCfnRequestValidator.Properties for defining aCfnRequestValidator.A builder forCfnRequestValidatorPropsAn implementation forCfnRequestValidatorPropsTheAWS::ApiGateway::Resourceresource creates a resource in an API.A fluent builder forCfnResource.Properties for defining aCfnResource.A builder forCfnResourcePropsAn implementation forCfnResourcePropsTheAWS::ApiGateway::RestApiresource creates a REST API.A fluent builder forCfnRestApi.TheEndpointConfigurationproperty type specifies the endpoint types and IP address types of a REST API.A builder forCfnRestApi.EndpointConfigurationPropertyAn implementation forCfnRestApi.EndpointConfigurationPropertyS3Locationis a property of the AWS::ApiGateway::RestApi resource that specifies the Amazon S3 location of a OpenAPI (formerly Swagger) file that defines a set of RESTful APIs in JSON or YAML.A builder forCfnRestApi.S3LocationPropertyAn implementation forCfnRestApi.S3LocationPropertyProperties for defining aCfnRestApi.A builder forCfnRestApiPropsAn implementation forCfnRestApiPropsTheAWS::ApiGateway::Stageresource creates a stage for a deployment.TheAccessLogSettingproperty type specifies settings for logging access in this stage.A builder forCfnStage.AccessLogSettingPropertyAn implementation forCfnStage.AccessLogSettingPropertyA fluent builder forCfnStage.Configuration settings of a canary deployment.A builder forCfnStage.CanarySettingPropertyAn implementation forCfnStage.CanarySettingPropertyTheMethodSettingproperty type configures settings for all methods in a stage.A builder forCfnStage.MethodSettingPropertyAn implementation forCfnStage.MethodSettingPropertyProperties for defining aCfnStage.A builder forCfnStagePropsAn implementation forCfnStagePropsTheAWS::ApiGateway::UsagePlanresource creates a usage plan for deployed APIs.API stage name of the associated API stage in a usage plan.A builder forCfnUsagePlan.ApiStagePropertyAn implementation forCfnUsagePlan.ApiStagePropertyA fluent builder forCfnUsagePlan.QuotaSettingsis a property of the AWS::ApiGateway::UsagePlan resource that specifies a target for the maximum number of requests users can make to your REST APIs.A builder forCfnUsagePlan.QuotaSettingsPropertyAn implementation forCfnUsagePlan.QuotaSettingsPropertyThrottleSettingsis a property of the AWS::ApiGateway::UsagePlan resource that specifies the overall request rate (average requests per second) and burst capacity when users call your REST APIs.A builder forCfnUsagePlan.ThrottleSettingsPropertyAn implementation forCfnUsagePlan.ThrottleSettingsPropertyTheAWS::ApiGateway::UsagePlanKeyresource associates an API key with a usage plan.A fluent builder forCfnUsagePlanKey.Properties for defining aCfnUsagePlanKey.A builder forCfnUsagePlanKeyPropsAn implementation forCfnUsagePlanKeyPropsProperties for defining aCfnUsagePlan.A builder forCfnUsagePlanPropsAn implementation forCfnUsagePlanPropsTheAWS::ApiGateway::VpcLinkresource creates an API Gateway VPC link for a REST API to access resources in an Amazon Virtual Private Cloud (VPC).A fluent builder forCfnVpcLink.Properties for defining aCfnVpcLink.A builder forCfnVpcLinkPropsAn implementation forCfnVpcLinkPropsCognito user pools based custom authorizer.A fluent builder forCognitoUserPoolsAuthorizer.Properties for CognitoUserPoolsAuthorizer.A builder forCognitoUserPoolsAuthorizerPropsAn implementation forCognitoUserPoolsAuthorizerPropsExample:Example:Example:Example:A builder forCorsOptionsAn implementation forCorsOptionsA Deployment of a REST API.A fluent builder forDeployment.Example:A builder forDeploymentPropsAn implementation forDeploymentPropsExample:A fluent builder forDomainName.Example:A builder forDomainNameAttributesAn implementation forDomainNameAttributesExample:A builder forDomainNameOptionsAn implementation forDomainNameOptionsExample:A builder forDomainNamePropsAn implementation forDomainNamePropsThe endpoint configuration of a REST API, including VPCs and endpoint types.A builder forEndpointConfigurationAn implementation forEndpointConfigurationExample:Use a Firehose delivery stream as a custom access log destination for API Gateway.Configure the response received by clients, produced from the API Gateway backend.A fluent builder forGatewayResponse.Options to add gateway response.A builder forGatewayResponseOptionsAn implementation forGatewayResponseOptionsProperties for a new gateway response.A builder forGatewayResponsePropsAn implementation forGatewayResponsePropsYou can integrate an API method with an HTTP endpoint using the HTTP proxy integration or the HTTP custom integration,.A fluent builder forHttpIntegration.Example:A builder forHttpIntegrationPropsAn implementation forHttpIntegrationPropsAccess log destination for a RestApi Stage.Internal default implementation forIAccessLogDestination.A proxy class which represents a concrete javascript instance of this type.API keys are alphanumeric string values that you distribute to app developer customers to grant access to your API.Internal default implementation forIApiKey.A proxy class which represents a concrete javascript instance of this type.Represents an API Gateway authorizer.Internal default implementation forIAuthorizer.A proxy class which represents a concrete javascript instance of this type.Represents an identity source.Internal default implementation forIDomainName.A proxy class which represents a concrete javascript instance of this type.Represents gateway response resource.Internal default implementation forIGatewayResponse.A proxy class which represents a concrete javascript instance of this type.Internal default implementation forIModel.A proxy class which represents a concrete javascript instance of this type.OpenAPI specification from an inline JSON object.Base class for backend integrations for an API Gateway method.A fluent builder forIntegration.Result of binding an Integration to a Method.A builder forIntegrationConfigAn implementation forIntegrationConfigExample:A builder forIntegrationOptionsAn implementation forIntegrationOptionsExample:A builder forIntegrationPropsAn implementation forIntegrationPropsExample:A builder forIntegrationResponseAn implementation forIntegrationResponseExample:Supported IP Address Types.Internal default implementation forIRequestValidator.A proxy class which represents a concrete javascript instance of this type.Internal default implementation forIResource.A proxy class which represents a concrete javascript instance of this type.Internal default implementation forIRestApi.A proxy class which represents a concrete javascript instance of this type.Represents an APIGateway Stage.Internal default implementation forIStage.A proxy class which represents a concrete javascript instance of this type.A UsagePlan, either managed by this CDK app, or imported.Internal default implementation forIUsagePlan.A proxy class which represents a concrete javascript instance of this type.Represents an API Gateway VpcLink.Internal default implementation forIVpcLink.A proxy class which represents a concrete javascript instance of this type.Represents a JSON schema definition of the structure of a REST API model.A builder forJsonSchemaAn implementation forJsonSchemaExample:Example:Properties for controlling items output in JSON standard format.A builder forJsonWithStandardFieldPropsAn implementation forJsonWithStandardFieldPropsBase properties for all lambda authorizers.A builder forLambdaAuthorizerPropsAn implementation forLambdaAuthorizerPropsIntegrates an AWS Lambda function to an API Gateway method.A fluent builder forLambdaIntegration.Example:A builder forLambdaIntegrationOptionsAn implementation forLambdaIntegrationOptionsDefines an API Gateway REST API with AWS Lambda proxy integration.A fluent builder forLambdaRestApi.Example:A builder forLambdaRestApiPropsAn implementation forLambdaRestApiPropsUse CloudWatch Logs as a custom access log destination for API Gateway.Example:A fluent builder forMethod.Example:A builder forMethodDeploymentOptionsAn implementation forMethodDeploymentOptionsExample:Example:A builder forMethodOptionsAn implementation forMethodOptionsExample:A builder forMethodPropsAn implementation forMethodPropsExample:A builder forMethodResponseAn implementation forMethodResponseThis type of integration lets API Gateway return a response without sending the request further to the backend.A fluent builder forMockIntegration.Example:A fluent builder forModel.Example:A builder forModelOptionsAn implementation forModelOptionsExample:A builder forModelPropsAn implementation forModelPropsThe mTLS authentication configuration for a custom domain name.A builder forMTLSConfigAn implementation forMTLSConfigExample:Time period for which quota settings apply.Defines a {proxy+} greedy resource and an ANY method on a route.A fluent builder forProxyResource.Example:A builder forProxyResourceOptionsAn implementation forProxyResourceOptionsExample:A builder forProxyResourcePropsAn implementation forProxyResourcePropsSpecifies the maximum number of requests that clients can make to API Gateway APIs.A builder forQuotaSettingsAn implementation forQuotaSettingsAn API Gateway ApiKey, for which a rate limiting configuration can be specified.A fluent builder forRateLimitedApiKey.RateLimitedApiKey properties.A builder forRateLimitedApiKeyPropsAn implementation forRateLimitedApiKeyPropsRequest-based lambda authorizer that recognizes the caller's identity via request parameters, such as headers, paths, query strings, stage variables, or context variables.A fluent builder forRequestAuthorizer.Properties for RequestAuthorizer.A builder forRequestAuthorizerPropsAn implementation forRequestAuthorizerPropsConfigure what must be included in therequestContext.A builder forRequestContextAn implementation forRequestContextExample:A fluent builder forRequestValidator.Example:A builder forRequestValidatorOptionsAn implementation forRequestValidatorOptionsExample:A builder forRequestValidatorPropsAn implementation forRequestValidatorPropsExample:A fluent builder forResource.Attributes that can be specified when importing a Resource.A builder forResourceAttributesAn implementation forResourceAttributesExample:A builder forResourceOptionsAn implementation forResourceOptionsExample:A builder forResourcePropsAn implementation forResourcePropsThe response transfer mode of the integration.Supported types of gateway responses.Represents a REST API in Amazon API Gateway.A fluent builder forRestApi.Attributes that can be specified when importing a RestApi.A builder forRestApiAttributesAn implementation forRestApiAttributesBase implementation that are common to various implementations of IRestApi.Represents the props that all Rest APIs share.A builder forRestApiBasePropsAn implementation forRestApiBasePropsThe Mode that determines how API Gateway handles resource updates when importing an OpenAPI definition.Props to create a new instance of RestApi.A builder forRestApiPropsAn implementation forRestApiPropsOpenAPI specification from an S3 archive.Integrates an AWS Sagemaker Endpoint to an API Gateway method.A fluent builder forSagemakerIntegration.Options for SageMakerIntegration.A builder forSagemakerIntegrationOptionsAn implementation forSagemakerIntegrationOptionsThe minimum version of the SSL protocol that you want API Gateway to use for HTTPS connections.Represents a REST API in Amazon API Gateway, created with an OpenAPI specification.A fluent builder forSpecRestApi.Props to instantiate a new SpecRestApi.A builder forSpecRestApiPropsAn implementation forSpecRestApiPropsExample:A fluent builder forStage.The attributes of an imported Stage.A builder forStageAttributesAn implementation forStageAttributesBase class for an ApiGateway Stage.Example:A builder forStageOptionsAn implementation forStageOptionsExample:A builder forStagePropsAn implementation forStagePropsOptions when configuring Step Functions synchronous integration with Rest API.A builder forStepFunctionsExecutionIntegrationOptionsAn implementation forStepFunctionsExecutionIntegrationOptionsOptions to integrate with various StepFunction API.Defines an API Gateway REST API with a Synchrounous Express State Machine as a proxy integration.A fluent builder forStepFunctionsRestApi.Properties for StepFunctionsRestApi.A builder forStepFunctionsRestApiPropsAn implementation forStepFunctionsRestApiPropsContainer for defining throttling parameters to API stages or methods.A builder forThrottleSettingsAn implementation forThrottleSettingsRepresents per-method throttling for a resource.A builder forThrottlingPerMethodAn implementation forThrottlingPerMethodToken based lambda authorizer that recognizes the caller's identity as a bearer token, such as a JSON Web Token (JWT) or an OAuth token.A fluent builder forTokenAuthorizer.Properties for TokenAuthorizer.A builder forTokenAuthorizerPropsAn implementation forTokenAuthorizerPropsExample:A fluent builder forUsagePlan.Represents the API stages that a usage plan applies to.A builder forUsagePlanPerApiStageAn implementation forUsagePlanPerApiStageExample:A builder forUsagePlanPropsAn implementation forUsagePlanPropsDefine a new VPC Link Specifies an API Gateway VPC link for a RestApi to access resources in an Amazon Virtual Private Cloud (VPC).A fluent builder forVpcLink.Properties for a VpcLink.A builder forVpcLinkPropsAn implementation forVpcLinkProps