Api
The Api construct is a higher level CDK construct that makes it easy to create an API. It provides a simple way to define the routes in your API. And allows you to configure the specific Lambda functions if necessary. It also allows you to configure authorization and custom domains.
Examples
The Api
construct is designed to make it easy to get started with, while allowing for a way to fully configure it as well. Let's look at how, through a couple of examples.
Using the minimal config
import { Api } from "sst/constructs";
new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
},
});
Configuring routes
Using ANY
methods
You can use the ANY
method to match all methods that you haven't defined.
new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"ANY /notes": "src/any.main",
},
});
Using path variable
new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"GET /notes/{id}": "src/get.main",
},
});
Using greedy path variable
A path variable {proxy+}
catches all child routes. The greedy path variable must be at the end of the resource path.
new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"GET /notes/{proxy+}": "src/greedy.main",
},
});
Using catch-all route
To add a catch-all route, add a route called $default
. This will catch requests that don't match any other routes.
new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
$default: "src/default.main",
},
});
Lazily adding routes
Add routes after the API has been created.
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
},
});
api.addRoutes(stack, {
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
});
Configuring Function routes
Specifying function props for all the routes
You can set some function props and have them apply to all the routes.
new Api(stack, "Api", {
defaults: {
function: {
timeout: 20,
environment: { tableName: table.tableName },
permissions: [table],
},
},
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
},
});
Configuring an individual route
Configure each Lambda function separately.
new Api(stack, "Api", {
routes: {
"GET /notes": {
function: {
handler: "src/list.main",
timeout: 20,
environment: { tableName: table.tableName },
permissions: [table],
},
},
},
});
Note that, you can set the defaults.function
while using the function
per route. The function
will just override the defaults.function
. Except for the environment
, the layers
, and the permissions
properties, that will be merged.
new Api(stack, "Api", {
defaults: {
function: {
timeout: 20,
environment: { tableName: table.tableName },
permissions: [table],
},
},
routes: {
"GET /notes": {
function: {
handler: "list.main",
timeout: 10,
environment: { bucketName: bucket.bucketName },
permissions: [bucket],
},
},
"POST /notes": "create.main",
},
});
So in the above example, the GET /notes
function doesn't use the timeout
that is set in the defaults.function
. It'll instead use the one that is defined in the function definition (10 seconds
). And the function will have both the tableName
and the bucketName
environment variables set; as well as permissions to both the table
and the bucket
.
Attaching permissions for the entire API
Allow the entire API to access S3.
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
},
});
api.attachPermissions(["s3"]);
Attaching permissions for a specific route
Allow one of the routes to access S3.
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
},
});
api.attachPermissionsToRoute("GET /notes", ["s3"]);
Getting the function for a route
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
},
});
const listFunction = api.getFunction("GET /notes");
Configuring ALB routes
You can configure a route to integrate with Application Load Balancers in your VPC.
new Api(stack, "Api", {
routes: {
"GET /": {
type: "alb",
cdk: {
albListener,
},
},
},
});
Configuring NLB routes
You can configure a route to integrate with Network Load Balancers in your VPC.
new Api(stack, "Api", {
routes: {
"GET /": {
type: "nlb",
cdk: {
nlbListener,
},
},
},
});
Configuring HTTP proxy routes
You can configure a route to pass the entire request to a publicly routable HTTP endpoint.
new Api(stack, "Api", {
routes: {
"GET /": {
type: "url",
url: "http://domain.com",
},
},
});
Configuring AWS proxy routes
You can configure a route to pass the entire request to an AWS service. Read more about supported AWS services.
import { HttpIntegrationSubtype, ParameterMapping, MappingValue } from "aws-cdk-lib/aws-apigatewayv2";
new Api(stack, "Api", {
routes: {
"POST /send_events": {
type: "aws",
cdk: {
integration: {
subtype: HttpIntegrationSubtype.EVENTBRIDGE_PUT_EVENTS,
parameterMapping: ParameterMapping.fromObject({
Source: MappingValue.custom("$request.body.source"),
DetailType: MappingValue.custom("$request.body.detailType"),
Detail: MappingValue.custom("$request.body.detail"),
}),
},
},
},
},
});
And you can send a POST request to the /send_events
endpoint to put an event in the default bus.
curl --request POST \
--url https://api.endpoint.com/send_events \
--header 'Content-Type: application/json' \
--data '{
"source": "my.source",
"detailType": "my.type",
"detail": {"foo": "bar"}
}'
Custom domains
You can configure the API with a custom domain hosted either on Route 53 or externally.
Using the basic config
new Api(stack, "Api", {
customDomain: "api.domain.com",
routes: {
"GET /notes": "src/list.main",
},
});
Configuring with a wildcard
new Api(stack, "Api", {
customDomain: "*.domain.com",
routes: {
"GET /notes": "src/list.main",
},
});
Using the full config
new Api(stack, "Api", {
customDomain: {
domainName: "api.domain.com",
hostedZone: "domain.com",
path: "v1",
},
routes: {
"GET /notes": "src/list.main",
},
});
Mapping multiple APIs to the same domain
const usersApi = new Api(stack, "UsersApi", {
customDomain: {
domainName: "api.domain.com",
path: "users",
},
});
new Api(stack, "PostsApi", {
customDomain: {
path: "posts",
cdk: {
domainName: usersApi.cdk.domainName,
},
},
});
Importing an existing API Gateway custom domain
import { DomainName } from "aws-cdk-lib/aws-apigatewayv2";
new Api(stack, "Api", {
customDomain: {
path: "newPath",
cdk: {
domainName: DomainName.fromDomainNameAttributes(stack, "MyDomain", {
name,
regionalDomainName,
regionalHostedZoneId,
}),
},
},
routes: {
"GET /notes": "src/list.main",
},
});
Importing an existing certificate
import { Certificate } from "aws-cdk-lib/aws-certificatemanager";
new Api(stack, "Api", {
customDomain: {
domainName: "api.domain.com",
cdk: {
certificate: Certificate.fromCertificateArn(stack, "MyCert", certArn),
},
},
routes: {
"GET /notes": "src/list.main",
},
});
Specifying a hosted zone
If you have multiple hosted zones for a given domain, you can choose the one you want to use to configure the domain.
import { HostedZone } from "aws-cdk-lib/aws-route53";
new Api(stack, "Api", {
customDomain: {
domainName: "api.domain.com",
cdk: {
hostedZone: HostedZone.fromHostedZoneAttributes(stack, "MyZone", {
hostedZoneId,
zoneName,
}),
},
},
routes: {
"GET /notes": "src/list.main",
},
});
Loading domain name from SSM parameter
If you have the domain name stored in AWS SSM Parameter Store, you can reference the value as the domain name:
import { StringParameter } from "aws-cdk-lib/aws-ssm";
const rootDomain = StringParameter.valueForStringParameter(stack, `/myApp/domain`);
new Api(stack, "Api", {
customDomain: {
domainName: `api.${rootDomain}`,
cdk: {
hostedZone: HostedZone.fromHostedZoneAttributes(stack, "MyZone", {
hostedZoneId,
zoneName,
}),
},
},
routes: {
"GET /notes": "src/list.main",
},
});
Note that, normally SST will look for a hosted zone by stripping out the first part of the domainName
. But this is not possible when the domainName
is a reference. So you'll need to specify the cdk.hostedZone
explicitly.
Using externally hosted domain
import { Certificate } from "aws-cdk-lib/aws-certificatemanager";
new Api(stack, "Api", {
customDomain: {
isExternalDomain: true,
domainName: "api.domain.com",
cdk: {
certificate: Certificate.fromCertificateArn(stack, "MyCert", certArn),
},
},
routes: {
"GET /notes": "src/list.main",
},
});
Note that you can also migrate externally hosted domains to Route 53 by following this guide.
Authorization
You can use IAM, JWT, or a Lambda authorizer to add auth to your APIs.
Adding IAM authorization
You can secure all your API routess by setting the defaults.authorizer
.
new Api(stack, "Api", {
defaults: {
authorizer: "iam",
},
routes: {
"GET /notes": "list.main",
"POST /notes": "create.main",
},
});
Adding IAM authorization to a specific route
You can also secure specific routes in your API.
new Api(stack, "Api", {
routes: {
"GET /public": "src/public.main",
"GET /private": {
authorizer: "iam",
function: "src/private.main",
},
},
});
Adding JWT authorization
JWT allows authorized users to access your API. Note that, this is a different authorization method when compared to using iam
, which allows you to secure other AWS resources as well.
new Api(stack, "Api", {
authorizers: {
myAuthorizer: {
type: "jwt",
jwt: {
issuer: "https://myorg.us.auth0.com",
audience: ["UsGRQJJz5sDfPQDs6bhQ9Oc3hNISuVif"],
},
},
},
defaults: {
authorizer: "myAuthorizer",
},
routes: {
"GET /notes": "list.main",
"POST /notes": "create.main",
},
});
Adding JWT authorization to a specific route
You can also secure specific routes using JWT by setting the authorizer
per route.
new Api(stack, "Api", {
authorizers: {
myAuthorizer: {
type: "jwt",
jwt: {
issuer: "https://myorg.us.auth0.com",
audience: ["UsGRQJJz5sDfPQDs6bhQ9Oc3hNISuVif"],
},
},
},
routes: {
"GET /public": "src/public.main",
"GET /private": {
authorizer: "myAuthorizer",
function: "src/private.main",
},
},
});
Using Cognito User Pool as the JWT authorizer
JWT can also use a Cognito User Pool as an authorizer.
new Api(stack, "Api", {
authorizers: {
myAuthorizer: {
type: "user_pool",
userPool: {
id: userPool.userPoolId,
clientIds: [userPoolClient.userPoolClientId],
},
},
},
defaults: {
authorizer: "myAuthorizer",
authorizationScopes: ["user.id", "user.email"],
},
routes: {
"GET /notes": "list.main",
"POST /notes": "create.main",
},
});
Adding Lambda authorization
You can also use a Lambda function to authorize users to access your API. Like using JWT and IAM, the Lambda authorizer is another way to secure your API.
import { Function, Api } from "sst/constructs";
new Api(stack, "Api", {
authorizers: {
myAuthorizer: {
type: "lambda",
function: new Function(stack, "Authorizer", {
handler: "src/authorizer.main",
}),
resultsCacheTtl: "30 seconds",
},
},
defaults: {
authorizer: "myAuthorizer",
},
routes: {
"GET /notes": "list.main",
"POST /notes": "create.main",
},
});
Note that resultsCacheTtl
configures how long the authorization result will be cached.
Adding Lambda authorization to a specific route
You can also secure specific routes using a Lambda authorizer by setting the authorizer
per route.
import { Function, Api } from "sst/constructs";
new Api(stack, "Api", {
authorizers: {
myAuthorizer: {
type: "lambda",
function: new Function(stack, "Authorizer", {
handler: "src/authorizer.main",
}),
resultsCacheTtl: "30 seconds",
},
},
routes: {
"GET /public": "src/public.main",
"GET /private": {
authorizer: "myAuthorizer",
function: "src/private.main",
},
},
});
Sharing an API authorizer
If defaults.authorizer
is configured for the Api, it will be applied to all routes, across all stacks.
const api = new Api(stack, "Api", {
authorizers: {
myAuthorizer: {
type: "lambda",
function: new Function(stack, "Authorizer", {
handler: "src/authorizer.main",
}),
resultsCacheTtl: "30 seconds",
},
},
defaults: {
authorizer: "myAuthorizer",
},
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
},
});
this.api = api;
api.addRoutes(stack, {
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
});
In this case, the 3 routes added in the second stack are also secured by the Lambda authorizer.
Access log
Configuring the log format
Use a CSV format instead of default JSON format.
new Api(stack, "Api", {
accessLog:
"$context.identity.sourceIp,$context.requestTime,$context.httpMethod,$context.routeKey,$context.protocol,$context.status,$context.responseLength,$context.requestId",
routes: {
"GET /notes": "src/list.main",
},
});
Configuring the log retention setting
new Api(stack, "Api", {
accessLog: {
retention: "one_week",
},
routes: {
"GET /notes": "src/list.main",
},
});
CORS
Override the default behavior of allowing all methods, and only allow the GET method.
new Api(stack, "Api", {
cors: {
allowMethods: ["GET"],
},
routes: {
"GET /notes": "src/list.main",
},
});
GraphQL
Add a GraphQL route using a Code-first GraphQL setup, configured using Pothos.
new Api(stack, "Api", {
routes: {
"POST /graphql": {
type: "graphql",
function: "src/graphql.main",
pothos: {
schema: "backend/functions/graphql/schema.ts",
output: "graphql/schema.graphql",
commands: [
"./genql graphql/graphql.schema graphql/
]
}
},
},
});
Advanced examples
Throttling
new Api(stack, "Api", {
defaults: {
throttle: {
rate: 2000,
burst: 100,
},
},
routes: {
"GET /notes": "list.main",
"POST /notes": "create.main",
},
});
Configuring the Http Api
Configure the internally created CDK HttpApi
instance.
new Api(stack, "Api", {
cdk: {
httpApi: {
disableExecuteApiEndpoint: true,
},
},
routes: {
"GET /notes": "src/list.main",
},
});
Sharing an API across stacks
You can create the Api construct in one stack, and add routes in other stacks. To do this, return the API from your stack function.
import { Api, StackContext } from "sst/constructs";
export function MainStack({ stack }: StackContext) {
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
},
});
return {
api,
};
}
Then in another stack, utilize use
to import the first stack's API. Finally, call addRoutes
. Note that the AWS resources for the added routes will be created in AnotherStack
.
import { StackContext, use } from "sst/constructs";
import { MainStack } from "./MainStack";
export function AnotherStack({ stack }: StackContext) {
const { api } = use(MainStack);
api.addRoutes(stack, {
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
});
}
Using 1 role for all routes
By default, Api
creates 1 IAM role
for each Function handling a route. To have all Functions reuse the same role, manually create a role, and pass it into defaults.function
.
Use attachPermissionsToRole
to grant IAM permissions for the role.
import { Role, ServicePrincipal } as iam from "aws-cdk-lib/aws-iam";
import { attachPermissionsToRole } from "sst/constructs";
// Create an IAM role
const role = new Role(stack, "ApiRole", {
assumedBy: new ServicePrincipal("lambda.amazonaws.com"),
managedPolicies: [
{
managedPolicyArn:
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
},
],
});
// Attach permissions to role
attachPermissionsToRole(role, [
// ie. table
]);
// Use the role for all routes
new Api(stack, "Api", {
defaults: {
function: {
role,
},
},
routes: {
"GET /notes": "src/list.main",
"POST /notes": "src/create.main",
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
},
});
Using Lambda container images
import * as lambda from "aws-cdk-lib/aws-lambda";
const fn = new lambda.DockerImageFunction(stack, "DockerFunction", {
code: lambda.DockerImageCode.fromImageAsset("path/to/Dockerfile/folder"),
});
new Api(stack, "Api", {
routes: {
"GET /": {
cdk: {
function: fn,
},
},
},
});
Using Lambda aliases
const fn = new Function(stack, "MyFunction", {
handler: "handler.main",
});
const alias = new lambda.Alias(stack, "MyAlias", {
aliasName: "hello",
version: fn.currentVersion,
});
new Api(stack, "Api", {
routes: {
"GET /": {
cdk: {
function: alias,
},
},
},
});
Importing an existing Http Api
Override the internally created CDK HttpApi
instance.
import { HttpApi } from "aws-cdk-lib/aws-apigatewayv2";
new Api(stack, "Api", {
cdk: {
httpApi: HttpApi.fromHttpApiAttributes(stack, "MyHttpApi", {
httpApiId,
}),
},
routes: {
"GET /notes": "src/list.main",
},
});
Constructor
new Api(scope, id, props)
Parameters
ApiProps
accessLog?
Type : string | boolean | ApiAccessLogProps
Default : true
Enable CloudWatch access logs for this API. Defaults to true.
new Api(stack, "Api", {
accessLog: true
});
new Api(stack, "Api", {
accessLog: {
retention: "one_week",
},
});
authorizers?
Type : Record<string, ApiUserPoolAuthorizer | ApiJwtAuthorizer | ApiLambdaAuthorizer>
Define the authorizers for the API. Can be a user pool, JWT, or Lambda authorizers.
new Api(stack, "Api", {
authorizers: {
Authorizer: {
type: "user_pool",
userPool: {
id: userPool.userPoolId,
clientIds: [userPoolClient.userPoolClientId],
},
},
},
});
cors?
Type : boolean | ApiCorsProps
Default : true
CORS support applied to all endpoints in this API
new Api(stack, "Api", {
cors: {
allowMethods: ["GET"],
},
});
customDomain?
Type : string | ApiDomainProps
Specify a custom domain to use in addition to the automatically generated one. SST currently supports domains that are configured using Route 53
new Api(stack, "Api", {
customDomain: "api.example.com"
})
new Api(stack, "Api", {
customDomain: {
domainName: "api.example.com",
hostedZone: "domain.com",
path: "v1"
}
})
defaults?
Type :
defaults.authorizationScopes?
Type : Array<string>
Default : []
An array of scopes to include in the authorization when using
user_pool
or
jwt
authorizers. These will be merged with the scopes from the attached authorizer.
defaults.authorizer?
Type : "none" | "iam" | string
The default authorizer for all the routes in the API.
new Api(stack, "Api", {
defaults: {
authorizer: "iam",
}
});
new Api(stack, "Api", {
authorizers: {
Authorizer: {
type: "user_pool",
userPool: {
id: userPool.userPoolId,
clientIds: [userPoolClient.userPoolClientId],
},
},
},
defaults: {
authorizer: "Authorizer",
}
});
defaults.function?
Type : FunctionProps
The default function props to be applied to all the Lambda functions in the API. The
environment
,
permissions
and
layers
properties will be merged with per route definitions if they are defined.
new Api(stack, "Api", {
defaults: {
function: {
timeout: 20,
environment: { tableName: table.tableName },
permissions: [table],
}
}
});
defaults.payloadFormatVersion?
Type : "1.0" | "2.0"
Default : "2.0"
The payload format version for all the endpoints in the API.
defaults.throttle?
Type :
defaults.throttle.burst?
Type : number
The burst rate of the number of concurrent request for all the routes in the API.
new Api(stack, "Api", {
defaults: {
throttle: {
burst: 100
}
}
})
defaults.throttle.rate?
Type : number
The steady-state rate of the number of concurrent request for all the routes in the API.
new Api(stack, "Api", {
defaults: {
throttle: {
rate: 10
}
}
})
routes?
Type : Record<string, string | Function | ApiFunctionRouteProps | ApiAwsRouteProps | ApiHttpRouteProps | ApiAlbRouteProps | ApiNlbRouteProps | ApiGraphQLRouteProps>
Define the routes for the API. Can be a function, proxy to another API, or point to an load balancer
new Api(stack, "api", {
routes: {
"GET /notes" : "src/list.main",
"GET /notes/{id}" : "src/get.main",
"$default": "src/default.main"
}
})
cdk?
Type :
cdk.httpApi?
Type : IHttpApi | HttpApiProps
Import the underlying HTTP API or override the default configuration
import { HttpApi } from "aws-cdk-lib/aws-apigatewayv2";
new Api(stack, "Api", {
cdk: {
httpApi: HttpApi.fromHttpApiAttributes(stack, "MyHttpApi", {
httpApiId,
}),
}
});
cdk.httpStages?
Type : Array<Omit<HttpStageProps, "httpApi">>
Configures the stages to create for the HTTP API.
Note that, a default stage is automatically created, unless the
cdk.httpApi.createDefaultStage
is set to `false.
import { HttpApi } from "aws-cdk-lib/aws-apigatewayv2";
new Api(stack, "Api", {
cdk: {
httpStages: [{
stageName: "dev",
autoDeploy: false,
}],
}
});
cdk.id?
Type : string
Allows you to override default id for this construct.
Properties
An instance of Api
has the following properties.
customDomainUrl
Type : undefined | string
If custom domain is enabled, this is the custom domain URL of the Api.
note
If you are setting the base mapping for the custom domain, you need to include the trailing slash while using the custom domain URL. For example, if the domainName
is set to
api.domain.com
and the path
is
v1
, the custom domain URL of the API will be
https://api.domain.com/v1/
.
httpApiArn
Type : string
The ARN of the internally created API Gateway HTTP API
httpApiId
Type : string
The id of the internally created API Gateway HTTP API
id
Type : string
routes
Type : Array<string>
The routes for the Api
url
Type : string
The AWS generated URL of the Api.
cdk
Type :
cdk.accessLogGroup?
Type : LogGroup
If access logs are enabled, this is the internally created CDK LogGroup instance.
cdk.certificate?
Type : Certificate
If custom domain is enabled, this is the internally created CDK Certificate instance.
cdk.domainName?
Type : DomainName
If custom domain is enabled, this is the internally created CDK DomainName instance.
cdk.httpApi
Type : HttpApi
The internally created CDK HttpApi instance.
Methods
An instance of Api
has the following methods.
addRoutes
addRoutes(scope, routes)
Parameters
- scope Construct
- routes Record<string, string | Function | ApiFunctionRouteProps | ApiAwsRouteProps | ApiHttpRouteProps | ApiAlbRouteProps | ApiNlbRouteProps | ApiGraphQLRouteProps>
Adds routes to the Api after it has been created.
api.addRoutes(stack, {
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
"DELETE /notes/{id}": "src/delete.main",
});
attachPermissions
attachPermissions(permissions)
Parameters
- permissions Permissions
Attaches the given list of permissions to all the routes. This allows the functions to access other AWS resources.
api.attachPermissions(["s3"]);
attachPermissionsToRoute
attachPermissionsToRoute(routeKey, permissions)
Parameters
- routeKey string
- permissions Permissions
Attaches the given list of permissions to a specific route. This allows that function to access other AWS resources.
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
},
});
api.attachPermissionsToRoute("GET /notes", ["s3"]);
bind
bind(constructs)
Parameters
- constructs Array<BindingResource>
Binds the given list of resources to all the routes.
api.bind([STRIPE_KEY, bucket]);
bindToRoute
bindToRoute(routeKey, constructs)
Parameters
- routeKey string
- constructs Array<BindingResource>
Binds the given list of resources to a specific route.
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
},
});
api.bindToRoute("GET /notes", [STRIPE_KEY, bucket]);
getFunction
getFunction(routeKey)
Parameters
- routeKey string
Get the instance of the internally created Function, for a given route key where the
routeKey
is the key used to define a route. For example,
GET /notes
.
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "src/list.main",
},
});
const listFunction = api.getFunction("GET /notes");
setCors
setCors(cors)
Parameters
- cors boolean | ApiCorsProps
Binds the given list of resources to a specific route.
const api = new Api(stack, "Api");
api.setCors({
allowMethods: ["GET"],
});
ApiCorsProps
allowCredentials?
Type : boolean
Default : false
Specifies whether credentials are included in the CORS request.
allowHeaders?
Type : Array<string>
Default : Allow all headers.
The collection of allowed headers.
// Allow all headers
allowHeaders: ["*"]
// Allow specific headers
allowHeaders: ["Accept", "Content-Type", "Authorization"]
allowMethods?
Type : Array<"GET" | "PUT" | "HEAD" | "POST" | "DELETE" | "ANY" | "PATCH" | "OPTIONS">
Default : Allow all methods.
The collection of allowed HTTP methods.
// Allow all methods
allowMethods: ["ANY"]
// Allow specific methods
allowMethods: ["GET", "POST"]
allowOrigins?
Type : Array<string>
Default : Allow all origins.
The collection of allowed origins.
// Allow all origins
allowOrigins: ["*"]
// Allow specific origins. Note that the url protocol, ie. "https://", is required.
allowOrigins: ["https://domain.com"]
exposeHeaders?
Type : Array<string>
Default : No expose headers are allowed.
The collection of exposed headers.
maxAge?
Type : ${number} second | ${number} seconds | ${number} minute | ${number} minutes | ${number} hour | ${number} hours | ${number} day | ${number} days
Default : No caching
Specify how long the results of a preflight response can be cached
maxAge: "1 day"
ApiDomainProps
domainName?
Type : string
The domain to be assigned to the API endpoint (ie. api.domain.com)
hostedZone?
Type : string
The hosted zone in Route 53 that contains the domain. By default, SST will look for a hosted zone by stripping out the first part of the domainName that's passed in. So, if your domainName is api.domain.com. SST will default the hostedZone to domain.com.
isExternalDomain?
Type : boolean
Set this option if the domain is not hosted on Amazon Route 53.
path?
Type : string
The base mapping for the custom domain.
For example, by setting the domainName to api.domain.com and the path to v1, the custom domain URL of the API will become https://api.domain.com/v1/. If the path is not set, the custom domain URL will be https://api.domain.com. Note the additional trailing slash in the former case.
cdk?
Type :
cdk.certificate?
Type : ICertificate
Override the internally created certificate
cdk.domainName?
Type : IDomainName
Override the internally created domain name
cdk.hostedZone?
Type : IHostedZone
Override the internally created hosted zone
ApiAlbRouteProps
Specify a route handler that forwards to an ALB
api.addRoutes(stack, {
"GET /notes/{id}": {
type: "alb",
cdk: {
albListener: listener,
}
}
});
authorizationScopes?
Type : Array<string>
authorizer?
Type : "none" | "iam" | string
type
Type : "alb"
cdk
Type :
cdk.albListener
Type : IApplicationListener
The listener to the application load balancer used for the integration.
cdk.integration?
Type : HttpAlbIntegrationProps
ApiAwsRouteProps
Specify a function route handler and configure additional options
api.addRoutes(stack, {
"GET /notes/{id}": {
type: "aws",
cdk: {
integration: {
subtype: apig.HttpIntegrationSubtype.EVENTBRIDGE_PUT_EVENTS,
parameterMapping: ParameterMapping.fromObject({
Source: MappingValue.custom("$request.body.source"),
DetailType: MappingValue.custom("$request.body.detailType"),
Detail: MappingValue.custom("$request.body.detail"),
}),
}
}
}
});
authorizationScopes?
Type : Array<string>
authorizer?
Type : "none" | "iam" | string
type
Type : "aws"
This is a constant
cdk
Type :
cdk.integration
Type : Omit<CdkHttpAwsIntegrationProps, "credentials">
ApiJwtAuthorizer
Specify a JWT authorizer and configure additional options.
new Api(stack, "Api", {
authorizers: {
Authorizer: {
type: "jwt",
userPool: {
issuer: "https://abc.us.auth0.com",
audience: ["123"],
},
},
},
});
identitySource?
Type : Array<string>
Default : ["$request.header.Authorization"]
The identity source for which authorization is requested.
jwt?
Type :
jwt.audience
Type : Array<string>
A list of the intended recipients of the JWT.
jwt.issuer
Type : string
The base domain of the identity provider that issues JWT.
name?
Type : string
The name of the authorizer.
type
Type : "jwt"
String literal to signify that the authorizer is JWT authorizer.
cdk?
Type :
cdk.authorizer
Type : HttpJwtAuthorizer
This allows you to override the default settings this construct uses internally to create the authorizer.
ApiNlbRouteProps
Specify a route handler that forwards to an NLB
api.addRoutes(stack, {
"GET /notes/{id}": {
type: "nlb",
cdk: {
nlbListener: listener,
}
}
});
authorizationScopes?
Type : Array<string>
authorizer?
Type : "none" | "iam" | string
type
Type : "nlb"
cdk
Type :
cdk.integration?
Type : HttpNlbIntegrationProps
cdk.nlbListener
Type : INetworkListener
The listener to the application load balancer used for the integration.
ApiAccessLogProps
destinationArn?
Type : string
format?
Type : string
retention?
Type : "one_day" | "three_days" | "five_days" | "one_week" | "two_weeks" | "one_month" | "two_months" | "three_months" | "four_months" | "five_months" | "six_months" | "one_year" | "thirteen_months" | "eighteen_months" | "two_years" | "three_years" | "five_years" | "six_years" | "seven_years" | "eight_years" | "nine_years" | "ten_years" | "infinite"
ApiHttpRouteProps
Specify a route handler that forwards to another URL
api.addRoutes(stack, {
"GET /notes/{id}": {
type: "url",
url: "https://example.com/notes/{id}",
}
});
authorizationScopes?
Type : Array<string>
authorizer?
Type : "none" | "iam" | string
type
Type : "url"
This is a constant
url
Type : string
The URL to forward to
cdk?
Type :
cdk.integration
Type : HttpUrlIntegrationProps
Override the underlying CDK integration
ApiLambdaAuthorizer
Specify a Lambda authorizer and configure additional options.
new Api(stack, "Api", {
authorizers: {
Authorizer: {
type: "lambda",
function: new Function(stack, "Authorizer", {
handler: "test/lambda.handler",
}),
},
},
});
function?
Type : Function
Used to create the authorizer function
identitySource?
Type : Array<string>
Default : ["$request.header.Authorization"]
The identity source for which authorization is requested.
name?
Type : string
The name of the authorizer.
responseTypes?
Type : Array<"iam" | "simple">
Default : ["iam"]
The types of responses the lambda can return.
If
simple
is included then response format 2.0 will be used.
resultsCacheTtl?
Type : ${number} second | ${number} seconds | ${number} minute | ${number} minutes | ${number} hour | ${number} hours | ${number} day | ${number} days
Default : Not cached
The amount of time the results are cached.
type
Type : "lambda"
String literal to signify that the authorizer is Lambda authorizer.
cdk?
Type :
cdk.authorizer
Type : HttpLambdaAuthorizer
This allows you to override the default settings this construct uses internally to create the authorizer.
ApiGraphQLRouteProps
Specify a route handler that handles GraphQL queries using Pothos
api.addRoutes(stack, {
"POST /graphql": {
type: "graphql",
function: {
handler: "functions/graphql/graphql.ts",
},
pothos: {
schema: "backend/functions/graphql/schema.ts",
output: "graphql/schema.graphql",
commands: [
"./genql graphql/graphql.schema graphql/
]
}
}
})
authorizationScopes?
Type : Array<string>
authorizer?
Type : "none" | "iam" | string
function
Type : string | Function | FunctionProps
The function definition used to create the function for this route. Must be a graphql handler
pothos?
Type :
pothos.commands?
Type : Array<string>
Commands to run after generating schema. Useful for code generation steps
pothos.internalPackages?
Type : Array<string>
List of packages that should be considered internal during schema generation
pothos.output?
Type : string
File to write graphql schema to
pothos.schema?
Type : string
Path to pothos schema
type
Type : "graphql"
ApiFunctionRouteProps
Specify a function route handler and configure additional options
api.addRoutes(stack, {
"GET /notes/{id}": {
type: "function",
function: "src/get.main",
payloadFormatVersion: "1.0",
}
});
authorizationScopes?
Type : Array<string>
authorizer?
Type : "none" | "iam" | string
function?
Type : string | Function | FunctionProps
The function definition used to create the function for this route.
payloadFormatVersion?
Type : "1.0" | "2.0"
Default : "2.0"
The payload format version for the route.
type?
Type : "function"
cdk?
Type :
cdk.function?
Type : IFunction
Use an existing Lambda function.
ApiUserPoolAuthorizer
Specify a user pool authorizer and configure additional options.
new Api(stack, "Api", {
authorizers: {
Authorizer: {
type: "user_pool",
userPool: {
id: userPool.userPoolId,
clientIds: [userPoolClient.userPoolClientId],
},
},
},
});
identitySource?
Type : Array<string>
Default : ["$request.header.Authorization"]
The identity source for which authorization is requested.
name?
Type : string
The name of the authorizer.
type
Type : "user_pool"
String li any shot and having even a miniscule shotteral to signify that the authorizer is user pool authorizer.
userPool?
Type :
userPool.clientIds?
Type : Array<string>
The ids of the user pool clients to use for authorization.
userPool.id
Type : string
The id of the user pool to use for authorization.
userPool.region?
Type : string
The AWS region of the user pool.
cdk?
Type :
cdk.authorizer
Type : HttpUserPoolAuthorizer
This allows you to override the default settings this construct uses internally to create the authorizer.
CdkHttpAwsIntegrationProps
credentials
Type : IntegrationCredentials
Default : - no credentials, use resource-based permissions on supported AWS services
The credentials with which to invoke the integration.
parameterMapping
Type : ParameterMapping
Specifies how to transform HTTP requests before sending them to the backend
subtype
Type : HttpIntegrationSubtype
Specifies the AWS service action to invoke