Module apigateway

@pulumi/awsx > apigateway

Pulumi API Gateway Components

Pulumi’s API for simplifying working with API Gateway. The API currently provides ways to define routes that accepts and forwards traffic to a specified destination. A route is a publicly accessible URI that supports the defined HTTP methods and responds according to the route definition.

Defining an Endpoint

To define an endpoint you will need to specify a route. You can also define the stage name (else it will default to “stage”). A stage is an addressable instance of the Rest API.

Routes

The destination is determined by the route, which can be an Event Handler Route, a Static Route, an Integration Route or a Raw Data Route.

Event Handler Route

An Event Handler Route is a route that will map to a Lambda. You will need to specify the path, method and the Lambda. Pulumi allows you to define the Lambda inline with your application code and provisions the appropriate permissions on your behalf so that API Gateway can communicate with your Lambda.

import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/",
        method: "GET",
        eventHandler: async (event) => {
            // This code runs in an AWS Lambda and will be invoked any time `/` is hit.
            return {
                statusCode: 200,
                body: "hello",
            };
        },
    }],
})

A complete example can be found here.

You can also link a route to an existing Lambda using aws.lambda.Function.get.

import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/",
        method: "GET",
        eventHandler: aws.lambda.Function.get("example", "your_lambda_id"),
    }],
})

Additionally, you can control the Lambda that is created by calling new aws.lambda.CallbackFunction.

import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/",
        method: "GET",
        eventHandler: new aws.lambda.CallbackFunction("test", {
            memorySize: 256,
            callback: async (event) => {
                return {
                    statusCode: 200,
                    body: "<h1>Hello world!</h1>",
                };
            },
        }),
    }],
})

Static Route

A Static Route is a route that will map to static content in files/directories. You will need to define the local path and then the files (and subdirectories) will be uploaded into S3 objects. If the local path points to a file, you can specify the content-type. Else, the content types for all files in a directory are inferred.

By default, any request on directory will serve index.html. This behavior can be disabled by setting the index field to false.

import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/www",
        localPath: "www",
        index: false,
    }],
})

A complete example can be found here.

Integration Route

An Integration Route is a route that will map an endpoint to a specified backend. The supported types are:

* `http` or `http_proxy`: integration with an HTTP backend
* `aws_proxy`: integration with AWS Lambda functions
* `aws`: integration with AWS Lambda functions or other AWS services, such as Amazon DynamoDB, Amazon Simple Notification Service or Amazon Simple Queue Service
* `mock`: integration with API Gateway without invoking any backend
import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/integration",
        target: {
            uri: "https://www.google.com",
            type: "http_proxy",
        },
    }],
})

For more information API Integrations, visit the AWS documentation.

Raw Data Route

A Raw Data Route is a fallback route for when raw swagger control is desired. The data field should be an object that will be then included in the final swagger specification. For more information on the x-amazon-apigateway-integration swagger object, visit the AWS documentation.

import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/rawdata",
        method: "GET",
        data: {
            "x-amazon-apigateway-integration": {
                "uri": "https://www.google.com/",
                "responses": {
                    "default": {
                        "statusCode": "200",
                    },
                },
                "passthroughBehavior": "when_no_match",
                "httpMethod": "GET",
                "type": "http_proxy",
            },
        },
    }],
})

Request Validation

API Gateway can perform basic validations against request parameters, a request payload or both. When a validation fails, a 400 error is returned immediately.

Validators

Validators can be assigned at the API level or at the method level. The validators defined at a method level override any validator set at the API level.

You must specify one of the following validators:

  • “ALL” - validate both the request body and request parameters
  • “BODY_ONLY” - validate only the request body
  • “PARAMS_ONLY” - validate only the request parameters
import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/www",
        localPath: "www",
        index: false,
        requestValidator: "PARAMS_ONLY",
    }],
    requestValidator: "ALL",
})

Request Parameters

For each required request parameter, you must define the name and where the parameter is expected (i.e. “path”, “query”, or “header”).

import * as awsx from "@pulumi/awsx";

let endpoint = new awsx.apigateway.API("example", {
    routes: [{
        path: "/www",
        localPath: "www",
        index: false,
        requestValidator: "PARAMS_ONLY",
        requiredParams: [{
            name: "key",
            in: "query",
        }]
    }],
})

Request Body

Request body validation is currently not supported. If you have a strong use case, please comment on this open issue.

API Keys

To require an API Key for an API Gateway route you set the apiKeyRequired property equal to true. At the API level, you can choose if you want the API Key source to be HEADER (i.e. client includes a x-api-key header with the API Key) or AUTHORIZER (i.e. a Lambda authorizer sends the API Key as part of the authorization response). If the API Key source is not set, then the source will default to HEADER.

import * as awsx from "@pulumi/awsx";

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        path: "/a",
        method: "GET",
        eventHandler: async () => {
            return {
                statusCode: 200,
                body: "<h1>Hello world!</h1>",
            };
        },
        apiKeyRequired: true,
    }],
    apikeySource: "AUTHORIZER",
});

You will also need to create a usage plan (new aws.apigateway.UsagePlan) and an API key (new aws.apigateway.ApiKey) and then associate the key with the usage plan (new aws.apigateway.UsagePlanKey). To simplify the creation of API Keys associated with your API you can use awsx.apigateway.createAssociatedAPIKeys, which create a Usage Plan, API Keys and associates the API Keys by creating a UsagePlanKey. Below is an example of using this helper function:

import * as awsx from "@pulumi/awsx";

const apikeys = awsx.apigateway.createAssociatedAPIKeys("my-api-keys", {
    apis: [api],
    apiKeys: [{
        name: "test-key",
    }],
});

 // Export the API Key if desired
export const apiKeyValue = apikeys.keys[0].apikey.value;

awsx.apigateway.createAssociatedAPIKeys will return an object that contains the Usage Plan, API Keys and Usage Plan Keys. Instead of providing the APIs, you can also specify the api stages for the Usage Plan as follows:

import * as awsx from "@pulumi/awsx";

const apikeys = awsx.apigateway.createAssociatedAPIKeys("my-api-keys", {
    usagePlan: {
        apiStages: [{
            apiId: api.restAPI.id,
            stage: api.stage.stageName,
        }],
    },
    apiKeys: [{
        name: "test-key",
    }],
});

Lambda Authorizers

Lambda Authorizers are AWS Lambda functions that provide control access to an API. You can define a Lambda Authorizer for an Event Handler Route or a Static Route. API Gateway supports request or token type Lambda authorizers. A token Lambda Authorizer uses an authorization token (i.e. a header in the form Authorization: Token <token>) to authorize the user, whereas a request Lambda Authorizer uses the request parameters (i.e. headers, path parameter or query parameters).

To define an Authorizer, you provide a Lambda that fulfills aws.lambda.EventHandler<AuthorizerEvent, AuthorizerResponse> or you provide information on a pre-existing Lambda authorizer. The example below shows defining the Authorizer Lambda directly inline. See the Event Handler Route section for other ways you can define a Lambda for the Authorizer.

Request Authorizer

Below is an example of a custom request Lambda Authorizer that uses awsx.apigateway.getRequestLambdaAuthorizer to simplify defining the authorizer.

import * as awsx from "@pulumi/awsx";

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        path: "/b",
        method: "GET",
        eventHandler: async () => {
            return {
                statusCode: 200,
                body: "<h1>Hello world!</h1>",
            };
        },
        authorizers: [awsx.apigateway.getRequestLambdaAuthorizer({
            queryParameters: ["auth"],
            handler: async (event: awsx.apigateway.AuthorizerEvent) => {
                // Add your own custom authorization logic here.
                // Access the headers using event.headers, the query parameters using
                // event.queryStringParameters or path parameters using event.pathParameters
                return awsx.apigateway.authorizerResponse("user", "Allow", event.methodArn);
            },
        })],
    }],
});

You may also define the authorizer by specifying all the values. As seen below:

import * as awsx from "@pulumi/awsx";

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        ...
        authorizers: [{
            authorizerName: "prettyAuthorizer",
            parameterName: "auth",
            parameterLocation: "query",
            authType: "custom",
            type: "request",
            handler: async (event: awsx.apigateway.AuthorizerEvent) => {
                // Add your own custom authorization logic here.
                return awsx.apigateway.authorizerResponse(
                    "user",
                    "Allow",
                    event.methodArn);
            },
            identitySource: ["method.request.querystring.auth"],
        }],
    }],
});

Token Authorizer

Below is an example of a custom token Lambda Authorizer that uses awsx.apigateway. to simplify the creation of the authorizer.

import * as awsx from "@pulumi/awsx";

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        path: "/b",
        method: "GET",
        eventHandler: async () => {
            return {
                statusCode: 200,
                body: "<h1>Hello world!</h1>",
            };
        },
        authorizers: [awsx.apigateway.getTokenLambdaAuthorizer({
            handler: async (event: awsx.apigateway.AuthorizerEvent) => {
                // Add your own custom authorization logic here.
                const token = event.authorizationToken;
                if (token === "Allow") {
                    return awsx.apigateway.authorizerResponse("user","Allow", event.methodArn);
                }
                return awsx.apigateway.authorizerResponse("user", "Deny", event.methodArn);
            },
        })],
    }],
});

You may also define the authorizer by specifying all the values. As seen below:

import * as awsx from "@pulumi/awsx";

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        path: "/b",
        method: "GET",
        eventHandler: async () => {
            return {
                statusCode: 200,
                body: "<h1>Hello world!</h1>",
            };
        },
        authorizers: [{
            parameterName: "Authorization",
            parameterLocation: "header",
            authType: "oauth2",
            type: "request",
            handler: async (event: awsx.apigateway.AuthorizerEvent) => {
                // Add your own custom authorization logic here.
                 return awsx.apigateway.authorizerResponse("user", "Allow", event.methodArn);
            },
        }],
    }],
});

Specifying the Role

If your Authorizer requires access to other AWS resources, you will need to provision the appropriate role. You can do so by using new aws.lambda.CallbackFunction.

import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";

const callbackFxn = new aws.lambda.CallbackFunction("callbackFxn", {
    callback: async (event: awsx.apigateway.AuthorizerEvent) => {
        // Add custom authorization logic here
        return awsx.apigateway.authorizerResponse("user", "Allow", event.methodArn);
    },
    role: role, // Specify role with appropriate AWS permissions.
});

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        path: "/b",
        method: "GET",
        eventHandler: async () => {
            return {
                statusCode: 200,
                body: "<h1>Hello world!</h1>",
            };
        },
        authorizers: [{
            parameterName: "Authorization",
            parameterLocation: "header",
            authType: "oauth2",
            type: "request",
            handler: callbackFxn,
        }],
    }],
});

Using a Pre-existing AWS Lambda

You can also define the Lambda Authorizer elsewhere and then reference the required values.

import * as awsx from "@pulumi/awsx";

const apiWithAuthorizer = new awsx.apigateway.API("authorizer-api", {
    routes: [{
        ...
        authorizers: [{
            authorizerName: "testing",
            parameterName: "auth",
            parameterLocation: "query",
            authType: "custom",
            type: "request",
            handler: {
                // Either specify the aws.lambda.Function or provide the invoke URI
                uri: authorizerLambda,
                credentials: gatewayRole.arn,
            },
            identitySource: ["method.request.querystring.auth"],
        }],
    }],
});

A complete example of defining the Lambda Authorizer elsewhere can be found here.

Authorizer Response

A helper function awsx.apigateway.authorizerResponse has been created to simplify generating the authorizer response. This can be used when defining the authorizer handler as follows:

import * as awsx from "@pulumi/awsx";

const api = new awsx.apigateway.API("myapi", {
    routes: [{
        ...
        authorizers: [{
            header: "Authorization",
            handler: async (event: awsx.apigateway.AuthorizerEvent) => {
                // Add your own custom authorization logic here.
                const token = event.authorizationToken;
                if (token === "Allow") {
                    return awsx.apigateway.authorizerResponse("user", "Allow", event.methodArn);
                }
                return awsx.apigateway.authorizerResponse("user", "Deny", event.methodArn);
            },
        }],
    }],
});

Cognito Authorizers

Cognito Authorizers allow you to use Amazon Cognito User Pools as an Authorizer for API Gateway. This will require users to sign in to the user pool, obtain an identity/access token and then call your API with said token.

import * as awsx from "@pulumi/awsx";

// Create an AWS Cognito User Pool
const cognitoUserPool = new aws.cognito.UserPool("pool", {});

// Create an API that requires authorizes against the User Pool
const apiWithCognitoAuthorizer = new awsx.apigateway.API("cognito-protected-api", {
    routes: [{
        path: "/www_old",
        localPath: "www",
        authorizers: [awsx.apigateway.getCognitoAuthorizer({
            providerARNs: [cognitoUserPool],
        })],
    }],
});

Swagger String

You can use a OpenAPI specification that is in string form to initialize the API Gateway. This in a way is an escape hatch for implementing featured not yet supported by Pulumi. You must manually provide permission for any route targets to be invoked by API Gateway when using this option.

import * as awsx from "@pulumi/awsx";

const swaggerSpec = {
    swagger: "2.0",
    info: { title: "api", version: "1.0" },
    ...
};

let endpoint = new awsx.apigateway.API("example", {
    swaggerString: JSON.stringify(swaggerSpec),
    stageName: "dev",
})

class API

extends ComponentResource

constructor

new API(name: string, args: APIArgs, opts: pulumi.ComponentResourceOptions)

method getFunction

public getFunction(route?: undefined | string, method?: Method): aws.lambda.Function

Returns the [aws.lambda.Function] an [EventHandlerRoute] points to. This will either be for the aws.lambda.Function created on your behalf if the route was passed a normal JavaScript/Typescript function, or it will be the [aws.lambda.Function] that was explicitly passed in.

[route] and [method] can both be elided if this API only has a single [EventHandlerRoute] assigned to it.

[method] can be elided if [route] only has a single [EventHandlerRoute] assigned to it.

This method will throw if the provided [route] and [method] do not resolve to a single [aws.lambda.Function]

method getProvider

getProvider(moduleMember: string): ProviderResource | undefined

method isInstance

static isInstance(obj: any): boolean

Returns true if the given object is an instance of CustomResource. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.

method registerOutputs

protected registerOutputs(outputs?: Inputs | Promise<Inputs> | Output<Inputs>): void

property deployment

public deployment: aws.apigateway.Deployment;

property restAPI

public restAPI: aws.apigateway.RestApi;

property stage

public stage: aws.apigateway.Stage;

property staticRoutesBucket

public staticRoutesBucket?: aws.s3.Bucket;

Bucket where static resources were placed. Only set if a Bucket was provided to the API at construction time, or if there were any [StaticRoute]s passed to the API.

property url

public url: pulumi.Output<string>;

property urn

urn: Output<URN>;

urn is the stable logical URN used to distinctly address a resource, both before and after deployments.

interface APIArgs

property apiKeySource

apiKeySource?: APIKeySource;

The source for the apikey. This can either be a HEADER or AUTHORIZER. If [apiKeyRequired] is set to true on a route, and this is not defined the value will default to HEADER.

property gatewayResponses

gatewayResponses?: Record<string, SwaggerGatewayResponse>;

Define custom gateway responses for the API. This can be used to properly enable CORS for Lambda Authorizers.

property requestValidator

requestValidator?: RequestValidator;

Request Validator specifies the validator to use at the API level. Note method level validators override this.

property routes

routes?: Route[];

Routes to use to initialize the APIGateway.

Either [swaggerString] or [routes] must be specified.

property stageName

stageName?: pulumi.Input<string>;

The stage name for your API. This will get added as a base path to your API url.

property staticRoutesBucket

staticRoutesBucket?: aws.s3.Bucket | aws.s3.BucketArgs;

Bucket to use for placing resources for static resources. If not provided a default one will be created on your behalf if any [StaticRoute]s are provided.

property swaggerString

swaggerString?: pulumi.Input<string>;

A Swagger specification already in string form to use to initialize the APIGateway. Note that you must manually provide permission for any route targets to be invoked by API Gateway when using [swaggerString].

Either [swaggerString] or [routes] must be specified.

interface BaseRoute

property apiKeyRequired

apiKeyRequired?: undefined | false | true;

If true, an API key will be required for this route. The source for the API Key can be set at the API level and by default, the source will be the HEADER.

property authorizers

authorizers?: Authorizer[] | Authorizer;

Authorizers allows you to define Lambda authorizers be applied for authorization when the the route is called.

property requestValidator

requestValidator?: RequestValidator;

Request Validator specifies the validator to use at the method level. This will override anything defined at the API level.

property requiredParameters

requiredParameters?: reqvalidation.Parameter[];

Required Parameters to validate. If the request validator is set to ALL or PARAMS_ONLY, api gateway will validate these before sending traffic to the event handler.

interface Endpoint

property hostname

hostname: string;

property loadBalancer

loadBalancer: aws.lb.LoadBalancer;

property port

port: number;

interface EventHandlerRoute

extends BaseRoute

property apiKeyRequired

apiKeyRequired?: undefined | false | true;

If true, an API key will be required for this route. The source for the API Key can be set at the API level and by default, the source will be the HEADER.

property authorizers

authorizers?: Authorizer[] | Authorizer;

Authorizers allows you to define Lambda authorizers be applied for authorization when the the route is called.

property eventHandler

eventHandler: aws.lambda.EventHandler<Request, Response>;

property method

method: Method;

property path

path: string;

The path on the API that will invoke the provided [eventHandler]. If not prefixed with /, then a / will be added automatically to the beginning.

property requestValidator

requestValidator?: RequestValidator;

Request Validator specifies the validator to use at the method level. This will override anything defined at the API level.

property requiredParameters

requiredParameters?: reqvalidation.Parameter[];

Required Parameters to validate. If the request validator is set to ALL or PARAMS_ONLY, api gateway will validate these before sending traffic to the event handler.

interface IntegrationRoute

extends BaseRoute

An apigateway route for an integration. https://docs.aws.amazon.com/apigateway/api-reference/resource/integration/ for more details.

property apiKeyRequired

apiKeyRequired?: undefined | false | true;

If true, an API key will be required for this route. The source for the API Key can be set at the API level and by default, the source will be the HEADER.

property authorizers

authorizers?: Authorizer[] | Authorizer;

Authorizers allows you to define Lambda authorizers be applied for authorization when the the route is called.

property path

path: string;

The path on the API that will invoke the provided [target]. If not prefixed with /, then a / will be added automatically to the beginning.

property requestValidator

requestValidator?: RequestValidator;

Request Validator specifies the validator to use at the method level. This will override anything defined at the API level.

property requiredParameters

requiredParameters?: reqvalidation.Parameter[];

Required Parameters to validate. If the request validator is set to ALL or PARAMS_ONLY, api gateway will validate these before sending traffic to the event handler.

property target

interface IntegrationRouteTargetProvider

interface IntegrationTarget

See https://docs.aws.amazon.com/apigateway/api-reference/resource/integration/ for more details.

property connectionId

connectionId?: pulumi.Input<string>;

The (id) of the VpcLink used for the integration when connectionType=VPC_LINK and undefined, otherwise.

property connectionType

connectionType?: pulumi.Input<IntegrationConnectionType>;

The type of the network connection to the integration endpoint. The valid value is INTERNET for connections through the public routable internet or VPC_LINK for private connections between API Gateway and a network load balancer in a VPC. The default value is INTERNET.

property httpMethod

httpMethod?: undefined | “ANY”;

Specifies the integration’s HTTP method type. Currently, the only supported type is ‘ANY’.

property passthroughBehavior

passthroughBehavior?: pulumi.Input<IntegrationPassthroughBehavior>;

Specifies how the method request body of an unmapped content type will be passed through the integration request to the back end without transformation.

The valid value is one of the following:

WHEN_NO_MATCH: passes the method request body through the integration request to the back end without transformation when the method request content type does not match any content type associated with the mapping templates defined in the integration request.

WHEN_NO_TEMPLATES: passes the method request body through the integration request to the back end without transformation when no mapping template is defined in the integration request. If a template is defined when this option is selected, the method request of an unmapped content-type will be rejected with an HTTP 415 Unsupported Media Type response.

NEVER: rejects the method request with an HTTP 415 Unsupported Media Type response when either the method request content type does not match any content type associated with the mapping templates defined in the integration request or no mapping template is defined in the integration request.

Defaults to ‘WHEN_NO_MATCH’ if unspecified.

property type

type: pulumi.Input<IntegrationType>;

Specifies an API method integration type. The valid value is one of the following:

aws: for integrating the API method request with an AWS service action, including the Lambda function-invoking action. With the Lambda function-invoking action, this is referred to as the Lambda custom integration. With any other AWS service action, this is known as AWS integration.

aws_proxy: for integrating the API method request with the Lambda function-invoking action with the client request passed through as-is. This integration is also referred to as the Lambda proxy integration.

http: for integrating the API method request with an HTTP endpoint, including a private HTTP endpoint within a VPC. This integration is also referred to as the HTTP custom integration.

http_proxy: for integrating the API method request with an HTTP endpoint, including a private HTTP endpoint within a VPC, with the client request passed through as-is. This is also referred to as the HTTP proxy integration.

mock: for integrating the API method request with API Gateway as a “loop-back” endpoint without invoking any backend.

property uri

uri: pulumi.Input<string>;

Specifies Uniform Resource Identifier (URI) of the integration endpoint.

For HTTP or HTTP_PROXY integrations, the URI must be a fully formed, encoded HTTP(S) URL according to the RFC-3986 specification, for either standard integration, where connectionType is not VPC_LINK, or private integration, where connectionType is VPC_LINK. For a private HTTP integration, the URI is not used for routing.

For AWS or AWS_PROXY integrations, the URI is of the form arn:aws:apigateway:{region}:{subdomain.service|service}:path|action/{service_api}. Here, {Region} is the API Gateway region (e.g., us-east-1); {service} is the name of the integrated AWS service (e.g., s3); and {subdomain} is a designated subdomain supported by certain AWS service for fast host-name lookup. action can be used for an AWS service action-based API, using an Action={name}&{p1}={v1}&p2={v2}… query string. The ensuing {service_api} refers to a supported action {name} plus any required input parameters. Alternatively, path can be used for an AWS service path-based API. The ensuing service_api refers to the path to an AWS service resource, including the region of the integrated AWS service, if applicable. For example, for integration with the S3 API of GetObject, the uri can be either arn:aws:apigateway:us-west-2:s3:action/GetObject&Bucket={bucket}&Key={key} or arn:aws:apigateway:us-west-2:s3:path/{bucket}/{key}

interface StaticRoute

extends BaseRoute

StaticRoute is a route that will map from an incoming path to the files/directories specified by [localPath].

property apiKeyRequired

apiKeyRequired?: undefined | false | true;

If true, an API key will be required for this route. The source for the API Key can be set at the API level and by default, the source will be the HEADER.

property authorizers

authorizers?: Authorizer[] | Authorizer;

Authorizers allows you to define Lambda authorizers be applied for authorization when the the route is called.

property contentType

contentType?: undefined | string;

The content-type to serve the file as. Only valid when localPath points to a file. If localPath points to a directory, the content types for all files will be inferred.

property index

index?: boolean | string;

By default API.static will also serve ‘index.html’ in response to a request on a directory. To disable this set false or to supply a new index pass an appropriate name.

property localPath

localPath: string;

The local path on disk to create static S3 resources for. Files will be uploaded into S3 objects, and directories will be recursively walked into.

property path

path: string;

The path on the API that will map to files in [localPath]. If not prefixed with /, then a / will be added automatically to the beginning.

property requestValidator

requestValidator?: RequestValidator;

Request Validator specifies the validator to use at the method level. This will override anything defined at the API level.

property requiredParameters

requiredParameters?: reqvalidation.Parameter[];

Required Parameters to validate. If the request validator is set to ALL or PARAMS_ONLY, api gateway will validate these before sending traffic to the event handler.

module metrics

function cacheHitCount

cacheHitCount(change?: ApigatewayMetricChange): Metric

The number of requests served from the API cache in a given period.

The Sum statistic represents this metric, namely, the total count of the cache hits in the specified period. The Average statistic represents the cache hit rate, namely, the total count of the cache hits divided by the total number of requests during the period. The denominator corresponds to the Count metric (below).

function cacheMissCount

cacheMissCount(change?: ApigatewayMetricChange): Metric

The number of requests served from the back end in a given period, when API caching is enabled.

The Sum statistic represents this metric, namely, the total count of the cache misses in the specified period. The Average statistic represents the cache miss rate, namely, the total count of the cache hits divided by the total number of requests during the period. The denominator corresponds to the Count metric (below).

Unit: Count

function count

count(change?: ApigatewayMetricChange): Metric

The total number API requests in a given period.

The SampleCount statistic represents this metric.

Unit: Count

function error4XX

error4XX(change?: ApigatewayMetricChange): Metric

The number of client-side errors captured in a specified period.

The Sum statistic represents this metric, namely, the total count of the 4XXError errors in the given period. The Average statistic represents the 4XXError error rate, namely, the total count of the 4XXError errors divided by the total number of requests during the period. The denominator corresponds to the Count metric (below).

Unit: Count

function error5XX

error5XX(change?: ApigatewayMetricChange): Metric

The number of server-side errors captured in a given period.

The Sum statistic represents this metric, namely, the total count of the 5XXError errors in the given period. The Average statistic represents the 5XXError error rate, namely, the total count of the 5XXError errors divided by the total number of requests during the period. The denominator corresponds to the Count metric (below).

Unit: Count

function integrationLatency

integrationLatency(change?: ApigatewayMetricChange): Metric

The time between when API Gateway relays a request to the back end and when it receives a response from the back end.

Unit: Milliseconds

function latency

latency(change?: ApigatewayMetricChange): Metric

The time between when API Gateway receives a request from a client and when it returns a response to the client. The latency includes the integration latency and other API Gateway overhead.

Unit: Milliseconds

function metric

metric(metricName: ApigatewayMetricName, change: ApigatewayMetricChange): Metric

Creates an AWS/ApiGateway metric with the requested [metricName]. See https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-metrics-and-dimensions.html for list of all metric-names.

Note, individual metrics can easily be obtained without supplying the name using the other [metricXXX] functions.

You can use the dimensions in the following table to filter API Gateway metrics.

  1. “ApiName”: Filters API Gateway metrics for an API of the specified API name.
  2. “ApiName, Method, Resource, Stage”: Filters API Gateway metrics for an API method of the specified API, stage, resource, and method.

API Gateway will not send such metrics unless you have explicitly enabled detailed CloudWatch metrics. You can do this in the console by selecting Enable CloudWatch Metrics under a stage Settings tab. Alternatively, you can call the stage:update action of the API Gateway REST API to update the metricsEnabled property to true.

Enabling such metrics will incur additional charges to your account. For pricing information, see Amazon CloudWatch Pricing. 3. “ApiName, Stage”: Filters API Gateway metrics for an API stage of the specified API and stage.

interface ApigatewayMetricChange

type ApigatewayMetricName

type ApigatewayMetricName = “4XXError” | “5XXError” | “CacheHitCount” | “CacheMissCount” | “Count” | “IntegrationLatency” | “Latency”;

type RawDataRoute

type RawDataRoute = {
    data: any;
    method: Method;
    path: string;
};

Fallback route for when raw swagger control is desired. The [data] field should be a javascript object that will be then included in the final swagger specification like so:

"paths": { [path]: { [method]: data } }

This value will be JSON.stringify’d as part of normal processing. It should not be passed as string here.

type Request

type Request = awslambda.APIGatewayProxyEvent;

type RequestContext

type RequestContext = awslambda.APIGatewayEventRequestContext;

type Response

type Response = awslambda.APIGatewayProxyResult;

type Route

type Route = EventHandlerRoute | StaticRoute | IntegrationRoute | RawDataRoute;

A route that that APIGateway should accept and forward to some type of destination. All routes have an incoming path that they match against. However, destinations are determined by the kind of the route. See [EventHandlerRoute], [StaticRoute], [IntegrationRoute] and [RawJsonRoute] for additional details.