Package: aws-cdk.aws-apigateway
Amazon API Gateway Construct Library---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.For more information on how to migrate, see theMigrating to AWS CDK v2guide.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 ContentsDefining APIsBreaking up Methods and Resources across StacksAWS Lambda-backed APIsAWS StepFunctions backed APIsIntegration TargetsUsage Plan & API KeysWorking with modelsDefault Integration and Method OptionsProxy RoutesAuthorizersIAM-based authorizerLambda-based token authorizerLambda-based request authorizerCognito User Pools authorizerMutual TLSDeploymentsDeep dive: Invalidation of deploymentsCustom DomainsAccess LoggingCross Origin Resource Sharing (CORS)Endpoint ConfigurationPrivate IntegrationsGateway ResponseOpenAPI DefinitionEndpoint configurationMetricsAPIGateway v2Defining APIsAPIs are defined as a hierarchy of resources and methods.addResourceandaddMethodcan be used to build this hierarchy. The root resource isapi.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}.api=apigateway.RestApi(self,"books-api")api.root.add_method("ANY")books=api.root.add_resource("books")books.add_method("GET")books.add_method("POST")book=books.add_resource("{book_id}")book.add_method("GET")book.add_method("DELETE")AWS Lambda-backed APIsA very common practice is to use Amazon API Gateway with AWS Lambda as the
backend integration. TheLambdaRestApiconstruct makes it easy:The following code defines a REST API that routes all requests to the
specified AWS Lambda function:# backend: lambda.Functionapigateway.LambdaRestApi(self,"myapi",handler=backend)You can also supplyproxy: false, in which case you will have to explicitly
define the API model:# backend: lambda.Functionapi=apigateway.LambdaRestApi(self,"myapi",handler=backend,proxy=False)items=api.root.add_resource("items")items.add_method("GET")# GET /itemsitems.add_method("POST")# POST /itemsitem=items.add_resource("{item}")item.add_method("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.add_method("DELETE",apigateway.HttpIntegration("http://amazon.com"))AWS StepFunctions backed APIsYou can use Amazon API Gateway with AWS Step Functions as the backend integration, specifically Synchronous Express Workflows.TheStepFunctionsRestApionly supports integration with Synchronous Express state machine. TheStepFunctionsRestApiconstruct makes this easy by setting up input, output and error mapping.The construct sets up an API endpoint and maps theANYHTTP 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 code200is returned with the execution output as the Response Body.If the execution fails, an HTTP500response is returned with theerrorandcausefrom the execution output as the Response Body. If the request is invalid (ex. bad execution input) HTTP code400is returned.The response from the invocation contains only theoutputfield from theStartSyncExecutionAPI.
In case of failures, the fieldserrorandcauseare 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, aprodstage is provisioned.In order to reduce the payload size sent to AWS Step Functions,headersare not forwarded to the Step Functions execution input. It is possible to choose whetherheaders,requestContext,path,querystring, andauthorizerare included or not. By default,headersare excluded in all requests.More details about AWS Step Functions payload limit can be found athttps://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:state_machine_definition=stepfunctions.Pass(self,"PassState")state_machine=stepfunctions.StateMachine(self,"StateMachine",definition=state_machine_definition,state_machine_type=stepfunctions.StateMachineType.EXPRESS)apigateway.StepFunctionsRestApi(self,"StepFunctionsRestApi",deploy=True,state_machine=state_machine)When the REST API endpoint configuration above is invoked using POST, as follows -curl-XPOST-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-XGEThttps://example.com/users/5?foo=barAWS 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.apigateway.StepFunctionsRestApi(self,"StepFunctionsRestApi",state_machine=machine,headers=True,path=False,querystring=False,authorizer=False,request_context=apigateway.RequestContext(caller=True,user=True))In such a case, when the endpoint is invoked as below:curl-XGEThttps://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 StacksIt is fairly common for REST APIs with a large number of Resources and Methods to hit theCloudFormation
limitof 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:fromaws_cdk.aws_apigatewayimportIntegrationResponse,MethodResponse,IntegrationResponse,MethodResponsefromaws_cdk.coreimportApp,CfnOutput,NestedStack,NestedStackProps,StackfromconstructsimportConstructfromaws_cdk.aws_apigatewayimportDeployment,Method,MockIntegration,PassthroughBehavior,RestApi,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#classRootStack(Stack):def__init__(self,scope):super().__init__(scope,"integ-restapi-import-RootStack")rest_api=RestApi(self,"RestApi",deploy=False)rest_api.root.add_method("ANY")pets_stack=PetsStack(self,rest_api_id=rest_api.rest_api_id,root_resource_id=rest_api.rest_api_root_resource_id)books_stack=BooksStack(self,rest_api_id=rest_api.rest_api_id,root_resource_id=rest_api.rest_api_root_resource_id)DeployStack(self,rest_api_id=rest_api.rest_api_id,methods=pets_stack.methods.concat(books_stack.methods))CfnOutput(self,"PetsURL",value=f"https://{restApi.restApiId}.execute-api.{this.region}.amazonaws.com/prod/pets")CfnOutput(self,"BooksURL",value=f"https://{restApi.restApiId}.execute-api.{this.region}.amazonaws.com/prod/books")classPetsStack(NestedStack):def__init__(self,scope,*,restApiId,rootResourceId,parameters=None,timeout=None,notificationArns=None,removalPolicy=None):super().__init__(scope,"integ-restapi-import-PetsStack",restApiId=restApiId,rootResourceId=rootResourceId,parameters=parameters,timeout=timeout,notificationArns=notificationArns,removalPolicy=removalPolicy)api=RestApi.from_rest_api_attributes(self,"RestApi",rest_api_id=rest_api_id,root_resource_id=root_resource_id)method=api.root.add_resource("pets").add_method("GET",MockIntegration(integration_responses=[IntegrationResponse(status_code="200")],passthrough_behavior=PassthroughBehavior.NEVER,request_templates={"application/json":"{\"statusCode\": 200 }"}),method_responses=[MethodResponse(status_code="200")])self.methods.push(method)classBooksStack(NestedStack):def__init__(self,scope,*,restApiId,rootResourceId,parameters=None,timeout=None,notificationArns=None,removalPolicy=None):super().__init__(scope,"integ-restapi-import-BooksStack",restApiId=restApiId,rootResourceId=rootResourceId,parameters=parameters,timeout=timeout,notificationArns=notificationArns,removalPolicy=removalPolicy)api=RestApi.from_rest_api_attributes(self,"RestApi",rest_api_id=rest_api_id,root_resource_id=root_resource_id)method=api.root.add_resource("books").add_method("GET",MockIntegration(integration_responses=[IntegrationResponse(status_code="200")],passthrough_behavior=PassthroughBehavior.NEVER,request_templates={"application/json":"{\"statusCode\": 200 }"}),method_responses=[MethodResponse(status_code="200")])self.methods.push(method)classDeployStack(NestedStack):def__init__(self,scope,*,restApiId,methods=None,parameters=None,timeout=None,notificationArns=None,removalPolicy=None):super().__init__(scope,"integ-restapi-import-DeployStack",restApiId=restApiId,methods=methods,parameters=parameters,timeout=timeout,notificationArns=notificationArns,removalPolicy=removalPolicy)deployment=Deployment(self,"Deployment",api=RestApi.from_rest_api_id(self,"RestApi",rest_api_id))ifmethods:formethodinmethods:deployment.node.add_dependency(method)Stage(self,"Stage",deployment=deployment)RootStack(App())Integration TargetsMethods 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.LambdaIntegration- can be used to invoke an AWS Lambda function.AwsIntegration- can be used to invoke arbitrary AWS service APIs.HttpIntegration- can be used to invoke HTTP endpoints.The following example shows how to integrate theGET /book/{book_id}method to
an AWS Lambda function:# get_book_handler: lambda.Function# book: apigateway.Resourceget_book_integration=apigateway.LambdaIntegration(get_book_handler)book.add_method("GET",get_book_integration)Integration options can be optionally be specified:# get_book_handler: lambda.Function# get_book_integration: apigateway.LambdaIntegrationget_book_integration=apigateway.LambdaIntegration(get_book_handler,content_handling=apigateway.ContentHandling.CONVERT_TO_TEXT,# convert to base64credentials_passthrough=True)Method options can optionally be specified when adding methods:# book: apigateway.Resource# get_book_integration: apigateway.LambdaIntegrationbook.add_method("GET",get_book_integration,authorization_type=apigateway.AuthorizationType.IAM,api_key_required=True)It is possible to also integrate with AWS services in a different region. The following code integrates with Amazon SQS in theeu-west-1region.get_message_integration=apigateway.AwsIntegration(service="sqs",path="queueName",region="eu-west-1")Usage Plan & API KeysA 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 asscociate a usage plan and an API key:# integration: apigateway.LambdaIntegrationapi=apigateway.RestApi(self,"hello-api")v1=api.root.add_resource("v1")echo=v1.add_resource("echo")echo_method=echo.add_method("GET",integration,api_key_required=True)plan=api.add_usage_plan("UsagePlan",name="Easy",throttle=apigateway.ThrottleSettings(rate_limit=10,burst_limit=2))key=api.add_api_key("ApiKey")plan.add_api_key(key)To associate a plan to a given RestAPI stage:# plan: apigateway.UsagePlan# api: apigateway.RestApi# echo_method: apigateway.Methodplan.add_api_stage(stage=api.deployment_stage,throttle=[apigateway.ThrottlingPerMethod(method=echo_method,throttle=apigateway.ThrottleSettings(rate_limit=10,burst_limit=2))])Existing usage plans can be imported into a CDK app using its id.imported_usage_plan=apigateway.UsagePlan.from_usage_plan_id(self,"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.# api: apigateway.RestApikey=api.add_api_key("ApiKey",api_key_name="myApiKey1",value="MyApiKeyThatIsAtLeast20Characters")Existing API keys can also be imported into a CDK app using its id.imported_key=apigateway.ApiKey.from_api_key_id(self,"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.# imported_key: apigateway.ApiKey# lambda_fn: lambda.Functionimported_key.grant_read(lambda_fn)⚠️ Multiple API KeysIt is possible to specify multiple API keys for a given Usage Plan, by callingusagePlan.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 thefeature 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 CloudFormationlogical idsof 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 theaddApiKey()method:# usageplan: apigateway.UsagePlan# api_key: apigateway.ApiKeyusageplan.add_api_key(api_key,override_logical_id="...")Rate Limited API KeyIn scenarios where you need to create a single api key and configure rate limiting for it, you can useRateLimitedApiKey.
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 :# api: apigateway.RestApikey=apigateway.RateLimitedApiKey(self,"rate-limited-api-key",customer_id="hello-customer",resources=[api],quota=apigateway.QuotaSettings(limit=10000,period=apigateway.Period.MONTH))Working with modelsWhen you work with Lambda integrations that are not Proxy integrations, you
have to define your models and mappings for the request, response, and integration.hello=lambda_.Function(self,"hello",runtime=lambda_.Runtime.NODEJS_14_X,handler="hello.handler",code=lambda_.Code.from_asset("lambda"))api=apigateway.RestApi(self,"hello-api")resource=api.root.add_resource("v1")You can define more parameters on the integration to tune the behavior of API Gateway# hello: lambda.Functionintegration=apigateway.LambdaIntegration(hello,proxy=False,request_parameters={# 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"},allow_test_invoke=True,request_templates={# 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({"action":"sayHello","poll_id":"$util.escapeJavaScript($input.params('who'))"})},# This parameter defines the behavior of the engine is no suitable response template is foundpassthrough_behavior=apigateway.PassthroughBehavior.NEVER,integration_responses=[apigateway.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 200status_code="200",response_templates={# 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({"state":"ok","greeting":"$util.escapeJavaScript($input.body)"})},response_parameters={# 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'"}),apigateway.IntegrationResponse(# For errors, we check if the error message is not empty, get the error dataselection_pattern="(\n|.)+",# We will set the response status code to 200status_code="400",response_templates={"application/json":JSON.stringify({"state":"error","message":"$util.escapeJavaScript($input.path('$.errorMessage'))"})},response_parameters={"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)# api: apigateway.RestApi# We define the JSON Schema for the transformed valid responseresponse_model=api.add_model("ResponseModel",content_type="application/json",model_name="ResponseModel",schema=apigateway.JsonSchema(schema=apigateway.JsonSchemaVersion.DRAFT4,title="pollResponse",type=apigateway.JsonSchemaType.OBJECT,properties={"state":apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING),"greeting":apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING)}))# We define the JSON Schema for the transformed error responseerror_response_model=api.add_model("ErrorResponseModel",content_type="application/json",model_name="ErrorResponseModel",schema=apigateway.JsonSchema(schema=apigateway.JsonSchemaVersion.DRAFT4,title="errorResponse",type=apigateway.JsonSchemaType.OBJECT,properties={"state":apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING),"message":apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING)}))And reference all on your method definition.# integration: apigateway.LambdaIntegration# resource: apigateway.Resource# response_model: apigateway.Model# error_response_model: apigateway.Modelresource.add_method("GET",integration,# We can mark the parameters as requiredrequest_parameters={"method.request.querystring.who":True},# we can set request validator options like belowrequest_validator_options=apigateway.RequestValidatorOptions(request_validator_name="test-validator",validate_request_body=True,validate_request_parameters=False),method_responses=[apigateway.MethodResponse(# Successful response from the integrationstatus_code="200",# Define what parameters are allowed or notresponse_parameters={"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 responseresponse_models={"application/json":response_model}),apigateway.MethodResponse(# Same thing for the error responsesstatus_code="400",response_parameters={"method.response.header.Content-Type":True,"method.response.header.Access-Control-Allow-Origin":True,"method.response.header.Access-Control-Allow-Credentials":True},response_models={"application/json":error_response_model})])SpecifyingrequestValidatorOptionsautomatically creates the RequestValidator construct with the given options.
However, if you have your RequestValidator already initialized or imported, use therequestValidatoroption instead.Default Integration and Method OptionsThedefaultIntegrationanddefaultMethodOptionsproperties 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 isMockIntegration. See reference
documentation for default method options.The following example defines thebooksBackendintegration 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.# books_backend: apigateway.LambdaIntegrationapi=apigateway.RestApi(self,"books",default_integration=books_backend)books=api.root.add_resource("books")books.add_method("GET")# integrated with `booksBackend`books.add_method("POST")# integrated with `booksBackend`book=books.add_resource("{book_id}")book.add_method("GET")A Method can be configured with authorization scopes. Authorization scopes are
used in conjunction with anauthorizer that uses Amazon Cognito user
pools.
Read more about authorization scopeshere.Authorization scopes for a Method can be configured using theauthorizationScopesproperty as shown below -# books: apigateway.Resourcebooks.add_method("GET",apigateway.HttpIntegration("http://amazon.com"),authorization_type=apigateway.AuthorizationType.COGNITO,authorization_scopes=["Scope1","Scope2"])Proxy RoutesTheaddProxymethod can be used to install a greedy{proxy+}resource
on a path. By default, this also installs an"ANY"method:# resource: apigateway.Resource# handler: lambda.Functionproxy=resource.add_proxy(default_integration=apigateway.LambdaIntegration(handler),# "false" will require explicitly adding methods on the `proxy` resourceany_method=True)AuthorizersAPI Gatewaysupports several different authorization typesthat can be used for controlling access to your REST APIs.IAM-based authorizerThe following CDK code provides 'execute-api' permission to an IAM user, via IAM policies, for the 'GET' method on thebooksresource:# books: apigateway.Resource# iam_user: iam.Userget_books=books.add_method("GET",apigateway.HttpIntegration("http://amazon.com"),authorization_type=apigateway.AuthorizationType.IAM)iam_user.attach_inline_policy(iam.Policy(self,"AllowBooks",statements=[iam.PolicyStatement(actions=["execute-api:Invoke"],effect=iam.Effect.ALLOW,resources=[get_books.method_arn])]))Lambda-based token authorizerAPI Gateway also allowslambda 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 theauthorizationTokenand themethodArnfrom the request to the
API Gateway endpoint. The handler is expected to return theprincipalId(i.e. the client identifier) and apolicyDocumentstating
what the client is authorizer to perform.
Seeherefor 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:# auth_fn: lambda.Function# books: apigateway.Resourceauth=apigateway.TokenAuthorizer(self,"booksAuthorizer",handler=auth_fn)books.add_method("GET",apigateway.HttpIntegration("http://amazon.com"),authorizer=auth)A full working example is shown below.!cdk-integ pragma:ignore-assetsfromaws_cdk.aws_apigatewayimportIntegrationResponse,MethodResponseimportpathaspathimportaws_cdk.aws_lambdaaslambda_fromaws_cdk.coreimportApp,Stackfromaws_cdk.aws_apigatewayimportMockIntegration,PassthroughBehavior,RestApi,TokenAuthorizer## Stack verification steps:# * `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401# * `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>` should return 403# * `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>` should return 200#app=App()stack=Stack(app,"TokenAuthorizerInteg")authorizer_fn=lambda_.Function(stack,"MyAuthorizerFunction",runtime=lambda_.Runtime.NODEJS_14_X,handler="index.handler",code=lambda_.AssetCode.from_asset(path.join(__dirname,"integ.token-authorizer.handler")))restapi=RestApi(stack,"MyRestApi")authorizer=TokenAuthorizer(stack,"MyAuthorizer",handler=authorizer_fn)restapi.root.add_method("ANY",MockIntegration(integration_responses=[IntegrationResponse(status_code="200")],passthrough_behavior=PassthroughBehavior.NEVER,request_templates={"application/json":"{\"statusCode\": 200 }"}),method_responses=[MethodResponse(status_code="200")],authorizer=authorizer)By default, theTokenAuthorizerlooks for the authorization token in the request header with the key 'Authorization'. This can,
however, be modified by changing theidentitySourceproperty.Authorizers can also be passed via thedefaultMethodOptionsproperty within theRestApiconstruct or theMethodconstruct. Unless
explicitly overridden, the specified defaults will be applied across allMethods across theRestApior across allResources,
depending on where the defaults were specified.Lambda-based request authorizerThis 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 themethodArnfrom the request to the
API Gateway endpoint. The handler is expected to return theprincipalId(i.e. the client identifier) and apolicyDocumentstating
what the client is authorizer to perform.
Seeherefor 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:# auth_fn: lambda.Function# books: apigateway.Resourceauth=apigateway.RequestAuthorizer(self,"booksAuthorizer",handler=auth_fn,identity_sources=[apigateway.IdentitySource.header("Authorization")])books.add_method("GET",apigateway.HttpIntegration("http://amazon.com"),authorizer=auth)A full working example is shown below.!cdk-integ pragma:ignore-assetsfromaws_cdk.aws_apigatewayimportIntegrationResponse,MethodResponseimportpathaspathimportaws_cdk.aws_lambdaaslambda_fromaws_cdk.coreimportApp,Stackfromaws_cdk.aws_apigatewayimportMockIntegration,PassthroughBehavior,RestApifromaws_cdk.aws_apigatewayimportRequestAuthorizerfromaws_cdk.aws_apigatewayimportIdentitySource# 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 200app=App()stack=Stack(app,"RequestAuthorizerInteg")authorizer_fn=lambda_.Function(stack,"MyAuthorizerFunction",runtime=lambda_.Runtime.NODEJS_14_X,handler="index.handler",code=lambda_.AssetCode.from_asset(path.join(__dirname,"integ.request-authorizer.handler")))restapi=RestApi(stack,"MyRestApi")authorizer=RequestAuthorizer(stack,"MyAuthorizer",handler=authorizer_fn,identity_sources=[IdentitySource.header("Authorization"),IdentitySource.query_string("allow")])restapi.root.add_method("ANY",MockIntegration(integration_responses=[IntegrationResponse(status_code="200")],passthrough_behavior=PassthroughBehavior.NEVER,request_templates={"application/json":"{\"statusCode\": 200 }"}),method_responses=[MethodResponse(status_code="200")],authorizer=authorizer)By default, theRequestAuthorizerdoes not pass any kind of information from the request. This can,
however, be modified by changing theidentitySourceproperty, and is required when specifying a value for caching.Authorizers can also be passed via thedefaultMethodOptionsproperty within theRestApiconstruct or theMethodconstruct. Unless
explicitly overridden, the specified defaults will be applied across allMethods across theRestApior across allResources,
depending on where the defaults were specified.Cognito User Pools authorizerAPI Gateway also allowsAmazon Cognito user pools as authorizerThe following snippet configures a Cognito user pool as an authorizer:# books: apigateway.Resourceuser_pool=cognito.UserPool(self,"UserPool")auth=apigateway.CognitoUserPoolsAuthorizer(self,"booksAuthorizer",cognito_user_pools=[user_pool])books.add_method("GET",apigateway.HttpIntegration("http://amazon.com"),authorizer=auth,authorization_type=apigateway.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.# acm: Anyapigateway.DomainName(self,"domain-name",domain_name="example.com",certificate=acm.Certificate.from_certificate_arn(self,"cert","arn:aws:acm:us-east-1:1111111:certificate/11-3336f1-44483d-adc7-9cd375c5169d"),mtls=apigateway.MTLSConfig(bucket=s3.Bucket(self,"bucket"),key="truststore.pem",version="version"))Instructions for configuring your trust store can be foundhere.DeploymentsBy default, theRestApiconstruct will automatically create an API GatewayDeploymentand a "prod"Stagewhich represent the API configuration you
defined in your CDK app. This means that when you deploy your app, your API will
be have open access from the internet via the stage URL.The URL of your API can be obtained from the attributerestApi.url, and is
also exported as anOutputfrom your stack, so it's printed when youcdk deployyour app:$cdkdeploy...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 aapigateway.Deploymentandapigateway.Stageresources.Use thedeployOptionsproperty 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:By default, an IAM role will be created and associated with API Gateway to
allow it to write logs and metrics to AWS CloudWatch unlesscloudWatchRoleis
set tofalse.api=apigateway.RestApi(self,"books",deploy_options=apigateway.StageOptions(logging_level=apigateway.MethodLoggingLevel.INFO,data_trace_enabled=True))Deep dive: Invalidation of deploymentsAPI 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 theAWS::ApiGateway::Deploymentresource 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 aredeleted. You can setretainDeployments: trueto allow users revert the stage to an old deployment manually.Custom DomainsTo associate an API with a custom domain, use thedomainNameconfiguration when
you define your API:# acm_certificate_for_example_com: Anyapi=apigateway.RestApi(self,"MyDomain",domain_name=apigateway.DomainNameOptions(domain_name="example.com",certificate=acm_certificate_for_example_com))This will define aDomainNameresource for you, along with aBasePathMappingfrom 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
asexample.com, and for subdomains, such aswww.example.com. (You can create
CNAME records only for subdomains.)importaws_cdk.aws_route53asroute53importaws_cdk.aws_route53_targetsastargets# api: apigateway.RestApi# hosted_zone_for_example_com: Anyroute53.ARecord(self,"CustomDomainAliasRecord",zone=hosted_zone_for_example_com,target=route53.RecordTarget.from_alias(targets.ApiGateway(api)))You can also define aDomainNameresource directly in order to customize the default behavior:# acm_certificate_for_example_com: Anyapigateway.DomainName(self,"custom-domain",domain_name="example.com",certificate=acm_certificate_for_example_com,endpoint_type=apigateway.EndpointType.EDGE,# default is REGIONALsecurity_policy=apigateway.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 URLhttps://example.com/go-to-api1to theapi1API andhttps://example.com/boomto theapi2API.# domain: apigateway.DomainName# api1: apigateway.RestApi# api2: apigateway.RestApidomain.add_base_path_mapping(api1,base_path="go-to-api1")domain.add_base_path_mapping(api2,base_path="boom")You can specify the APIStageto which this base path URL will map to. By default, this will be thedeploymentStageof theRestApi.# domain: apigateway.DomainName# restapi: apigateway.RestApibeta_deploy=apigateway.Deployment(self,"beta-deployment",api=restapi)beta_stage=apigateway.Stage(self,"beta-stage",deployment=beta_deploy)domain.add_base_path_mapping(restapi,base_path="api/beta",stage=beta_stage)If you don't specifybasePath, 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:# domain: apigateway.DomainName# api: apigateway.RestApidomain.add_base_path_mapping(api)This can also be achieved through themappingconfiguration when defining the
domain as demonstrated above.If you wish to setup this domain with an Amazon Route53 alias, use thetargets.ApiGatewayDomain:# hosted_zone_for_example_com: Any# domain_name: apigateway.DomainNameimportaws_cdk.aws_route53asroute53importaws_cdk.aws_route53_targetsastargetsroute53.ARecord(self,"CustomDomainAliasRecord",zone=hosted_zone_for_example_com,target=route53.RecordTarget.from_alias(targets.ApiGatewayDomain(domain_name)))Access LoggingAccess 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 the 'requestId'. The list of  variables that can be expressed in the access
log can be foundhere.
Read more atSetting Up CloudWatch API Logging in API
Gateway# production stageprd_log_group=logs.LogGroup(self,"PrdLogs")api=apigateway.RestApi(self,"books",deploy_options=apigateway.StageOptions(access_log_destination=apigateway.LogGroupLogDestination(prd_log_group),access_log_format=apigateway.AccessLogFormat.json_with_standard_fields()))deployment=apigateway.Deployment(self,"Deployment",api=api)# development stagedev_log_group=logs.LogGroup(self,"DevLogs")apigateway.Stage(self,"dev",deployment=deployment,access_log_destination=apigateway.LogGroupLogDestination(dev_log_group),access_log_format=apigateway.AccessLogFormat.json_with_standard_fields(caller=False,http_method=True,ip=True,protocol=True,request_time=True,resource_path=True,response_length=True,status=True,user=True))The following code will generate the access log in theCLF format.log_group=logs.LogGroup(self,"ApiGatewayAccessLogs")api=apigateway.RestApi(self,"books",deploy_options=apigateway.StageOptions(access_log_destination=apigateway.LogGroupLogDestination(log_group),access_log_format=apigateway.AccessLogFormat.clf()))You can also configure your own access log format by using theAccessLogFormat.custom()API.AccessLogFieldprovides commonly used fields. The following code configures access log to contain.log_group=logs.LogGroup(self,"ApiGatewayAccessLogs")apigateway.RestApi(self,"books",deploy_options=apigateway.StageOptions(access_log_destination=apigateway.LogGroupLogDestination(log_group),access_log_format=apigateway.AccessLogFormat.custom(f"{apigateway.AccessLogField.contextRequestId()}{apigateway.AccessLogField.contextErrorMessage()}{apigateway.AccessLogField.contextErrorMessageString()}")))You can use themethodOptionsproperty to configuredefault method throttlingfor a stage. The following snippet configures the a stage that accepts
100 requests per minute, allowing burst up to 200 requests per minute.api=apigateway.RestApi(self,"books")deployment=apigateway.Deployment(self,"my-deployment",api=api)stage=apigateway.Stage(self,"my-stage",deployment=deployment,method_options={"/*/*":apigateway.MethodDeploymentOptions(# This special path applies to all resource paths and all HTTP methodsthrottling_rate_limit=100,throttling_burst_limit=200)})ConfiguringmethodOptionson thedeployOptionsofRestApiwill set the
throttling behaviors on the default stage that is automatically created.api=apigateway.RestApi(self,"books",deploy_options=apigateway.StageOptions(method_options={"/*/*":apigateway.MethodDeploymentOptions(# This special path applies to all resource paths and all HTTP methodsthrottling_rate_limit=100,throttling_burst_limit=1000)}))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 CORSpreflightOPTIONS
HTTP method to any API resource via thedefaultCorsPreflightOptionsoption or by calling theaddCorsPreflighton a specific resource.The following example will enable CORS for all methods and all origins on all resources of the API:apigateway.RestApi(self,"api",default_cors_preflight_options=apigateway.CorsOptions(allow_origins=apigateway.Cors.ALL_ORIGINS,allow_methods=apigateway.Cors.ALL_METHODS))The following example will add an OPTIONS method to themyResourceAPI resource, which
only allows GET and PUT HTTP requests from the originhttps://amazon.com.# my_resource: apigateway.Resourcemy_resource.add_cors_preflight(allow_origins=["https://amazon.com"],allow_methods=["GET","PUT"])See theCorsOptionsAPI 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: apigateway.Resourcesubtree=resource.add_resource("subtree",default_cors_preflight_options=apigateway.CorsOptions(allow_origins=["https://amazon.com"]))This means that all resources undersubtree(inclusive) will have a preflight
OPTIONS added to them.See#906for a list of CORS
features which are not yet supported.Endpoint ConfigurationAPI gateway allows you to specify anAPI Endpoint Type.
To define an endpoint type for the API gateway, useendpointConfigurationproperty:api=apigateway.RestApi(self,"api",endpoint_configuration=apigateway.EndpointConfiguration(types=[apigateway.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 foundhere.Here is an example:# some_endpoint: ec2.IVpcEndpointapi=apigateway.RestApi(self,"api",endpoint_configuration=apigateway.EndpointConfiguration(types=[apigateway.EndpointType.PRIVATE],vpc_endpoints=[some_endpoint]))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 IntegrationsA 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 ofVpcLinkto encapsulate connections between API
Gateway and targeted VPC resources.
TheVpcLinkis then attached to theIntegrationof a specific API Gateway
Method. The following code sets up a private integration with a network load
balancer -importaws_cdk.aws_elasticloadbalancingv2aselbv2vpc=ec2.Vpc(self,"VPC")nlb=elbv2.NetworkLoadBalancer(self,"NLB",vpc=vpc)link=apigateway.VpcLink(self,"link",targets=[nlb])integration=apigateway.Integration(type=apigateway.IntegrationType.HTTP_PROXY,options=apigateway.IntegrationOptions(connection_type=apigateway.ConnectionType.VPC_LINK,vpc_link=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 theuriproperty.Any existingVpcLinkresource can be imported into the CDK app via theVpcLink.fromVpcLinkId().awesome_link=apigateway.VpcLink.from_vpc_link_id(self,"awesome-vpc-link","us-east-1_oiuR12Abd")Gateway responseIf 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 foundhere.
Learn more aboutGateway
Responses.The following code configures a Gateway Response when the response is 'access denied':api=apigateway.RestApi(self,"books-api")api.add_gateway_response("test-response",type=apigateway.ResponseType.ACCESS_DENIED,status_code="500",response_headers={"Access-Control-Allow-Origin":"test.com","test-key":"test-value"},templates={"application/json":"{\"message\": $context.error.messageString,\"statusCode\":\"488\",\"type\":\"$context.error.responseType\"}"})OpenAPI DefinitionCDK 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 aboutConfiguring a REST API using
OpenAPI.The following code creates a REST API using an external OpenAPI definition JSON file -# integration: apigateway.Integrationapi=apigateway.SpecRestApi(self,"books-api",api_definition=apigateway.ApiDefinition.from_asset("path-to-file.json"))books_resource=api.root.add_resource("books")books_resource.add_method("GET",integration)It is possible to use theaddResource()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 asdefaultIntegration,defaultMethodOptions, etc. will only be
applied to Resources and Methods defined in the CDK, and not the ones defined in the spec. Use theAPI Gateway
extensions to OpenAPIto configure these.There are a number of limitations in using OpenAPI definitions in API Gateway. Read theAmazon API Gateway important
notes for REST APIsfor more details.Note:When starting off with an OpenAPI definition usingSpecRestApi, 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 configurationBy default,SpecRestApiwill create an edge optimized endpoint.This can be modified as shown below:# api_definition: apigateway.ApiDefinitionapi=apigateway.SpecRestApi(self,"ExampleRestApi",api_definition=api_definition,endpoint_types=[apigateway.EndpointType.PRIVATE])Note:For private endpoints you will still need to provide thex-amazon-apigateway-policyandx-amazon-apigateway-endpoint-configurationin your openApi file.MetricsThe 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 theRestApiconstruct.
The APIs with themetricprefix can be used to get reference to specific metrics for this API. For example,
the method below refers to the client side errors metric for this API.api=apigateway.RestApi(self,"my-api")client_error_metric=api.metric_client_error()APIGateway v2APIGateway v2 APIs are now moved to its own package namedaws-apigatewayv2. For backwards compatibility, existing
APIGateway v2 "CFN resources" (such asCfnApi) 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 usingaws-apigatewayv2to get the latest APIs and updates.This module is part of theAWS Cloud Development Kitproject.