Skip to content
v2.274.0

HttpApi L2 construct ​

Create a new API Gateway HTTP API endpoint.

Example ​

ts
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const booksDefaultFn: lambda.Function;
const booksIntegration = new HttpLambdaIntegration('BooksIntegration', booksDefaultFn);

const httpApi = new apigwv2.HttpApi(this, 'HttpApi');

httpApi.addRoutes({
  path: '/books',
  methods: [ apigwv2.HttpMethod.GET ],
  integration: booksIntegration,
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration

# books_default_fn: lambda.Function

books_integration = HttpLambdaIntegration("BooksIntegration", books_default_fn)

http_api = apigwv2.HttpApi(self, "HttpApi")

http_api.add_routes(
    path="/books",
    methods=[apigwv2.HttpMethod.GET],
    integration=books_integration
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpLambdaIntegration;

Function booksDefaultFn;

HttpLambdaIntegration booksIntegration = new HttpLambdaIntegration("BooksIntegration", booksDefaultFn);

HttpApi httpApi = new HttpApi(this, "HttpApi");

httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/books")
        .methods(List.of(HttpMethod.GET))
        .integration(booksIntegration)
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AwsApigatewayv2Integrations;

Function booksDefaultFn;

var booksIntegration = new HttpLambdaIntegration("BooksIntegration", booksDefaultFn);

var httpApi = new HttpApi(this, "HttpApi");

httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/books",
    Methods = new [] { HttpMethod.GET },
    Integration = booksIntegration
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"

var booksDefaultFn Function

booksIntegration := awscdk.NewHttpLambdaIntegration(jsii.String("BooksIntegration"), booksDefaultFn)

httpApi := apigwv2.NewHttpApi(this, jsii.String("HttpApi"))

httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/books"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_GET,
	},
	Integration: booksIntegration,
})

Initializer ​

ts
new HttpApi(scope: Construct, id: string, props?: HttpApiProps)
python
HttpApi(scope: Construct, id: str, props: typing.Optional[HttpApiProps] = None)
java
new HttpApi(Construct scope, String id, HttpApiProps props)
csharp
new HttpApi(Construct scope, string id, HttpApiProps? props = null)
go
NewHttpApi(Scope Construct, Id *string, Props HttpApiProps)

Construct Props ​

apiNameoptionalstringapi_nameoptionalstrapiNameoptionalStringApiNameoptionalstringApiNameoptional*string#
Name for the HTTP API resource.

Default: id of the HttpApi construct.

corsPreflightoptionalCorsPreflightOptionscors_preflightoptionalCorsPreflightOptionscorsPreflightoptionalCorsPreflightOptionsCorsPreflightoptionalCorsPreflightOptionsCorsPreflightoptionalCorsPreflightOptions#
Specifies a CORS configuration for an API.

Default: CORS disabled.

createDefaultStageoptionalbooleancreate_default_stageoptionalboolcreateDefaultStageoptionalBooleanCreateDefaultStageoptionalboolCreateDefaultStageoptional*bool= true#
Whether a default stage and deployment should be automatically created.
defaultAuthorizationScopesoptionalstring[]default_authorization_scopesoptionaltyping.List[str]defaultAuthorizationScopesoptionalList<String>DefaultAuthorizationScopesoptionalstring[]DefaultAuthorizationScopesoptional*[]*string#
Default OIDC scopes attached to all routes in the gateway, unless explicitly configured on the route.

Default: no default authorization scopes

The scopes are used with a COGNITO_USER_POOLS authorizer to authorize the method invocation.

defaultAuthorizeroptionalIHttpRouteAuthorizerdefault_authorizeroptionalIHttpRouteAuthorizerdefaultAuthorizeroptionalIHttpRouteAuthorizerDefaultAuthorizeroptionalIHttpRouteAuthorizerDefaultAuthorizeroptionalIHttpRouteAuthorizer#
Default Authorizer applied to all routes in the gateway.

Default: no default authorizer

defaultDomainMappingoptionalDomainMappingOptionsdefault_domain_mappingoptionalDomainMappingOptionsdefaultDomainMappingoptionalDomainMappingOptionsDefaultDomainMappingoptionalDomainMappingOptionsDefaultDomainMappingoptionalDomainMappingOptions#
Configure a custom domain with the API mapping resource to the HTTP API.

Default: no default domain mapping configured. meaningless if createDefaultStage is false.

defaultIntegrationoptionalHttpRouteIntegrationdefault_integrationoptionalHttpRouteIntegrationdefaultIntegrationoptionalHttpRouteIntegrationDefaultIntegrationoptionalHttpRouteIntegrationDefaultIntegrationoptionalHttpRouteIntegration= none#
An integration that will be configured on the catch-all route ($default).
descriptionoptionalstringdescriptionoptionalstrdescriptionoptionalStringDescriptionoptionalstringDescriptionoptional*string= none#
The description of the API.
disableExecuteApiEndpointoptionalbooleandisable_execute_api_endpointoptionalbooldisableExecuteApiEndpointoptionalBooleanDisableExecuteApiEndpointoptionalboolDisableExecuteApiEndpointoptional*bool#
Specifies whether clients can invoke your API using the default endpoint.

Default: false execute-api endpoint enabled.

By default, clients can invoke your API with the default https://{api_id}.execute-api.{region}.amazonaws.com endpoint. Set this to true if you would like clients to use your custom domain name.

ipAddressTypeoptionalIpAddressTypeip_address_typeoptionalIpAddressTypeipAddressTypeoptionalIpAddressTypeIpAddressTypeoptionalIpAddressTypeIpAddressTypeoptionalIpAddressType#
The IP address types that can invoke the API.

Default: undefined - AWS default is IPV4

routeSelectionExpressionoptionalbooleanroute_selection_expressionoptionalboolrouteSelectionExpressionoptionalBooleanRouteSelectionExpressionoptionalboolRouteSelectionExpressionoptional*bool= false#
Whether to set the default route selection expression for the API.

When enabled, "${request.method} ${request.path}" is set as the default route selection expression.

Properties ​

apiEndpointstringapi_endpointstrapiEndpointStringApiEndpointstringApiEndpoint*stringrequired#
Get the default endpoint for this API.
apiIdstringapi_idstrapiIdStringApiIdstringApiId*stringrequired#
The identifier of this API Gateway API.
A reference to a Api resource.
defaultAuthorizationScopesmay be undefinedstring[]default_authorization_scopesmay be undefinedtyping.List[str]defaultAuthorizationScopesmay be undefinedList<String>DefaultAuthorizationScopesmay be undefinedstring[]DefaultAuthorizationScopesmay be undefined*[]*string#
Default OIDC scopes attached to all routes in the gateway, unless explicitly configured on the route.

The scopes are used with a COGNITO_USER_POOLS authorizer to authorize the method invocation.

defaultAuthorizermay be undefinedIHttpRouteAuthorizerdefault_authorizermay be undefinedIHttpRouteAuthorizerdefaultAuthorizermay be undefinedIHttpRouteAuthorizerDefaultAuthorizermay be undefinedIHttpRouteAuthorizerDefaultAuthorizermay be undefinedIHttpRouteAuthorizer#
Default Authorizer applied to all routes in the gateway.
defaultStagemay be undefinedIHttpStagedefault_stagemay be undefinedIHttpStagedefaultStagemay be undefinedIHttpStageDefaultStagemay be undefinedIHttpStageDefaultStagemay be undefinedIHttpStage#
The default stage of this API.
disableExecuteApiEndpointmay be undefinedbooleandisable_execute_api_endpointmay be undefinedbooldisableExecuteApiEndpointmay be undefinedBooleanDisableExecuteApiEndpointmay be undefinedboolDisableExecuteApiEndpointmay be undefined*bool#
Specifies whether clients can invoke this HTTP API by using the default execute-api endpoint.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

httpApiIdstringhttp_api_idstrhttpApiIdStringHttpApiIdstringHttpApiId*stringrequired#
The identifier of the HTTP API.
httpApiNamemay be undefinedstringhttp_api_namemay be undefinedstrhttpApiNamemay be undefinedStringHttpApiNamemay be undefinedstringHttpApiNamemay be undefined*string#
A human friendly name for this HTTP API.

Note that this is different from httpApiId.

isHttpApibooleanis_http_apiboolisHttpApiBooleanIsHttpApiboolIsHttpApi*boolrequired#
Indicates that this is an HTTP API.

Will always return true, but is necessary to prevent accidental structural equality in TypeScript.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
urlmay be undefinedstringurlmay be undefinedstrurlmay be undefinedStringUrlmay be undefinedstringUrlmay be undefined*string#
Get the URL to the default stage of this API.

Returns undefined if createDefaultStage is unset.

Methods ​

addRoutes(options: AddRoutesOptions): HttpRoute[]def add_routes(self, options: AddRoutesOptions) -> typing.List[HttpRoute]public List<HttpRoute> addRoutes(AddRoutesOptions options)public HttpRoute[] AddRoutes(AddRoutesOptions options)func AddRoutes(Options AddRoutesOptions) *[]HttpRoute#
Add multiple routes that uses the same configuration.

The routes all go to the same path, but for different methods.

addStage(id: string, options: HttpStageOptions): HttpStagedef add_stage(self, id: str, options: HttpStageOptions) -> HttpStagepublic HttpStage addStage(String id, HttpStageOptions options)public HttpStage AddStage(string id, HttpStageOptions options)func AddStage(Id *string, Options HttpStageOptions) HttpStage#
Add a new stage.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

arnForExecuteApi(method?: string, path?: string, stage?: string): stringdef arn_for_execute_api(self, method: typing.Optional[str] = None, path: typing.Optional[str] = None, stage: typing.Optional[str] = None) -> strpublic String arnForExecuteApi(String method, String path, String stage)public string ArnForExecuteApi(string? method = null, string? path = null, string? stage = null)func ArnForExecuteApi(Method *string, Path *string, Stage *string) *string#
Get the "execute-api" ARN.

When 'ANY' is passed to the method, an ARN with the method set to '*' is obtained.

fromHttpApiAttributes(scope: Construct, id: string, attrs: HttpApiAttributes): IHttpApi@staticmethod def from_http_api_attributes(scope: Construct, id: str, attrs: HttpApiAttributes) -> IHttpApipublic static IHttpApi fromHttpApiAttributes(Construct scope, String id, HttpApiAttributes attrs)public static IHttpApi FromHttpApiAttributes(Construct scope, string id, HttpApiAttributes attrs)func FromHttpApiAttributes(Scope Construct, Id *string, Attrs HttpApiAttributes) IHttpApistatic#
Import an existing HTTP API into this CDK app.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#
Return the given named metric for this Api Gateway.
metricClientError(props?: MetricOptions): Metricdef metric_client_error(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricClientError(MetricOptions props)public Metric MetricClientError(MetricOptions? props = null)func MetricClientError(Props MetricOptions) Metric#
Metric for the number of client-side errors captured in a given period.
metricCount(props?: MetricOptions): Metricdef metric_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCount(MetricOptions props)public Metric MetricCount(MetricOptions? props = null)func MetricCount(Props MetricOptions) Metric#
Metric for the total number API requests in a given period.
metricDataProcessed(props?: MetricOptions): Metricdef metric_data_processed(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricDataProcessed(MetricOptions props)public Metric MetricDataProcessed(MetricOptions? props = null)func MetricDataProcessed(Props MetricOptions) Metric#
Metric for the amount of data processed in bytes.
metricIntegrationLatency(props?: MetricOptions): Metricdef metric_integration_latency(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricIntegrationLatency(MetricOptions props)public Metric MetricIntegrationLatency(MetricOptions? props = null)func MetricIntegrationLatency(Props MetricOptions) Metric#
Metric for the time between when API Gateway relays a request to the backend and when it receives a response from the backend.
metricLatency(props?: MetricOptions): Metricdef metric_latency(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricLatency(MetricOptions props)public Metric MetricLatency(MetricOptions? props = null)func MetricLatency(Props MetricOptions) 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.

metricServerError(props?: MetricOptions): Metricdef metric_server_error(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricServerError(MetricOptions props)public Metric MetricServerError(MetricOptions? props = null)func MetricServerError(Props MetricOptions) Metric#
Metric for the number of server-side errors captured in a given period.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.