Namespace Amazon.CDK.AWS.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
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}
.
var api = new RestApi(this, "books-api");
api.Root.AddMethod("ANY");
var books = api.Root.AddResource("books");
books.AddMethod("GET");
books.AddMethod("POST");
var 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;
var method = api.Root.AddResource("books").AddMethod("GET");
method.GrantExecute(user);
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;
new LambdaRestApi(this, "myapi", new LambdaRestApiProps {
Handler = backend
});
You can also supply proxy: false
, in which case you will have to explicitly
define the API model:
Function backend;
var api = new LambdaRestApi(this, "myapi", new LambdaRestApiProps {
Handler = backend,
Proxy = false
});
var items = api.Root.AddResource("items");
items.AddMethod("GET"); // GET /items
items.AddMethod("POST"); // POST /items
var 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;
var api = new LambdaRestApi(this, "myapi", new LambdaRestApiProps {
Handler = backend,
IntegrationOptions = new LambdaIntegrationOptions {
AllowTestInvoke = false,
Timeout = Duration.Seconds(1)
}
});
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;
new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps {
StateMachine = machine,
UseDefaultMethodResponses = false
});
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:
var stateMachineDefinition = new Pass(this, "PassState");
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
Definition = stateMachineDefinition,
StateMachineType = StateMachineType.EXPRESS
});
new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps {
Deploy = true,
StateMachine = stateMachine
});
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.
new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps {
StateMachine = machine,
Headers = true,
Path = false,
Querystring = false,
Authorizer = false,
RequestContext = new RequestContext {
Caller = true,
User = true
}
});
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": {}
}
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:
using Constructs;
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
/**
* 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
*/
class RootStack : Stack
{
public RootStack(Construct scope) : base(scope, "integ-restapi-import-RootStack")
{
var restApi = new RestApi(this, "RestApi", new RestApiProps {
CloudWatchRole = true,
Deploy = false
});
restApi.Root.AddMethod("ANY");
var petsStack = new PetsStack(this, new ResourceNestedStackProps {
RestApiId = restApi.RestApiId,
RootResourceId = restApi.RestApiRootResourceId
});
var booksStack = new BooksStack(this, new ResourceNestedStackProps {
RestApiId = restApi.RestApiId,
RootResourceId = restApi.RestApiRootResourceId
});
new DeployStack(this, new DeployStackProps {
RestApiId = restApi.RestApiId,
Methods = petsStack.Methods.Concat(booksStack.Methods)
});
new CfnOutput(this, "PetsURL", new CfnOutputProps {
Value = $"https://{restApi.restApiId}.execute-api.{this.region}.amazonaws.com/prod/pets"
});
new CfnOutput(this, "BooksURL", new CfnOutputProps {
Value = $"https://{restApi.restApiId}.execute-api.{this.region}.amazonaws.com/prod/books"
});
}
}
class ResourceNestedStackProps : NestedStackProps
{
public string RestApiId { get; set; }
public string RootResourceId { get; set; }
}
class PetsStack : NestedStack
{
public readonly Method[] Methods = new [] { };
public PetsStack(Construct scope, ResourceNestedStackProps props) : base(scope, "integ-restapi-import-PetsStack", props)
{
var api = RestApi.FromRestApiAttributes(this, "RestApi", new RestApiAttributes {
RestApiId = props.RestApiId,
RootResourceId = props.RootResourceId
});
var method = api.Root.AddResource("pets").AddMethod("GET", new MockIntegration(new IntegrationOptions {
IntegrationResponses = new [] { new IntegrationResponse {
StatusCode = "200"
} },
PassthroughBehavior = PassthroughBehavior.NEVER,
RequestTemplates = new Dictionary<string, string> {
{ "application/json", "{ \"statusCode\": 200 }" }
}
}), new MethodOptions {
MethodResponses = new [] { new MethodResponse { StatusCode = "200" } }
});
Methods.Push(method);
}
}
class BooksStack : NestedStack
{
public readonly Method[] Methods = new [] { };
public BooksStack(Construct scope, ResourceNestedStackProps props) : base(scope, "integ-restapi-import-BooksStack", props)
{
var api = RestApi.FromRestApiAttributes(this, "RestApi", new RestApiAttributes {
RestApiId = props.RestApiId,
RootResourceId = props.RootResourceId
});
var method = api.Root.AddResource("books").AddMethod("GET", new MockIntegration(new IntegrationOptions {
IntegrationResponses = new [] { new IntegrationResponse {
StatusCode = "200"
} },
PassthroughBehavior = PassthroughBehavior.NEVER,
RequestTemplates = new Dictionary<string, string> {
{ "application/json", "{ \"statusCode\": 200 }" }
}
}), new MethodOptions {
MethodResponses = new [] { new MethodResponse { StatusCode = "200" } }
});
Methods.Push(method);
}
}
class DeployStackProps : NestedStackProps
{
public string RestApiId { get; set; }
public Method[]? Methods { get; set; }
}
class DeployStack : NestedStack
{
public DeployStack(Construct scope, DeployStackProps props) : base(scope, "integ-restapi-import-DeployStack", props)
{
var deployment = new Deployment(this, "Deployment", new DeploymentProps {
Api = RestApi.FromRestApiId(this, "RestApi", props.RestApiId)
});
if (props.Methods)
{
for (var method in props.Methods)
{
deployment.Node.AddDependency(method);
}
}
new Stage(this, "Stage", new StageProps { Deployment = deployment });
}
}
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.
Integration Targets
Methods are associated with backend integrations, which are invoked when this method is called. API Gateway supports the following integrations:
The following example shows how to integrate the GET /book/{book_id}
method to
an AWS Lambda function:
Function getBookHandler;
Resource book;
var getBookIntegration = new LambdaIntegration(getBookHandler);
book.AddMethod("GET", getBookIntegration);
Integration options can be optionally be specified:
Function getBookHandler;
LambdaIntegration getBookIntegration;
var getBookIntegration = new LambdaIntegration(getBookHandler, new LambdaIntegrationOptions {
ContentHandling = ContentHandling.CONVERT_TO_TEXT, // convert to base64
CredentialsPassthrough = true
});
Method options can optionally be specified when adding methods:
Resource book;
LambdaIntegration getBookIntegration;
book.AddMethod("GET", getBookIntegration, new MethodOptions {
AuthorizationType = AuthorizationType.IAM,
ApiKeyRequired = true
});
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.
var getMessageIntegration = new AwsIntegration(new AwsIntegrationProps {
Service = "sqs",
Path = "queueName",
Region = "eu-west-1"
});
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;
var api = new RestApi(this, "hello-api");
var v1 = api.Root.AddResource("v1");
var echo = v1.AddResource("echo");
var echoMethod = echo.AddMethod("GET", integration, new MethodOptions { ApiKeyRequired = true });
var plan = api.AddUsagePlan("UsagePlan", new UsagePlanProps {
Name = "Easy",
Throttle = new ThrottleSettings {
RateLimit = 10,
BurstLimit = 2
}
});
var key = api.AddApiKey("ApiKey");
plan.AddApiKey(key);
To associate a plan to a given RestAPI stage:
UsagePlan plan;
RestApi api;
Method echoMethod;
plan.AddApiStage(new UsagePlanPerApiStage {
Stage = api.DeploymentStage,
Throttle = new [] { new ThrottlingPerMethod {
Method = echoMethod,
Throttle = new ThrottleSettings {
RateLimit = 10,
BurstLimit = 2
}
} }
});
Existing usage plans can be imported into a CDK app using its id.
var 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;
var key = api.AddApiKey("ApiKey", new ApiKeyOptions {
ApiKeyName = "myApiKey1",
Value = "MyApiKeyThatIsAtLeast20Characters"
});
Existing API keys can also be imported into a CDK app using its id.
var 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;
var importedStage = Stage.FromStageAttributes(this, "imported-stage", new StageAttributes {
StageName = "myStageName",
RestApi = restApi
});
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, new AddApiKeyOptions {
OverrideLogicalId = "..."
});
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;
var key = new RateLimitedApiKey(this, "rate-limited-api-key", new RateLimitedApiKeyProps {
CustomerId = "hello-customer",
Stages = new [] { api.DeploymentStage },
Quota = new QuotaSettings {
Limit = 10000,
Period = Period.MONTH
}
});
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.
var hello = new Function(this, "hello", new FunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "hello.handler",
Code = Code.FromAsset("lambda")
});
var api = new RestApi(this, "hello-api", new RestApiProps { });
var resource = api.Root.AddResource("v1");
You can define more parameters on the integration to tune the behavior of API Gateway
Function hello;
var integration = new LambdaIntegration(hello, new LambdaIntegrationOptions {
Proxy = false,
RequestParameters = new Dictionary<string, string> {
// 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 = new Dictionary<string, string> {
// 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(new Dictionary<string, string> { { "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 = new [] { new IntegrationResponse {
// 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 = new Dictionary<string, string> {
// 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(new Dictionary<string, string> { { "state", "ok" }, { "greeting", "$util.escapeJavaScript($input.body)" } }) }
},
ResponseParameters = new Dictionary<string, string> {
// 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'" }
}
}, new IntegrationResponse {
// For errors, we check if the error message is not empty, get the error data
SelectionPattern = @"(
|.)+",
// We will set the response status code to 200
StatusCode = "400",
ResponseTemplates = new Dictionary<string, string> {
{ "application/json", JSON.Stringify(new Dictionary<string, string> { { "state", "error" }, { "message", "$util.escapeJavaScript($input.path('$.errorMessage'))" } }) }
},
ResponseParameters = new Dictionary<string, string> {
{ "method.response.header.Content-Type", "'application/json'" },
{ "method.response.header.Access-Control-Allow-Origin", "'*'" },
{ "method.response.header.Access-Control-Allow-Credentials", "'true'" }
}
} }
});
You can define models for your responses (and requests)
RestApi api;
// We define the JSON Schema for the transformed valid response
var responseModel = api.AddModel("ResponseModel", new ModelOptions {
ContentType = "application/json",
ModelName = "ResponseModel",
Schema = new JsonSchema {
Schema = JsonSchemaVersion.DRAFT4,
Title = "pollResponse",
Type = JsonSchemaType.OBJECT,
Properties = new Dictionary<string, JsonSchema> {
{ "state", new JsonSchema { Type = JsonSchemaType.STRING } },
{ "greeting", new JsonSchema { Type = JsonSchemaType.STRING } }
}
}
});
// We define the JSON Schema for the transformed error response
var errorResponseModel = api.AddModel("ErrorResponseModel", new ModelOptions {
ContentType = "application/json",
ModelName = "ErrorResponseModel",
Schema = new JsonSchema {
Schema = JsonSchemaVersion.DRAFT4,
Title = "errorResponse",
Type = JsonSchemaType.OBJECT,
Properties = new Dictionary<string, JsonSchema> {
{ "state", new JsonSchema { Type = JsonSchemaType.STRING } },
{ "message", new JsonSchema { Type = JsonSchemaType.STRING } }
}
}
});
And reference all on your method definition.
LambdaIntegration integration;
Resource resource;
Model responseModel;
Model errorResponseModel;
resource.AddMethod("GET", integration, new MethodOptions {
// We can mark the parameters as required
RequestParameters = new Dictionary<string, boolean> {
{ "method.request.querystring.who", true }
},
// we can set request validator options like below
RequestValidatorOptions = new RequestValidatorOptions {
RequestValidatorName = "test-validator",
ValidateRequestBody = true,
ValidateRequestParameters = false
},
MethodResponses = new [] { new MethodResponse {
// Successful response from the integration
StatusCode = "200",
// Define what parameters are allowed or not
ResponseParameters = new Dictionary<string, boolean> {
{ "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 = new Dictionary<string, IModel> {
{ "application/json", responseModel }
}
}, new MethodResponse {
// Same thing for the error responses
StatusCode = "400",
ResponseParameters = new Dictionary<string, boolean> {
{ "method.response.header.Content-Type", true },
{ "method.response.header.Access-Control-Allow-Origin", true },
{ "method.response.header.Access-Control-Allow-Credentials", true }
},
ResponseModels = new Dictionary<string, IModel> {
{ "application/json", errorResponseModel }
}
} }
});
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()
with requestValidatorOptions
the 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, new MethodOptions {
// we can set request validator options like below
RequestValidatorOptions = new RequestValidatorOptions {
RequestValidatorName = "test-validator",
ValidateRequestBody = true,
ValidateRequestParameters = false
}
});
resource.AddMethod("POST", integration, new MethodOptions {
// we can set request validator options like below
RequestValidatorOptions = new RequestValidatorOptions {
RequestValidatorName = "test-validator2",
ValidateRequestBody = true,
ValidateRequestParameters = false
}
});
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 <code>MockIntegration</code>. 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;
var api = new RestApi(this, "books", new RestApiProps {
DefaultIntegration = booksBackend
});
var books = api.Root.AddResource("books");
books.AddMethod("GET"); // integrated with `booksBackend`
books.AddMethod("POST"); // integrated with `booksBackend`
var 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"), new MethodOptions {
AuthorizationType = AuthorizationType.COGNITO,
AuthorizationScopes = new [] { "Scope1", "Scope2" }
});
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;
var proxy = resource.AddProxy(new ProxyResourceOptions {
DefaultIntegration = new LambdaIntegration(handler),
// "false" will require explicitly adding methods on the `proxy` resource
AnyMethod = true
});
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;
var getBooks = books.AddMethod("GET", new HttpIntegration("http://amazon.com"), new MethodOptions {
AuthorizationType = AuthorizationType.IAM
});
iamUser.AttachInlinePolicy(new Policy(this, "AllowBooks", new PolicyProps {
Statements = new [] {
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "execute-api:Invoke" },
Effect = Effect.ALLOW,
Resources = new [] { getBooks.MethodArn }
}) }
}));
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;
var auth = new TokenAuthorizer(this, "booksAuthorizer", new TokenAuthorizerProps {
Handler = authFn
});
books.AddMethod("GET", new HttpIntegration("http://amazon.com"), new MethodOptions {
Authorizer = auth
});
A full working example is shown below.
class MyStack : Stack
{
public MyStack(Construct scope, string id) : base(scope, id)
{
var authorizerFn = new Function(this, "MyAuthorizerFunction", new FunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "index.handler",
Code = AssetCode.FromAsset(Join(__dirname, "integ.token-authorizer.handler"))
});
var authorizer = new TokenAuthorizer(this, "MyAuthorizer", new TokenAuthorizerProps {
Handler = authorizerFn
});
var restapi = new RestApi(this, "MyRestApi", new RestApiProps {
CloudWatchRole = true,
DefaultMethodOptions = new MethodOptions {
Authorizer = authorizer
},
DefaultCorsPreflightOptions = new CorsOptions {
AllowOrigins = Cors.ALL_ORIGINS
}
});
restapi.Root.AddMethod("ANY", new MockIntegration(new IntegrationOptions {
IntegrationResponses = new [] { new IntegrationResponse { StatusCode = "200" } },
PassthroughBehavior = PassthroughBehavior.NEVER,
RequestTemplates = new Dictionary<string, string> {
{ "application/json", "{ \"statusCode\": 200 }" }
}
}), new MethodOptions {
MethodResponses = new [] { new MethodResponse { StatusCode = "200" } }
});
}
}
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 Method
s across the RestApi
or across all Resource
s,
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;
var auth = new RequestAuthorizer(this, "booksAuthorizer", new RequestAuthorizerProps {
Handler = authFn,
IdentitySources = new [] { IdentitySource.Header("Authorization") }
});
books.AddMethod("GET", new HttpIntegration("http://amazon.com"), new MethodOptions {
Authorizer = auth
});
A full working example is shown below.
using Path;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
// 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
var app = new App();
var stack = new Stack(app, "RequestAuthorizerInteg");
var authorizerFn = new Function(stack, "MyAuthorizerFunction", new FunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "index.handler",
Code = AssetCode.FromAsset(Join(__dirname, "integ.request-authorizer.handler"))
});
var restapi = new RestApi(stack, "MyRestApi", new RestApiProps { CloudWatchRole = true });
var authorizer = new RequestAuthorizer(stack, "MyAuthorizer", new RequestAuthorizerProps {
Handler = authorizerFn,
IdentitySources = new [] { IdentitySource.Header("Authorization"), IdentitySource.QueryString("allow") }
});
var secondAuthorizer = new RequestAuthorizer(stack, "MySecondAuthorizer", new RequestAuthorizerProps {
Handler = authorizerFn,
IdentitySources = new [] { IdentitySource.Header("Authorization"), IdentitySource.QueryString("allow") }
});
restapi.Root.AddMethod("ANY", new MockIntegration(new IntegrationOptions {
IntegrationResponses = new [] { new IntegrationResponse { StatusCode = "200" } },
PassthroughBehavior = PassthroughBehavior.NEVER,
RequestTemplates = new Dictionary<string, string> {
{ "application/json", "{ \"statusCode\": 200 }" }
}
}), new MethodOptions {
MethodResponses = new [] { new MethodResponse { StatusCode = "200" } },
Authorizer = authorizer
});
restapi.Root.ResourceForPath("auth").AddMethod("ANY", new MockIntegration(new IntegrationOptions {
IntegrationResponses = new [] { new IntegrationResponse { StatusCode = "200" } },
PassthroughBehavior = PassthroughBehavior.NEVER,
RequestTemplates = new Dictionary<string, string> {
{ "application/json", "{ \"statusCode\": 200 }" }
}
}), new MethodOptions {
MethodResponses = new [] { new MethodResponse { StatusCode = "200" } },
Authorizer = secondAuthorizer
});
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 Method
s across the RestApi
or across all Resource
s,
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;
var userPool = new UserPool(this, "UserPool");
var auth = new CognitoUserPoolsAuthorizer(this, "booksAuthorizer", new CognitoUserPoolsAuthorizerProps {
CognitoUserPools = new [] { userPool }
});
books.AddMethod("GET", new HttpIntegration("http://amazon.com"), new MethodOptions {
Authorizer = auth,
AuthorizationType = AuthorizationType.COGNITO
});
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.
var acm;
new DomainName(this, "domain-name", new DomainNameProps {
DomainName = "example.com",
Certificate = acm.Certificate.FromCertificateArn(this, "cert", "arn:aws:acm:us-east-1:1111111:certificate/11-3336f1-44483d-adc7-9cd375c5169d"),
Mtls = new MTLSConfig {
Bucket = new Bucket(this, "bucket"),
Key = "truststore.pem",
Version = "version"
}
});
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:disableCloudWatchRole
feature flag. When this feature flag
is set to false
the default behavior will set cloudWatchRole=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.
var api = new RestApi(this, "books", new RestApiProps {
CloudWatchRole = true,
DeployOptions = new StageOptions {
LoggingLevel = MethodLoggingLevel.INFO,
DataTraceEnabled = true
}
});
Note: there can only be a single apigateway.CfnAccount per AWS environment
so if you create multiple <code>RestApi</code>s with <code>cloudWatchRole=true</code> each new <code>RestApi</code>
will overwrite the <code>CfnAccount</code>. It is recommended to set <code>cloudWatchRole=false</code>
(the default behavior if <code>@aws-cdk/aws-apigateway:disableCloudWatchRole</code> is 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.
using Amazon.CDK;
var api = new RestApi(this, "books", new RestApiProps {
CloudWatchRole = true,
CloudWatchRoleRemovalPolicy = RemovalPolicy.DESTROY
});
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.
var restApi = new RestApi(this, "my-rest-api", new RestApiProps {
Deploy = false
});
// Use `stageName` to deploy to an existing stage
var deployment = new Deployment(this, "my-deployment", new DeploymentProps {
Api = restApi,
StageName = "dev",
RetainDeployments = true
});
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.
var myApiDefinition = ApiDefinition.FromAsset("path-to-file.json");
var specRestApi = new SpecRestApi(this, "my-specrest-api", new SpecRestApiProps {
Deploy = false,
ApiDefinition = myApiDefinition
});
// Use `stageName` to deploy to an existing stage
var deployment = new Deployment(this, "my-deployment", new DeploymentProps {
Api = specRestApi,
StageName = "dev",
RetainDeployments = true
});
// Trigger a new deployment on OpenAPI definition updates
deployment.AddToLogicalId(myApiDefinition);
Note: If the <code>stageName</code> property 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 <code>stageName</code> property, 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:
var restApi = new RestApi(this, "my-api", new RestApiProps {
Deploy = false
});
var deploymentRevision = 5; // Bump this counter to trigger a new deployment
// Bump this counter to trigger a new deployment
new Deployment(this, $"Deployment{deploymentRevision}", new DeploymentProps {
Api = restApi
});
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:
var acmCertificateForExampleCom;
var api = new RestApi(this, "MyDomain", new RestApiProps {
DomainName = new DomainNameOptions {
DomainName = "example.com",
Certificate = acmCertificateForExampleCom
}
});
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.)
using Amazon.CDK.AWS.Route53;
using Amazon.CDK.AWS.Route53.Targets;
RestApi api;
var hostedZoneForExampleCom;
new ARecord(this, "CustomDomainAliasRecord", new ARecordProps {
Zone = hostedZoneForExampleCom,
Target = RecordTarget.FromAlias(new ApiGateway(api))
});
You can also define a DomainName
resource directly in order to customize the default behavior:
var acmCertificateForExampleCom;
new DomainName(this, "custom-domain", new DomainNameProps {
DomainName = "example.com",
Certificate = acmCertificateForExampleCom,
EndpointType = EndpointType.EDGE, // default is REGIONAL
SecurityPolicy = SecurityPolicy.TLS_1_2
});
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, new BasePathMappingOptions { BasePath = "go-to-api1" });
domain.AddBasePathMapping(api2, new BasePathMappingOptions { BasePath = "boom" });
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;
var betaDeploy = new Deployment(this, "beta-deployment", new DeploymentProps {
Api = restapi
});
var betaStage = new Stage(this, "beta-stage", new StageProps {
Deployment = betaDeploy
});
domain.AddBasePathMapping(restapi, new BasePathMappingOptions { BasePath = "api/beta", Stage = betaStage });
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, new BasePathMappingOptions { BasePath = "myapi", AttachToStage = false });
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;
var domainName = DomainName.FromDomainNameAttributes(this, "DomainName", new DomainNameAttributes {
DomainName = "domainName",
DomainNameAliasHostedZoneId = "domainNameAliasHostedZoneId",
DomainNameAliasTarget = "domainNameAliasTarget"
});
new BasePathMapping(this, "BasePathMapping", new BasePathMappingProps {
DomainName = domainName,
RestApi = api
});
If you wish to setup this domain with an Amazon Route53 alias, use the targets.ApiGatewayDomain
:
var hostedZoneForExampleCom;
DomainName domainName;
using Amazon.CDK.AWS.Route53;
using Amazon.CDK.AWS.Route53.Targets;
new ARecord(this, "CustomDomainAliasRecord", new ARecordProps {
Zone = hostedZoneForExampleCom,
Target = RecordTarget.FromAlias(new ApiGatewayDomain(domainName))
});
Custom Domains with multi-level api mapping
Additional requirements for creating multi-level path mappings for RestApis:
(both are defaults)
var acmCertificateForExampleCom;
RestApi restApi;
new DomainName(this, "custom-domain", new DomainNameProps {
DomainName = "example.com",
Certificate = acmCertificateForExampleCom,
Mapping = restApi,
BasePath = "orders/v1/api"
});
To then add additional mappings to a domain you can use the addApiMapping
method.
var acmCertificateForExampleCom;
RestApi restApi;
RestApi secondRestApi;
var domain = new DomainName(this, "custom-domain", new DomainNameProps {
DomainName = "example.com",
Certificate = acmCertificateForExampleCom,
Mapping = restApi
});
domain.AddApiMapping(secondRestApi.DeploymentStage, new ApiMappingOptions {
BasePath = "orders/v2/api"
});
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
var prodLogGroup = new LogGroup(this, "PrdLogs");
var api = new RestApi(this, "books", new RestApiProps {
DeployOptions = new StageOptions {
AccessLogDestination = new LogGroupLogDestination(prodLogGroup),
AccessLogFormat = AccessLogFormat.JsonWithStandardFields()
}
});
var deployment = new Deployment(this, "Deployment", new DeploymentProps { Api = api });
// development stage
var devLogGroup = new LogGroup(this, "DevLogs");
new Stage(this, "dev", new StageProps {
Deployment = deployment,
AccessLogDestination = new LogGroupLogDestination(devLogGroup),
AccessLogFormat = AccessLogFormat.JsonWithStandardFields(new JsonWithStandardFieldProps {
Caller = false,
HttpMethod = true,
Ip = true,
Protocol = true,
RequestTime = true,
ResourcePath = true,
ResponseLength = true,
Status = true,
User = true
})
});
The following code will generate the access log in the CLF format.
var logGroup = new LogGroup(this, "ApiGatewayAccessLogs");
var api = new RestApi(this, "books", new RestApiProps {
DeployOptions = new StageOptions {
AccessLogDestination = new LogGroupLogDestination(logGroup),
AccessLogFormat = AccessLogFormat.Clf()
}
});
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.
var logGroup = new LogGroup(this, "ApiGatewayAccessLogs");
new RestApi(this, "books", new RestApiProps {
DeployOptions = new StageOptions {
AccessLogDestination = new LogGroupLogDestination(logGroup),
AccessLogFormat = AccessLogFormat.Custom($@"{apigateway.AccessLogField.contextRequestId()} {apigateway.AccessLogField.contextErrorMessage()} {apigateway.AccessLogField.contextErrorMessageString()}
{apigateway.AccessLogField.contextAuthorizerError()} {apigateway.AccessLogField.contextAuthorizerIntegrationStatus()}")
}
});
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.
var api = new RestApi(this, "books");
var deployment = new Deployment(this, "my-deployment", new DeploymentProps { Api = api });
var stage = new Stage(this, "my-stage", new StageProps {
Deployment = deployment,
MethodOptions = new Dictionary<string, MethodDeploymentOptions> {
{ "/*/*", new MethodDeploymentOptions { // This special path applies to all resource paths and all HTTP methods
ThrottlingRateLimit = 100,
ThrottlingBurstLimit = 200 } }
}
});
Configuring methodOptions
on the deployOptions
of RestApi
will set the
throttling behaviors on the default stage that is automatically created.
var api = new RestApi(this, "books", new RestApiProps {
DeployOptions = new StageOptions {
MethodOptions = new Dictionary<string, MethodDeploymentOptions> {
{ "/*/*", new MethodDeploymentOptions { // This special path applies to all resource paths and all HTTP methods
ThrottlingRateLimit = 100,
ThrottlingBurstLimit = 1000 } }
}
}
});
To write access log files to a Firehose delivery stream destination use the FirehoseLogDestination
class:
var destinationBucket = new Bucket(this, "Bucket");
var deliveryStreamRole = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("firehose.amazonaws.com")
});
var stream = new CfnDeliveryStream(this, "MyStream", new CfnDeliveryStreamProps {
DeliveryStreamName = "amazon-apigateway-delivery-stream",
S3DestinationConfiguration = new S3DestinationConfigurationProperty {
BucketArn = destinationBucket.BucketArn,
RoleArn = deliveryStreamRole.RoleArn
}
});
var api = new RestApi(this, "books", new RestApiProps {
DeployOptions = new StageOptions {
AccessLogDestination = new FirehoseLogDestination(stream),
AccessLogFormat = AccessLogFormat.JsonWithStandardFields()
}
});
Note: The delivery stream name must start with amazon-apigateway-
.
Visit <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-logging-to-kinesis.html">Logging API calls to Kinesis Data Firehose</a> 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:
new RestApi(this, "api", new RestApiProps {
DefaultCorsPreflightOptions = new CorsOptions {
AllowOrigins = Cors.ALL_ORIGINS,
AllowMethods = Cors.ALL_METHODS
}
});
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(new CorsOptions {
AllowOrigins = new [] { "https://amazon.com" },
AllowMethods = new [] { "GET", "PUT" }
});
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;
var subtree = resource.AddResource("subtree", new ResourceOptions {
DefaultCorsPreflightOptions = new CorsOptions {
AllowOrigins = new [] { "https://amazon.com" }
}
});
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:
var api = new RestApi(this, "api", new RestApiProps {
EndpointConfiguration = new EndpointConfiguration {
Types = new [] { EndpointType.EDGE }
}
});
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;
var api = new RestApi(this, "api", new RestApiProps {
EndpointConfiguration = new EndpointConfiguration {
Types = new [] { EndpointType.PRIVATE },
VpcEndpoints = new [] { someEndpoint }
}
});
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}
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 -
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
var vpc = new Vpc(this, "VPC");
var nlb = new NetworkLoadBalancer(this, "NLB", new NetworkLoadBalancerProps {
Vpc = vpc
});
var link = new VpcLink(this, "link", new VpcLinkProps {
Targets = new [] { nlb }
});
var integration = new Integration(new IntegrationProps {
Type = IntegrationType.HTTP_PROXY,
IntegrationHttpMethod = "ANY",
Options = new IntegrationOptions {
ConnectionType = ConnectionType.VPC_LINK,
VpcLink = link
}
});
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()
.
var 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':
var api = new RestApi(this, "books-api");
api.AddGatewayResponse("test-response", new GatewayResponseOptions {
Type = ResponseType.ACCESS_DENIED,
StatusCode = "500",
ResponseHeaders = new Dictionary<string, string> {
// Note that values must be enclosed within a pair of single quotes
{ "Access-Control-Allow-Origin", "'test.com'" },
{ "test-key", "'test-value'" }
},
Templates = new Dictionary<string, string> {
{ "application/json", "{ \"message\": $context.error.messageString, \"statusCode\": \"488\", \"type\": \"$context.error.responseType\" }" }
}
});
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;
var api = new SpecRestApi(this, "books-api", new SpecRestApiProps {
ApiDefinition = ApiDefinition.FromAsset("path-to-file.json")
});
var 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.
Endpoint configuration
By default, SpecRestApi
will create an edge optimized endpoint.
This can be modified as shown below:
ApiDefinition apiDefinition;
var api = new SpecRestApi(this, "ExampleRestApi", new SpecRestApiProps {
ApiDefinition = apiDefinition,
EndpointTypes = new [] { EndpointType.PRIVATE }
});
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:
var api = new RestApi(this, "my-api");
var stage = api.DeploymentStage;
var method = api.Root.AddMethod("GET");
var clientErrorApiMetric = api.MetricClientError();
var serverErrorStageMetric = stage.MetricServerError();
var latencyMethodMetric = method.MetricLatency(stage);
APIGateway v2
APIGateway v2 APIs are now moved to its own package named aws-apigatewayv2
. For backwards compatibility, existing
APIGateway v2 "CFN resources" (such as CfnApi
) that were previously exported as part of this package, are still
exported from here and have been marked deprecated. However, updates to these CloudFormation resources, such as new
properties and new resource types will not be available.
Move to using aws-apigatewayv2
to get the latest APIs and updates.
This module is part of the AWS Cloud Development Kit project.
Classes
AccessLogDestinationConfig | Options when binding a log destination to a RestApi Stage. |
AccessLogField | $context variables that can be used to customize access log pattern. |
AccessLogFormat | factory methods for access log format. |
AddApiKeyOptions | Options to the UsagePlan.addApiKey() method. |
ApiDefinition | Represents an OpenAPI definition asset. |
ApiDefinitionConfig | Post-Binding Configuration for a CDK construct. |
ApiDefinitionS3Location | S3 location of the API definition file. |
ApiKey | An API Gateway ApiKey. |
ApiKeyOptions | The options for creating an API Key. |
ApiKeyProps | ApiKey Properties. |
ApiKeySourceType | |
ApiMappingOptions | Options for creating an api mapping. |
AssetApiDefinition | OpenAPI specification from a local file. |
AuthorizationType | |
Authorizer | Base class for all custom authorizers. |
AwsIntegration | This type of integration lets an API expose AWS service actions. |
AwsIntegrationProps | |
BasePathMapping | This resource creates a base path that clients who call your API must use in the invocation URL. |
BasePathMappingOptions | |
BasePathMappingProps | |
CfnAccount | The |
CfnAccountProps | Properties for defining a |
CfnApiKey | The |
CfnApiKey.StageKeyProperty |
|
CfnApiKeyProps | Properties for defining a |
CfnAuthorizer | The |
CfnAuthorizerProps | Properties for defining a |
CfnBasePathMapping | The |
CfnBasePathMappingProps | Properties for defining a |
CfnClientCertificate | The |
CfnClientCertificateProps | Properties for defining a |
CfnDeployment | The |
CfnDeployment.AccessLogSettingProperty | The |
CfnDeployment.CanarySettingProperty | The |
CfnDeployment.DeploymentCanarySettingsProperty | The |
CfnDeployment.MethodSettingProperty | The |
CfnDeployment.StageDescriptionProperty |
|
CfnDeploymentProps | Properties for defining a |
CfnDocumentationPart | The |
CfnDocumentationPart.LocationProperty | The |
CfnDocumentationPartProps | Properties for defining a |
CfnDocumentationVersion | The |
CfnDocumentationVersionProps | Properties for defining a |
CfnDomainName | The |
CfnDomainName.EndpointConfigurationProperty | The |
CfnDomainName.MutualTlsAuthenticationProperty | The mutual TLS authentication configuration for a custom domain name. |
CfnDomainNameProps | Properties for defining a |
CfnGatewayResponse | The |
CfnGatewayResponseProps | Properties for defining a |
CfnMethod | The |
CfnMethod.IntegrationProperty |
|
CfnMethod.IntegrationResponseProperty |
|
CfnMethod.MethodResponseProperty | Represents a method response of a given HTTP status code returned to the client. |
CfnMethodProps | Properties for defining a |
CfnModel | The |
CfnModelProps | Properties for defining a |
CfnRequestValidator | The |
CfnRequestValidatorProps | Properties for defining a |
CfnResource | The |
CfnResourceProps | Properties for defining a |
CfnRestApi | The |
CfnRestApi.EndpointConfigurationProperty | The |
CfnRestApi.S3LocationProperty |
|
CfnRestApiProps | Properties for defining a |
CfnStage | The |
CfnStage.AccessLogSettingProperty | The |
CfnStage.CanarySettingProperty | Configuration settings of a canary deployment. |
CfnStage.MethodSettingProperty | The |
CfnStageProps | Properties for defining a |
CfnUsagePlan | The |
CfnUsagePlan.ApiStageProperty | API stage name of the associated API stage in a usage plan. |
CfnUsagePlan.QuotaSettingsProperty |
|
CfnUsagePlan.ThrottleSettingsProperty |
|
CfnUsagePlanKey | The |
CfnUsagePlanKeyProps | Properties for defining a |
CfnUsagePlanProps | Properties for defining a |
CfnVpcLink | The |
CfnVpcLinkProps | Properties for defining a |
CognitoUserPoolsAuthorizer | Cognito user pools based custom authorizer. |
CognitoUserPoolsAuthorizerProps | Properties for CognitoUserPoolsAuthorizer. |
ConnectionType | |
ContentHandling | |
Cors | |
CorsOptions | |
Deployment | A Deployment of a REST API. |
DeploymentProps | |
DomainName_ | |
DomainNameAttributes | |
DomainNameOptions | |
DomainNameProps | |
EndpointConfiguration | The endpoint configuration of a REST API, including VPCs and endpoint types. |
EndpointType | |
FirehoseLogDestination | Use a Firehose delivery stream as a custom access log destination for API Gateway. |
GatewayResponse | Configure the response received by clients, produced from the API Gateway backend. |
GatewayResponseOptions | Options to add gateway response. |
GatewayResponseProps | Properties for a new gateway response. |
HttpIntegration | You can integrate an API method with an HTTP endpoint using the HTTP proxy integration or the HTTP custom integration,. |
HttpIntegrationProps | |
IdentitySource | Represents an identity source. |
InlineApiDefinition | OpenAPI specification from an inline JSON object. |
Integration | Base class for backend integrations for an API Gateway method. |
IntegrationConfig | Result of binding an Integration to a Method. |
IntegrationOptions | |
IntegrationProps | |
IntegrationResponse | |
IntegrationType | |
JsonSchema | Represents a JSON schema definition of the structure of a REST API model. |
JsonSchemaType | |
JsonSchemaVersion | |
JsonWithStandardFieldProps | Properties for controlling items output in JSON standard format. |
LambdaAuthorizerProps | Base properties for all lambda authorizers. |
LambdaIntegration | Integrates an AWS Lambda function to an API Gateway method. |
LambdaIntegrationOptions | |
LambdaRestApi | Defines an API Gateway REST API with AWS Lambda proxy integration. |
LambdaRestApiProps | |
LogGroupLogDestination | Use CloudWatch Logs as a custom access log destination for API Gateway. |
Method | |
MethodDeploymentOptions | |
MethodLoggingLevel | |
MethodOptions | |
MethodProps | |
MethodResponse | |
MockIntegration | This type of integration lets API Gateway return a response without sending the request further to the backend. |
Model | |
ModelOptions | |
ModelProps | |
MTLSConfig | The mTLS authentication configuration for a custom domain name. |
PassthroughBehavior | |
Period | Time period for which quota settings apply. |
ProxyResource | Defines a {proxy+} greedy resource and an ANY method on a route. |
ProxyResourceOptions | |
ProxyResourceProps | |
QuotaSettings | Specifies the maximum number of requests that clients can make to API Gateway APIs. |
RateLimitedApiKey | An API Gateway ApiKey, for which a rate limiting configuration can be specified. |
RateLimitedApiKeyProps | RateLimitedApiKey properties. |
RequestAuthorizer | Request-based lambda authorizer that recognizes the caller's identity via request parameters, such as headers, paths, query strings, stage variables, or context variables. |
RequestAuthorizerProps | Properties for RequestAuthorizer. |
RequestContext | Configure what must be included in the |
RequestValidator | |
RequestValidatorOptions | |
RequestValidatorProps | |
Resource | |
ResourceAttributes | Attributes that can be specified when importing a Resource. |
ResourceBase | |
ResourceOptions | |
ResourceProps | |
ResponseType_ | Supported types of gateway responses. |
RestApi | Represents a REST API in Amazon API Gateway. |
RestApiAttributes | Attributes that can be specified when importing a RestApi. |
RestApiBase | Base implementation that are common to various implementations of IRestApi. |
RestApiBaseProps | Represents the props that all Rest APIs share. |
RestApiProps | Props to create a new instance of RestApi. |
S3ApiDefinition | OpenAPI specification from an S3 archive. |
SagemakerIntegration | Integrates an AWS Sagemaker Endpoint to an API Gateway method. |
SagemakerIntegrationOptions | Options for SageMakerIntegration. |
SecurityPolicy | The minimum version of the SSL protocol that you want API Gateway to use for HTTPS connections. |
SpecRestApi | Represents a REST API in Amazon API Gateway, created with an OpenAPI specification. |
SpecRestApiProps | Props to instantiate a new SpecRestApi. |
Stage | |
StageAttributes | The attributes of an imported Stage. |
StageBase | Base class for an ApiGateway Stage. |
StageOptions | |
StageProps | |
StepFunctionsExecutionIntegrationOptions | Options when configuring Step Functions synchronous integration with Rest API. |
StepFunctionsIntegration | Options to integrate with various StepFunction API. |
StepFunctionsRestApi | Defines an API Gateway REST API with a Synchrounous Express State Machine as a proxy integration. |
StepFunctionsRestApiProps | Properties for StepFunctionsRestApi. |
ThrottleSettings | Container for defining throttling parameters to API stages or methods. |
ThrottlingPerMethod | Represents per-method throttling for a resource. |
TokenAuthorizer | Token based lambda authorizer that recognizes the caller's identity as a bearer token, such as a JSON Web Token (JWT) or an OAuth token. |
TokenAuthorizerProps | Properties for TokenAuthorizer. |
UsagePlan | |
UsagePlanPerApiStage | Represents the API stages that a usage plan applies to. |
UsagePlanProps | |
VpcLink | Define a new VPC Link Specifies an API Gateway VPC link for a RestApi to access resources in an Amazon Virtual Private Cloud (VPC). |
VpcLinkProps | Properties for a VpcLink. |
Interfaces
CfnApiKey.IStageKeyProperty |
|
CfnDeployment.IAccessLogSettingProperty | The |
CfnDeployment.ICanarySettingProperty | The |
CfnDeployment.IDeploymentCanarySettingsProperty | The |
CfnDeployment.IMethodSettingProperty | The |
CfnDeployment.IStageDescriptionProperty |
|
CfnDocumentationPart.ILocationProperty | The |
CfnDomainName.IEndpointConfigurationProperty | The |
CfnDomainName.IMutualTlsAuthenticationProperty | The mutual TLS authentication configuration for a custom domain name. |
CfnMethod.IIntegrationProperty |
|
CfnMethod.IIntegrationResponseProperty |
|
CfnMethod.IMethodResponseProperty | Represents a method response of a given HTTP status code returned to the client. |
CfnRestApi.IEndpointConfigurationProperty | The |
CfnRestApi.IS3LocationProperty |
|
CfnStage.IAccessLogSettingProperty | The |
CfnStage.ICanarySettingProperty | Configuration settings of a canary deployment. |
CfnStage.IMethodSettingProperty | The |
CfnUsagePlan.IApiStageProperty | API stage name of the associated API stage in a usage plan. |
CfnUsagePlan.IQuotaSettingsProperty |
|
CfnUsagePlan.IThrottleSettingsProperty |
|
IAccessLogDestination | Access log destination for a RestApi Stage. |
IAccessLogDestinationConfig | Options when binding a log destination to a RestApi Stage. |
IAddApiKeyOptions | Options to the UsagePlan.addApiKey() method. |
IApiDefinitionConfig | Post-Binding Configuration for a CDK construct. |
IApiDefinitionS3Location | S3 location of the API definition file. |
IApiKey | API keys are alphanumeric string values that you distribute to app developer customers to grant access to your API. |
IApiKeyOptions | The options for creating an API Key. |
IApiKeyProps | ApiKey Properties. |
IApiMappingOptions | Options for creating an api mapping. |
IAuthorizer | Represents an API Gateway authorizer. |
IAwsIntegrationProps | |
IBasePathMappingOptions | |
IBasePathMappingProps | |
ICfnAccountProps | Properties for defining a |
ICfnApiKeyProps | Properties for defining a |
ICfnAuthorizerProps | Properties for defining a |
ICfnBasePathMappingProps | Properties for defining a |
ICfnClientCertificateProps | Properties for defining a |
ICfnDeploymentProps | Properties for defining a |
ICfnDocumentationPartProps | Properties for defining a |
ICfnDocumentationVersionProps | Properties for defining a |
ICfnDomainNameProps | Properties for defining a |
ICfnGatewayResponseProps | Properties for defining a |
ICfnMethodProps | Properties for defining a |
ICfnModelProps | Properties for defining a |
ICfnRequestValidatorProps | Properties for defining a |
ICfnResourceProps | Properties for defining a |
ICfnRestApiProps | Properties for defining a |
ICfnStageProps | Properties for defining a |
ICfnUsagePlanKeyProps | Properties for defining a |
ICfnUsagePlanProps | Properties for defining a |
ICfnVpcLinkProps | Properties for defining a |
ICognitoUserPoolsAuthorizerProps | Properties for CognitoUserPoolsAuthorizer. |
ICorsOptions | |
IDeploymentProps | |
IDomainName | |
IDomainNameAttributes | |
IDomainNameOptions | |
IDomainNameProps | |
IEndpointConfiguration | The endpoint configuration of a REST API, including VPCs and endpoint types. |
IGatewayResponse | Represents gateway response resource. |
IGatewayResponseOptions | Options to add gateway response. |
IGatewayResponseProps | Properties for a new gateway response. |
IHttpIntegrationProps | |
IIntegrationConfig | Result of binding an Integration to a Method. |
IIntegrationOptions | |
IIntegrationProps | |
IIntegrationResponse | |
IJsonSchema | Represents a JSON schema definition of the structure of a REST API model. |
IJsonWithStandardFieldProps | Properties for controlling items output in JSON standard format. |
ILambdaAuthorizerProps | Base properties for all lambda authorizers. |
ILambdaIntegrationOptions | |
ILambdaRestApiProps | |
IMethodDeploymentOptions | |
IMethodOptions | |
IMethodProps | |
IMethodResponse | |
IModel | |
IModelOptions | |
IModelProps | |
IMTLSConfig | The mTLS authentication configuration for a custom domain name. |
IProxyResourceOptions | |
IProxyResourceProps | |
IQuotaSettings | Specifies the maximum number of requests that clients can make to API Gateway APIs. |
IRateLimitedApiKeyProps | RateLimitedApiKey properties. |
IRequestAuthorizerProps | Properties for RequestAuthorizer. |
IRequestContext | Configure what must be included in the |
IRequestValidator | |
IRequestValidatorOptions | |
IRequestValidatorProps | |
IResource | |
IResourceAttributes | Attributes that can be specified when importing a Resource. |
IResourceOptions | |
IResourceProps | |
IRestApi | |
IRestApiAttributes | Attributes that can be specified when importing a RestApi. |
IRestApiBaseProps | Represents the props that all Rest APIs share. |
IRestApiProps | Props to create a new instance of RestApi. |
ISagemakerIntegrationOptions | Options for SageMakerIntegration. |
ISpecRestApiProps | Props to instantiate a new SpecRestApi. |
IStage | Represents an APIGateway Stage. |
IStageAttributes | The attributes of an imported Stage. |
IStageOptions | |
IStageProps | |
IStepFunctionsExecutionIntegrationOptions | Options when configuring Step Functions synchronous integration with Rest API. |
IStepFunctionsRestApiProps | Properties for StepFunctionsRestApi. |
IThrottleSettings | Container for defining throttling parameters to API stages or methods. |
IThrottlingPerMethod | Represents per-method throttling for a resource. |
ITokenAuthorizerProps | Properties for TokenAuthorizer. |
IUsagePlan | A UsagePlan, either managed by this CDK app, or imported. |
IUsagePlanPerApiStage | Represents the API stages that a usage plan applies to. |
IUsagePlanProps | |
IVpcLink | Represents an API Gateway VpcLink. |
IVpcLinkProps | Properties for a VpcLink. |