Show / Hide Table of Contents

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}.

    RestApi api = new RestApi(this, "books-api");
    
    api.Root.AddMethod("ANY");
    
    Resource books = api.Root.AddResource("books");
    books.AddMethod("GET");
    books.AddMethod("POST");
    
    Resource book = books.AddResource("{book_id}");
    book.AddMethod("GET");
    book.AddMethod("DELETE");

    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;
    
    LambdaRestApi api = new LambdaRestApi(this, "myapi", new LambdaRestApiProps {
        Handler = backend,
        Proxy = false
    });
    
    Resource items = api.Root.AddResource("items");
    items.AddMethod("GET"); // GET /items
    items.AddMethod("POST"); // POST /items
    
    Resource item = items.AddResource("{item}");
    item.AddMethod("GET"); // GET /items/{item}
    
    // the default integration for methods is "handler", but one can
    // customize this behavior per method or even a sub path.
    item.AddMethod("DELETE", new HttpIntegration("http://amazon.com"));

    Additionally, integrationOptions can be supplied to explicitly define options of the Lambda integration:

    Function backend;
    
    
    LambdaRestApi api = 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.

    The response from the invocation contains only the output field from the StartSyncExecution API. In case of failures, the fields error and cause are returned as part of the response. Other metadata such as billing details, AWS account ID and resource ARNs are not returned in the API response.

    By default, a prod stage is provisioned.

    In order to reduce the payload size sent to AWS Step Functions, headers are not forwarded to the Step Functions execution input. It is possible to choose whether headers, requestContext, path, querystring, and authorizer are included or not. By default, headers are excluded in all requests.

    More details about AWS Step Functions payload limit can be found at https://docs.aws.amazon.com/step-functions/latest/dg/limits-overview.html#service-limits-task-executions.

    The following code defines a REST API that routes all requests to the specified AWS StepFunctions state machine:

    Pass stateMachineDefinition = new Pass(this, "PassState");
    
    IStateMachine stateMachine = 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 Amazon.CDK;
    using Constructs;
    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")
        {
    
            RestApi restApi = new RestApi(this, "RestApi", new RestApiProps {
                CloudWatchRole = true,
                Deploy = false
            });
            restApi.Root.AddMethod("ANY");
    
            PetsStack petsStack = new PetsStack(this, new ResourceNestedStackProps {
                RestApiId = restApi.RestApiId,
                RootResourceId = restApi.RestApiRootResourceId
            });
            BooksStack 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)
        {
    
            IRestApi api = RestApi.FromRestApiAttributes(this, "RestApi", new RestApiAttributes {
                RestApiId = props.RestApiId,
                RootResourceId = props.RootResourceId
            });
    
            Method 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)
        {
    
            IRestApi api = RestApi.FromRestApiAttributes(this, "RestApi", new RestApiAttributes {
                RestApiId = props.RestApiId,
                RootResourceId = props.RootResourceId
            });
    
            Method 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)
        {
    
            Deployment 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());

    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;
      
      
      LambdaIntegration getBookIntegration = new LambdaIntegration(getBookHandler);
      book.AddMethod("GET", getBookIntegration);

      Integration options can be optionally be specified:

      Function getBookHandler;
      LambdaIntegration getBookIntegration;
      
      
      LambdaIntegration 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.

      AwsIntegration 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;
      
      
      RestApi api = new RestApi(this, "hello-api");
      
      Resource v1 = api.Root.AddResource("v1");
      Resource echo = v1.AddResource("echo");
      Method echoMethod = echo.AddMethod("GET", integration, new MethodOptions { ApiKeyRequired = true });
      
      UsagePlan plan = api.AddUsagePlan("UsagePlan", new UsagePlanProps {
          Name = "Easy",
          Throttle = new ThrottleSettings {
              RateLimit = 10,
              BurstLimit = 2
          }
      });
      
      IApiKey key = api.AddApiKey("ApiKey");
      plan.AddApiKey(key);

      To associate a plan to a given RestAPI stage:

      UsagePlan plan;
      RestApi api;
      Method echoMethod;
      
      
      plan.AddApiStage(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.

      IUsagePlan importedUsagePlan = UsagePlan.FromUsagePlanId(this, "imported-usage-plan", "<usage-plan-key-id>");

      The name and value of the API Key can be specified at creation; if not provided, a name and value will be automatically generated by API Gateway.

      RestApi api;
      
      IApiKey key = api.AddApiKey("ApiKey", new ApiKeyOptions {
          ApiKeyName = "myApiKey1",
          Value = "MyApiKeyThatIsAtLeast20Characters"
      });

      Existing API keys can also be imported into a CDK app using its id.

      IApiKey importedKey = ApiKey.FromApiKeyId(this, "imported-key", "<api-key-id>");

      The "grant" methods can be used to give prepackaged sets of permissions to other resources. The following code provides read permission to an API key.

      ApiKey importedKey;
      Function lambdaFn;
      
      importedKey.GrantRead(lambdaFn);

      Adding an API Key to an imported RestApi

      API Keys are added to ApiGateway Stages, not to the API itself. When you import a RestApi it does not have any information on the Stages that may be associated with it. Since adding an API Key requires a stage, you should instead add the Api Key to the imported Stage.

      IRestApi restApi;
      
      IStage importedStage = Stage.FromStageAttributes(this, "imported-stage", 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;
      
      
      RateLimitedApiKey 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.

      Function hello = new Function(this, "hello", new FunctionProps {
          Runtime = Runtime.NODEJS_14_X,
          Handler = "hello.handler",
          Code = Code.FromAsset("lambda")
      });
      
      RestApi api = new RestApi(this, "hello-api", new RestApiProps { });
      Resource resource = api.Root.AddResource("v1");

      You can define more parameters on the integration to tune the behavior of API Gateway

      Function hello;
      
      
      LambdaIntegration integration = 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
      Model 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
      Model 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.

      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;
      
      RestApi api = new RestApi(this, "books", new RestApiProps {
          DefaultIntegration = booksBackend
      });
      
      Resource books = api.Root.AddResource("books");
      books.AddMethod("GET"); // integrated with `booksBackend`
      books.AddMethod("POST"); // integrated with `booksBackend`
      
      Resource book = books.AddResource("{book_id}");
      book.AddMethod("GET");

      A Method can be configured with authorization scopes. Authorization scopes are used in conjunction with an authorizer that uses Amazon Cognito user pools. Read more about authorization scopes here.

      Authorization scopes for a Method can be configured using the authorizationScopes property as shown below -

      Resource books;
      
      
      books.AddMethod("GET", new HttpIntegration("http://amazon.com"), 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;
      
      ProxyResource 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;
      
      
      Method 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;
      
      
      TokenAuthorizer 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.

      // Example automatically generated from non-compiling source. May contain errors.
      using Path;
      using Amazon.CDK.AWS.Lambda;
      using Amazon.CDK;
      using Lib;
      
      
      App app = new App();
      Stack stack = new Stack(app, "TokenAuthorizerInteg");
      
      Function authorizerFn = new Function(stack, "MyAuthorizerFunction", new FunctionProps {
          Runtime = Runtime.NODEJS_14_X,
          Handler = "index.handler",
          Code = AssetCode.FromAsset(Join(__dirname, "integ.token-authorizer.handler"))
      });
      
      var authorizer = new TokenAuthorizer(stack, "MyAuthorizer", new Struct {
          Handler = authorizerFn
      });
      
      var restapi = new RestApi(stack, "MyRestApi", new Struct {
          CloudWatchRole = true,
          DefaultMethodOptions = new Struct {
              Authorizer = authorizer
          },
          DefaultCorsPreflightOptions = new Struct {
              AllowOrigins = Cors.ALL_ORIGINS
          }
      });
      
      restapi.Root.AddMethod("ANY", new MockIntegration(new Struct {
          IntegrationResponses = new [] { new Struct { StatusCode = "200" } },
          PassthroughBehavior = PassthroughBehavior.NEVER,
          RequestTemplates = new Struct {
              Application/json = "{ \"statusCode\": 200 }"
          }
      }), new Struct {
          MethodResponses = new [] { new Struct { 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 Methods across the RestApi or across all Resources, depending on where the defaults were specified.

      Lambda-based request authorizer

      This module provides support for request-based Lambda authorizers. When a client makes a request to an API's methods configured with such an authorizer, API Gateway calls the Lambda authorizer, which takes specified parts of the request, known as identity sources, as input and returns an IAM policy as output. A request-based Lambda authorizer (also called a request authorizer) receives the identity sources in a series of values pulled from the request, from the headers, stage variables, query strings, and the context.

      API Gateway interacts with the authorizer Lambda function handler by passing input and expecting the output in a specific format. The event object that the handler is called with contains the body of the request and the methodArn from the request to the API Gateway endpoint. The handler is expected to return the principalId (i.e. the client identifier) and a policyDocument stating what the client is authorizer to perform. See here for a detailed specification on inputs and outputs of the Lambda handler.

      The following code attaches a request-based Lambda authorizer to the 'GET' Method of the Book resource:

      Function authFn;
      Resource books;
      
      
      RequestAuthorizer auth = 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
      
      App app = new App();
      Stack stack = new Stack(app, "RequestAuthorizerInteg");
      
      Function authorizerFn = new Function(stack, "MyAuthorizerFunction", new FunctionProps {
          Runtime = Runtime.NODEJS_14_X,
          Handler = "index.handler",
          Code = AssetCode.FromAsset(Join(__dirname, "integ.request-authorizer.handler"))
      });
      
      RestApi restapi = new RestApi(stack, "MyRestApi", new RestApiProps { CloudWatchRole = true });
      
      RequestAuthorizer authorizer = new RequestAuthorizer(stack, "MyAuthorizer", 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
      });

      By default, the RequestAuthorizer does not pass any kind of information from the request. This can, however, be modified by changing the identitySource property, and is required when specifying a value for caching.

      Authorizers can also be passed via the defaultMethodOptions property within the RestApi construct or the Method construct. Unless explicitly overridden, the specified defaults will be applied across all Methods across the RestApi or across all Resources, depending on where the defaults were specified.

      Cognito User Pools authorizer

      API Gateway also allows Amazon Cognito user pools as authorizer

      The following snippet configures a Cognito user pool as an authorizer:

      Resource books;
      UserPool userPool = new UserPool(this, "UserPool");
      
      CognitoUserPoolsAuthorizer auth = 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 be 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.

      RestApi 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.
      

      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.

      Custom Domains

      To associate an API with a custom domain, use the domainName configuration when you define your API:

      var acmCertificateForExampleCom;
      
      
      RestApi 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;
      
      
      Deployment betaDeploy = new Deployment(this, "beta-deployment", new DeploymentProps {
          Api = restapi
      });
      Stage 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;
      
      
      IDomainName 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;
        
        
        DomainName 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
        LogGroup prdLogGroup = new LogGroup(this, "PrdLogs");
        RestApi api = new RestApi(this, "books", new RestApiProps {
            DeployOptions = new StageOptions {
                AccessLogDestination = new LogGroupLogDestination(prdLogGroup),
                AccessLogFormat = AccessLogFormat.JsonWithStandardFields()
            }
        });
        Deployment deployment = new Deployment(this, "Deployment", new DeploymentProps { Api = api });
        
        // development stage
        LogGroup 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.

        LogGroup logGroup = new LogGroup(this, "ApiGatewayAccessLogs");
        RestApi 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.

        LogGroup 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.

        RestApi api = new RestApi(this, "books");
        Deployment deployment = new Deployment(this, "my-deployment", new DeploymentProps { Api = api });
        Stage 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.

        RestApi 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 } }
                }
            }
        });

        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;
        
        
        Resource 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:

        RestApi 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;
        
        
        RestApi 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;
        
        
        Vpc vpc = new Vpc(this, "VPC");
        NetworkLoadBalancer nlb = new NetworkLoadBalancer(this, "NLB", new NetworkLoadBalancerProps {
            Vpc = vpc
        });
        VpcLink link = new VpcLink(this, "link", new VpcLinkProps {
            Targets = new [] { nlb }
        });
        
        Integration integration = new Integration(new IntegrationProps {
            Type = IntegrationType.HTTP_PROXY,
            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().

        IVpcLink awesomeLink = VpcLink.FromVpcLinkId(this, "awesome-vpc-link", "us-east-1_oiuR12Abd");

        Gateway response

        If the Rest API fails to process an incoming request, it returns to the client an error response without forwarding the request to the integration backend. API Gateway has a set of standard response messages that are sent to the client for each type of error. These error responses can be configured on the Rest API. The list of Gateway responses that can be configured can be found here. Learn more about Gateway Responses.

        The following code configures a Gateway Response when the response is 'access denied':

        RestApi api = new RestApi(this, "books-api");
        api.AddGatewayResponse("test-response", 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;
        
        
        SpecRestApi api = new SpecRestApi(this, "books-api", new SpecRestApiProps {
            ApiDefinition = ApiDefinition.FromAsset("path-to-file.json")
        });
        
        Resource booksResource = api.Root.AddResource("books");
        booksResource.AddMethod("GET", integration);

        It is possible to use the addResource() API to define additional API Gateway Resources.

        Note: Deployment will fail if a Resource of the same name is already defined in the Open API specification.

        Note: Any default properties configured, such as defaultIntegration, defaultMethodOptions, etc. will only be applied to Resources and Methods defined in the CDK, and not the ones defined in the spec. Use the API Gateway extensions to OpenAPI to configure these.

        There are a number of limitations in using OpenAPI definitions in API Gateway. Read the Amazon API Gateway important notes for REST APIs for more details.

        Note: When starting off with an OpenAPI definition using SpecRestApi, it is not possible to configure some properties that can be configured directly in the OpenAPI specification file. This is to prevent people duplication of these properties and potential confusion.

        Endpoint configuration

        By default, SpecRestApi will create an edge optimized endpoint.

        This can be modified as shown below:

        ApiDefinition apiDefinition;
        
        
        SpecRestApi 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:

        RestApi api = new RestApi(this, "my-api");
        Stage stage = api.DeploymentStage;
        Method method = api.Root.AddMethod("GET");
        
        Metric clientErrorApiMetric = api.MetricClientError();
        Metric serverErrorStageMetric = stage.MetricServerError();
        Metric latencyMethodMetric = method.MetricLatency(stage);

        APIGateway v2

        APIGateway v2 APIs are now moved to its own package named aws-apigatewayv2. 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

        A CloudFormation AWS::ApiGateway::Account.

        CfnAccountProps

        Properties for defining a CfnAccount.

        CfnApiKey

        A CloudFormation AWS::ApiGateway::ApiKey.

        CfnApiKey.StageKeyProperty

        StageKey is a property of the AWS::ApiGateway::ApiKey resource that specifies the stage to associate with the API key. This association allows only clients with the key to make requests to methods in that stage.

        CfnApiKeyProps

        Properties for defining a CfnApiKey.

        CfnAuthorizer

        A CloudFormation AWS::ApiGateway::Authorizer.

        CfnAuthorizerProps

        Properties for defining a CfnAuthorizer.

        CfnBasePathMapping

        A CloudFormation AWS::ApiGateway::BasePathMapping.

        CfnBasePathMappingProps

        Properties for defining a CfnBasePathMapping.

        CfnClientCertificate

        A CloudFormation AWS::ApiGateway::ClientCertificate.

        CfnClientCertificateProps

        Properties for defining a CfnClientCertificate.

        CfnDeployment

        A CloudFormation AWS::ApiGateway::Deployment.

        CfnDeployment.AccessLogSettingProperty

        The AccessLogSetting property type specifies settings for logging access in this stage.

        CfnDeployment.CanarySettingProperty

        The CanarySetting property type specifies settings for the canary deployment in this stage.

        CfnDeployment.DeploymentCanarySettingsProperty

        The DeploymentCanarySettings property type specifies settings for the canary deployment.

        CfnDeployment.MethodSettingProperty

        The MethodSetting property type configures settings for all methods in a stage.

        CfnDeployment.StageDescriptionProperty

        StageDescription is a property of the AWS::ApiGateway::Deployment resource that configures a deployment stage.

        CfnDeploymentProps

        Properties for defining a CfnDeployment.

        CfnDocumentationPart

        A CloudFormation AWS::ApiGateway::DocumentationPart.

        CfnDocumentationPart.LocationProperty

        The Location property specifies the location of the Amazon API Gateway API entity that the documentation applies to.

        CfnDocumentationPartProps

        Properties for defining a CfnDocumentationPart.

        CfnDocumentationVersion

        A CloudFormation AWS::ApiGateway::DocumentationVersion.

        CfnDocumentationVersionProps

        Properties for defining a CfnDocumentationVersion.

        CfnDomainName

        A CloudFormation AWS::ApiGateway::DomainName.

        CfnDomainName.EndpointConfigurationProperty

        The EndpointConfiguration property type specifies the endpoint types of an Amazon API Gateway domain name.

        CfnDomainName.MutualTlsAuthenticationProperty

        The mutual TLS authentication configuration for a custom domain name.

        CfnDomainNameProps

        Properties for defining a CfnDomainName.

        CfnGatewayResponse

        A CloudFormation AWS::ApiGateway::GatewayResponse.

        CfnGatewayResponseProps

        Properties for defining a CfnGatewayResponse.

        CfnMethod

        A CloudFormation AWS::ApiGateway::Method.

        CfnMethod.IntegrationProperty

        Integration is a property of the AWS::ApiGateway::Method resource that specifies information about the target backend that a method calls.

        CfnMethod.IntegrationResponseProperty

        IntegrationResponse is a property of the Amazon API Gateway Method Integration property type that specifies the response that API Gateway sends after a method's backend finishes processing a request.

        CfnMethod.MethodResponseProperty

        Represents a method response of a given HTTP status code returned to the client.

        CfnMethodProps

        Properties for defining a CfnMethod.

        CfnModel

        A CloudFormation AWS::ApiGateway::Model.

        CfnModelProps

        Properties for defining a CfnModel.

        CfnRequestValidator

        A CloudFormation AWS::ApiGateway::RequestValidator.

        CfnRequestValidatorProps

        Properties for defining a CfnRequestValidator.

        CfnResource

        A CloudFormation AWS::ApiGateway::Resource.

        CfnResourceProps

        Properties for defining a CfnResource.

        CfnRestApi

        A CloudFormation AWS::ApiGateway::RestApi.

        CfnRestApi.EndpointConfigurationProperty

        The EndpointConfiguration property type specifies the endpoint types of a REST API.

        CfnRestApi.S3LocationProperty

        S3Location is a property of the AWS::ApiGateway::RestApi resource that specifies the Amazon S3 location of a OpenAPI (formerly Swagger) file that defines a set of RESTful APIs in JSON or YAML.

        CfnRestApiProps

        Properties for defining a CfnRestApi.

        CfnStage

        A CloudFormation AWS::ApiGateway::Stage.

        CfnStage.AccessLogSettingProperty

        The AccessLogSetting property type specifies settings for logging access in this stage.

        CfnStage.CanarySettingProperty

        Configuration settings of a canary deployment.

        CfnStage.MethodSettingProperty

        The MethodSetting property type configures settings for all methods in a stage.

        CfnStageProps

        Properties for defining a CfnStage.

        CfnUsagePlan

        A CloudFormation AWS::ApiGateway::UsagePlan.

        CfnUsagePlan.ApiStageProperty

        API stage name of the associated API stage in a usage plan.

        CfnUsagePlan.QuotaSettingsProperty

        QuotaSettings is a property of the AWS::ApiGateway::UsagePlan resource that specifies a target for the maximum number of requests users can make to your REST APIs.

        CfnUsagePlan.ThrottleSettingsProperty

        ThrottleSettings is a property of the AWS::ApiGateway::UsagePlan resource that specifies the overall request rate (average requests per second) and burst capacity when users call your REST APIs.

        CfnUsagePlanKey

        A CloudFormation AWS::ApiGateway::UsagePlanKey.

        CfnUsagePlanKeyProps

        Properties for defining a CfnUsagePlanKey.

        CfnUsagePlanProps

        Properties for defining a CfnUsagePlan.

        CfnVpcLink

        A CloudFormation AWS::ApiGateway::VpcLink.

        CfnVpcLinkProps

        Properties for defining a CfnVpcLink.

        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
        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 requestContext.

        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.

        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

        StageKey is a property of the AWS::ApiGateway::ApiKey resource that specifies the stage to associate with the API key. This association allows only clients with the key to make requests to methods in that stage.

        CfnDeployment.IAccessLogSettingProperty

        The AccessLogSetting property type specifies settings for logging access in this stage.

        CfnDeployment.ICanarySettingProperty

        The CanarySetting property type specifies settings for the canary deployment in this stage.

        CfnDeployment.IDeploymentCanarySettingsProperty

        The DeploymentCanarySettings property type specifies settings for the canary deployment.

        CfnDeployment.IMethodSettingProperty

        The MethodSetting property type configures settings for all methods in a stage.

        CfnDeployment.IStageDescriptionProperty

        StageDescription is a property of the AWS::ApiGateway::Deployment resource that configures a deployment stage.

        CfnDocumentationPart.ILocationProperty

        The Location property specifies the location of the Amazon API Gateway API entity that the documentation applies to.

        CfnDomainName.IEndpointConfigurationProperty

        The EndpointConfiguration property type specifies the endpoint types of an Amazon API Gateway domain name.

        CfnDomainName.IMutualTlsAuthenticationProperty

        The mutual TLS authentication configuration for a custom domain name.

        CfnMethod.IIntegrationProperty

        Integration is a property of the AWS::ApiGateway::Method resource that specifies information about the target backend that a method calls.

        CfnMethod.IIntegrationResponseProperty

        IntegrationResponse is a property of the Amazon API Gateway Method Integration property type that specifies the response that API Gateway sends after a method's backend finishes processing a request.

        CfnMethod.IMethodResponseProperty

        Represents a method response of a given HTTP status code returned to the client.

        CfnRestApi.IEndpointConfigurationProperty

        The EndpointConfiguration property type specifies the endpoint types of a REST API.

        CfnRestApi.IS3LocationProperty

        S3Location is a property of the AWS::ApiGateway::RestApi resource that specifies the Amazon S3 location of a OpenAPI (formerly Swagger) file that defines a set of RESTful APIs in JSON or YAML.

        CfnStage.IAccessLogSettingProperty

        The AccessLogSetting property type specifies settings for logging access in this stage.

        CfnStage.ICanarySettingProperty

        Configuration settings of a canary deployment.

        CfnStage.IMethodSettingProperty

        The MethodSetting property type configures settings for all methods in a stage.

        CfnUsagePlan.IApiStageProperty

        API stage name of the associated API stage in a usage plan.

        CfnUsagePlan.IQuotaSettingsProperty

        QuotaSettings is a property of the AWS::ApiGateway::UsagePlan resource that specifies a target for the maximum number of requests users can make to your REST APIs.

        CfnUsagePlan.IThrottleSettingsProperty

        ThrottleSettings is a property of the AWS::ApiGateway::UsagePlan resource that specifies the overall request rate (average requests per second) and burst capacity when users call your REST APIs.

        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 CfnAccount.

        ICfnApiKeyProps

        Properties for defining a CfnApiKey.

        ICfnAuthorizerProps

        Properties for defining a CfnAuthorizer.

        ICfnBasePathMappingProps

        Properties for defining a CfnBasePathMapping.

        ICfnClientCertificateProps

        Properties for defining a CfnClientCertificate.

        ICfnDeploymentProps

        Properties for defining a CfnDeployment.

        ICfnDocumentationPartProps

        Properties for defining a CfnDocumentationPart.

        ICfnDocumentationVersionProps

        Properties for defining a CfnDocumentationVersion.

        ICfnDomainNameProps

        Properties for defining a CfnDomainName.

        ICfnGatewayResponseProps

        Properties for defining a CfnGatewayResponse.

        ICfnMethodProps

        Properties for defining a CfnMethod.

        ICfnModelProps

        Properties for defining a CfnModel.

        ICfnRequestValidatorProps

        Properties for defining a CfnRequestValidator.

        ICfnResourceProps

        Properties for defining a CfnResource.

        ICfnRestApiProps

        Properties for defining a CfnRestApi.

        ICfnStageProps

        Properties for defining a CfnStage.

        ICfnUsagePlanKeyProps

        Properties for defining a CfnUsagePlanKey.

        ICfnUsagePlanProps

        Properties for defining a CfnUsagePlan.

        ICfnVpcLinkProps

        Properties for defining a CfnVpcLink.

        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 requestContext.

        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.

        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.

        Back to top Generated by DocFX