AWS SAM constructs for creating REST APIs and HTTP APIs with Gateway-specific features including CORS, authentication, and custom domain configuration.
Creates a REST API Gateway with SAM enhancements.
/**
* AWS::Serverless::Api - REST API Gateway with SAM-specific features
*/
class CfnApi extends cdk.CfnResource {
constructor(
scope: cdk.Construct,
id: string,
props: CfnApiProps
);
}
interface CfnApiProps {
/** Stage name for deployment */
stageName?: string;
/** OpenAPI definition inline */
definitionBody?: any;
/** OpenAPI definition from S3 */
definitionUri?: any;
/** API name */
name?: string;
/** Authentication configuration */
auth?: CfnApi.AuthProperty;
/** Binary media types */
binaryMediaTypes?: string[];
/** CORS configuration */
cors?: any;
/** Custom domain configuration */
domain?: CfnApi.DomainConfigurationProperty;
/** Endpoint configuration */
endpointConfiguration?: any;
/** Method settings */
methodSettings?: CfnApi.MethodSettingProperty[];
/** Stage variables */
variables?: { [key: string]: string };
/** Access logging configuration */
accessLogSetting?: CfnApi.AccessLogSettingProperty;
/** Canary deployment settings */
canarySetting?: CfnApi.CanarySettingProperty;
/** Enable X-Ray tracing */
tracingEnabled?: boolean;
/** OpenAPI version */
openApiVersion?: string;
/** API models */
models?: { [key: string]: CfnApi.ModelProperty };
/** Gateway responses */
gatewayResponses?: { [key: string]: CfnApi.GatewayResponseProperty };
/** Tags */
tags?: { [key: string]: string };
}Usage Examples:
import * as cdk from '@aws-cdk/core';
import * as sam from '@aws-cdk/aws-sam';
const stack = new cdk.Stack();
// Basic REST API
new sam.CfnApi(stack, 'MyApi', {
stageName: 'prod',
definitionBody: {
openapi: '3.0.1',
info: { title: 'My API', version: '1.0' },
paths: {
'/hello': {
get: {
responses: {
'200': {
description: 'Success',
}
}
}
}
}
},
});
// API with CORS and authentication
new sam.CfnApi(stack, 'SecureApi', {
stageName: 'prod',
cors: {
allowOrigin: '*',
allowMethods: 'GET,POST,PUT,DELETE',
allowHeaders: 'Content-Type,Authorization',
},
auth: {
defaultAuthorizer: 'MyCognitoAuth',
authorizers: {
MyCognitoAuth: {
userPoolArn: 'arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_ABC123',
}
}
}
});
// API with custom domain
new sam.CfnApi(stack, 'CustomDomainApi', {
stageName: 'prod',
domain: {
domainName: 'api.example.com',
certificateArn: 'arn:aws:acm:us-east-1:123456789012:certificate/abcd1234',
endpointConfiguration: 'REGIONAL',
route53: {
hostedZoneId: 'Z123456789',
}
}
});Creates an HTTP API Gateway (API Gateway v2) with enhanced performance and simplified configuration.
/**
* AWS::Serverless::HttpApi - HTTP API Gateway (API Gateway v2)
*/
class CfnHttpApi extends cdk.CfnResource {
constructor(
scope: cdk.Construct,
id: string,
props: CfnHttpApiProps
);
}
interface CfnHttpApiProps {
/** Stage name */
stageName?: string;
/** Authentication configuration */
auth?: CfnHttpApi.HttpApiAuthProperty;
/** CORS configuration */
corsConfiguration?: CfnHttpApi.HttpApiCorsConfigurationProperty;
/** Custom domain configuration */
domain?: CfnHttpApi.HttpApiDomainConfigurationProperty;
/** OpenAPI definition inline */
definitionBody?: any;
/** OpenAPI definition from S3 */
definitionUri?: any;
/** API name */
name?: string;
/** Access logging configuration */
accessLogSetting?: CfnHttpApi.AccessLogSettingProperty;
/** Default route settings */
defaultRouteSettings?: CfnHttpApi.RouteSettingsProperty;
/** Disable execute API endpoint */
disableExecuteApiEndpoint?: boolean;
/** Fail on warnings during deployment */
failOnWarnings?: boolean;
/** Per-route settings */
routeSettings?: { [key: string]: CfnHttpApi.RouteSettingsProperty };
/** Stage variables */
stageVariables?: { [key: string]: string };
/** Tags */
tags?: { [key: string]: string };
}Usage Examples:
// Basic HTTP API
new sam.CfnHttpApi(stack, 'MyHttpApi', {
stageName: 'v1',
corsConfiguration: {
allowOrigins: ['*'],
allowMethods: ['GET', 'POST'],
allowHeaders: ['content-type'],
}
});
// HTTP API with JWT authentication
new sam.CfnHttpApi(stack, 'JwtApi', {
stageName: 'prod',
auth: {
authorizers: {
JwtAuthorizer: {
jwtConfiguration: {
issuer: 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123',
audience: ['client-id-1', 'client-id-2'],
},
identitySource: '$request.header.Authorization',
}
},
defaultAuthorizer: 'JwtAuthorizer',
}
});interface AuthProperty {
/** Default authorizer */
defaultAuthorizer?: string;
/** Available authorizers */
authorizers?: { [key: string]: any };
/** API key configuration */
apiKeySourceType?: string;
/** Add default auth to all methods */
addDefaultAuthorizerToCorsPreflight?: boolean;
}
interface CognitoAuthorizerProperty {
/** User pool ARN */
userPoolArn?: string;
/** Header name for auth token */
header?: string;
/** Authorization scopes */
authorizationScopes?: string[];
}
interface LambdaTokenAuthorizerProperty {
/** Lambda function ARN */
functionArn?: string;
/** Lambda function payload version */
functionPayloadType?: string;
/** Identity source */
identity?: LambdaAuthorizerIdentityProperty;
/** Authorization scopes */
authorizationScopes?: string[];
}
interface LambdaRequestAuthorizerProperty {
/** Lambda function ARN */
functionArn?: string;
/** Lambda function payload version */
functionPayloadType?: string;
/** Identity source */
identity?: LambdaAuthorizerIdentityProperty;
/** Authorization scopes */
authorizationScopes?: string[];
}
interface LambdaAuthorizerIdentityProperty {
/** Headers to pass to authorizer */
headers?: string[];
/** Query strings to pass to authorizer */
queryStrings?: string[];
/** Stage variables to pass to authorizer */
stageVariables?: string[];
/** Context to pass to authorizer */
context?: string[];
/** Reauthorization TTL */
reauthorizeEvery?: number;
}interface DomainConfigurationProperty {
/** Custom domain name */
domainName?: string;
/** SSL certificate ARN */
certificateArn?: string;
/** Endpoint configuration type */
endpointConfiguration?: string;
/** Mutual TLS authentication */
mutualTlsAuthentication?: MutualTlsAuthenticationProperty;
/** Ownership verification certificate ARN */
ownershipVerificationCertificateArn?: string;
/** Route 53 configuration */
route53?: Route53ConfigurationProperty;
/** Security policy */
securityPolicy?: string;
}
interface MutualTlsAuthenticationProperty {
/** Truststore S3 URI */
truststoreUri?: string;
/** Truststore version */
truststoreVersion?: string;
}
interface Route53ConfigurationProperty {
/** Route 53 hosted zone ID */
hostedZoneId?: string;
/** Route 53 hosted zone name */
hostedZoneName?: string;
/** Evaluate target health */
evaluateTargetHealth?: boolean;
/** Route 53 record type */
ipV6?: boolean;
}interface MethodSettingProperty {
/** HTTP method */
httpMethod?: string;
/** Resource path */
resourcePath?: string;
/** Enable logging */
loggingLevel?: string;
/** Enable data trace */
dataTraceEnabled?: boolean;
/** Enable metrics */
metricsEnabled?: boolean;
/** Throttling burst limit */
throttlingBurstLimit?: number;
/** Throttling rate limit */
throttlingRateLimit?: number;
/** Caching enabled */
cachingEnabled?: boolean;
/** Cache TTL in seconds */
cacheTtlInSeconds?: number;
/** Cache key parameters */
cacheKeyParameters?: string[];
}interface AccessLogSettingProperty {
/** CloudWatch Logs destination ARN */
destinationArn?: string;
/** Log format */
format?: string;
}interface CanarySettingProperty {
/** Percentage of traffic for canary */
percentTraffic?: number;
/** Stage variables for canary */
stageVariableOverrides?: { [key: string]: string };
/** Use stage cache for canary */
useStageCache?: boolean;
/** Deployment ID for canary */
deploymentId?: string;
}interface ModelProperty {
/** Model name */
name?: string;
/** Content type */
contentType?: string;
/** JSON schema */
schema?: any;
/** Model description */
description?: string;
}interface GatewayResponseProperty {
/** HTTP status code */
statusCode?: string;
/** Response parameters */
responseParameters?: { [key: string]: string };
/** Response templates */
responseTemplates?: { [key: string]: string };
}interface HttpApiAuthProperty {
/** Available authorizers */
authorizers?: { [key: string]: any };
/** Default authorizer */
defaultAuthorizer?: string;
}
interface HttpApiJwtConfigurationProperty {
/** JWT issuer */
issuer?: string;
/** JWT audience */
audience?: string[];
}
interface HttpApiLambdaAuthorizerProperty {
/** Lambda function ARN */
functionArn?: string;
/** Identity source */
identitySource?: string[];
/** Lambda payload format version */
payloadFormatVersion?: string;
/** Authorization scopes */
authorizationScopes?: string[];
/** Authorizer result TTL */
authorizerResultTtlInSeconds?: number;
/** Enable simple responses */
enableSimpleResponses?: boolean;
}interface HttpApiCorsConfigurationProperty {
/** Allowed origins */
allowOrigins?: string[];
/** Allowed methods */
allowMethods?: string[];
/** Allowed headers */
allowHeaders?: string[];
/** Exposed headers */
exposeHeaders?: string[];
/** Max age in seconds */
maxAge?: number;
/** Allow credentials */
allowCredentials?: boolean;
}interface HttpApiDomainConfigurationProperty {
/** Custom domain name */
domainName?: string;
/** SSL certificate ARN */
certificateArn?: string;
/** Endpoint configuration type */
endpointConfiguration?: string;
/** Mutual TLS authentication */
mutualTlsAuthentication?: MutualTlsAuthenticationProperty;
/** Route 53 configuration */
route53?: Route53ConfigurationProperty;
/** Security policy */
securityPolicy?: string;
}interface RouteSettingsProperty {
/** Enable detailed metrics */
detailedMetricsEnabled?: boolean;
/** Enable logging */
loggingLevel?: string;
/** Enable data trace */
dataTraceEnabled?: boolean;
/** Throttling burst limit */
throttlingBurstLimit?: number;
/** Throttling rate limit */
throttlingRateLimit?: number;
}