Skip to content
v2.274.0

AWS APIGatewayv2 Integrations ​

HTTP APIs ​

Integrations connect a route to backend resources. HTTP APIs support Lambda proxy, AWS service, and HTTP proxy integrations. HTTP proxy integrations are also known as private integrations.

Lambda ​

Lambda integrations enable integrating an HTTP API route with a Lambda function. When a client invokes the route, the API Gateway service forwards the request to the Lambda function and returns the function's response to the client.

The API Gateway service will invoke the Lambda function with an event payload of a specific format. The service expects the function to respond in a specific format. The details on this format are available at Working with AWS Lambda proxy integrations.

The following code configures a route GET /books with a Lambda proxy integration.

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
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
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,
})

Lambda Integration Permissions ​

By default, creating a HttpLambdaIntegration will add a permission for API Gateway to invoke your AWS Lambda function, scoped to the specific route which uses the integration.

If you reuse the same AWS Lambda function for many integrations, the AWS Lambda permission policy size can be exceeded by adding a separate policy statement for each route which invokes the AWS Lambda function. To avoid this, you can opt to scope permissions to any route on the API by setting scopePermissionToRoute to false, and this will ensure only a single policy statement is added to the AWS Lambda permission policy.

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

declare const booksDefaultFn: lambda.Function;

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

const getBooksIntegration = new HttpLambdaIntegration('GetBooksIntegration', booksDefaultFn, {
  scopePermissionToRoute: false,
});
const createBookIntegration = new HttpLambdaIntegration('CreateBookIntegration', booksDefaultFn, {
  scopePermissionToRoute: false,
});

httpApi.addRoutes({
  path: '/books',
  methods: [ apigwv2.HttpMethod.GET ],
  integration: getBooksIntegration,
});

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

# books_default_fn: lambda.Function


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

get_books_integration = HttpLambdaIntegration("GetBooksIntegration", books_default_fn,
    scope_permission_to_route=False
)
create_book_integration = HttpLambdaIntegration("CreateBookIntegration", books_default_fn,
    scope_permission_to_route=False
)

http_api.add_routes(
    path="/books",
    methods=[apigwv2.HttpMethod.GET],
    integration=get_books_integration
)

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

Function booksDefaultFn;


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

HttpLambdaIntegration getBooksIntegration = HttpLambdaIntegration.Builder.create("GetBooksIntegration", booksDefaultFn)
        .scopePermissionToRoute(false)
        .build();
HttpLambdaIntegration createBookIntegration = HttpLambdaIntegration.Builder.create("CreateBookIntegration", booksDefaultFn)
        .scopePermissionToRoute(false)
        .build();

httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/books")
        .methods(List.of(HttpMethod.GET))
        .integration(getBooksIntegration)
        .build());

httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/books")
        .methods(List.of(HttpMethod.POST))
        .integration(createBookIntegration)
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function booksDefaultFn;


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

var getBooksIntegration = new HttpLambdaIntegration("GetBooksIntegration", booksDefaultFn, new HttpLambdaIntegrationProps {
    ScopePermissionToRoute = false
});
var createBookIntegration = new HttpLambdaIntegration("CreateBookIntegration", booksDefaultFn, new HttpLambdaIntegrationProps {
    ScopePermissionToRoute = false
});

httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/books",
    Methods = new [] { HttpMethod.GET },
    Integration = getBooksIntegration
});

httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/books",
    Methods = new [] { HttpMethod.POST },
    Integration = createBookIntegration
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var booksDefaultFn Function


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

getBooksIntegration := awscdk.NewHttpLambdaIntegration(jsii.String("GetBooksIntegration"), booksDefaultFn, &HttpLambdaIntegrationProps{
	ScopePermissionToRoute: jsii.Boolean(false),
})
createBookIntegration := awscdk.NewHttpLambdaIntegration(jsii.String("CreateBookIntegration"), booksDefaultFn, &HttpLambdaIntegrationProps{
	ScopePermissionToRoute: jsii.Boolean(false),
})

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

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

In the above example, a single permission is added, shared by both getBookIntegration and createBookIntegration.

HTTP Proxy ​

HTTP Proxy integrations enables connecting an HTTP API route to a publicly routable HTTP endpoint. When a client invokes the route, the API Gateway service forwards the entire request and response between the API Gateway endpoint and the integrating HTTP endpoint. More information can be found at Working with HTTP proxy integrations.

The following code configures a route GET /books with an HTTP proxy integration to an HTTP endpoint get-books-proxy.example.com.

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

const booksIntegration = new HttpUrlIntegration('BooksIntegration', 'https://get-books-proxy.example.com');

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 HttpUrlIntegration


books_integration = HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com")

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.HttpUrlIntegration;


HttpUrlIntegration booksIntegration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com");

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

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


var booksIntegration = new HttpUrlIntegration("BooksIntegration", "https://get-books-proxy.example.com");

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

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


booksIntegration := awscdk.NewHttpUrlIntegration(jsii.String("BooksIntegration"), jsii.String("https://get-books-proxy.example.com"))

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

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

StepFunctions Integration ​

Step Functions integrations enable integrating an HTTP API route with AWS Step Functions. This allows the HTTP API to start state machine executions synchronously or asynchronously, or to stop executions.

When a client invokes the route configured with a Step Functions integration, the API Gateway service interacts with the specified state machine according to the integration subtype (e.g., starts a new execution, synchronously starts an execution, or stops an execution) and returns the response to the client.

The following code configures a Step Functions integrations:

ts
import { HttpStepFunctionsIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';

declare const stateMachine: sfn.StateMachine;
declare const httpApi: apigwv2.HttpApi;

httpApi.addRoutes({
  path: '/start',
  methods: [ apigwv2.HttpMethod.POST ],
  integration: new HttpStepFunctionsIntegration('StartExecutionIntegration', {
    stateMachine,
    subtype: apigwv2.HttpIntegrationSubtype.STEPFUNCTIONS_START_EXECUTION,
  }),
});

httpApi.addRoutes({
  path: '/start-sync',
  methods: [ apigwv2.HttpMethod.POST ],
  integration: new HttpStepFunctionsIntegration('StartSyncExecutionIntegration', {
    stateMachine,
    subtype: apigwv2.HttpIntegrationSubtype.STEPFUNCTIONS_START_SYNC_EXECUTION,
  }),
});

httpApi.addRoutes({
  path: '/stop',
  methods: [ apigwv2.HttpMethod.POST ],
  integration: new HttpStepFunctionsIntegration('StopExecutionIntegration', {
    stateMachine,
    subtype: apigwv2.HttpIntegrationSubtype.STEPFUNCTIONS_STOP_EXECUTION,
    // For the `STOP_EXECUTION` subtype, it is necessary to specify the `executionArn`.
    parameterMapping: new apigwv2.ParameterMapping()
      .custom('ExecutionArn', '$request.querystring.executionArn'),
  }),
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpStepFunctionsIntegration
import aws_cdk.aws_stepfunctions as sfn

# state_machine: sfn.StateMachine
# http_api: apigwv2.HttpApi


http_api.add_routes(
    path="/start",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpStepFunctionsIntegration("StartExecutionIntegration",
        state_machine=state_machine,
        subtype=apigwv2.HttpIntegrationSubtype.STEPFUNCTIONS_START_EXECUTION
    )
)

http_api.add_routes(
    path="/start-sync",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpStepFunctionsIntegration("StartSyncExecutionIntegration",
        state_machine=state_machine,
        subtype=apigwv2.HttpIntegrationSubtype.STEPFUNCTIONS_START_SYNC_EXECUTION
    )
)

http_api.add_routes(
    path="/stop",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpStepFunctionsIntegration("StopExecutionIntegration",
        state_machine=state_machine,
        subtype=apigwv2.HttpIntegrationSubtype.STEPFUNCTIONS_STOP_EXECUTION,
        # For the `STOP_EXECUTION` subtype, it is necessary to specify the `executionArn`.
        parameter_mapping=apigwv2.ParameterMapping().custom("ExecutionArn", "$request.querystring.executionArn")
    )
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpStepFunctionsIntegration;
import software.amazon.awscdk.services.stepfunctions.*;

StateMachine stateMachine;
HttpApi httpApi;


httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/start")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpStepFunctionsIntegration.Builder.create("StartExecutionIntegration")
                .stateMachine(stateMachine)
                .subtype(HttpIntegrationSubtype.STEPFUNCTIONS_START_EXECUTION)
                .build())
        .build());

httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/start-sync")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpStepFunctionsIntegration.Builder.create("StartSyncExecutionIntegration")
                .stateMachine(stateMachine)
                .subtype(HttpIntegrationSubtype.STEPFUNCTIONS_START_SYNC_EXECUTION)
                .build())
        .build());

httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/stop")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpStepFunctionsIntegration.Builder.create("StopExecutionIntegration")
                .stateMachine(stateMachine)
                .subtype(HttpIntegrationSubtype.STEPFUNCTIONS_STOP_EXECUTION)
                // For the `STOP_EXECUTION` subtype, it is necessary to specify the `executionArn`.
                .parameterMapping(new ParameterMapping().custom("ExecutionArn", "$request.querystring.executionArn"))
                .build())
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;
using Amazon.CDK.AWS.StepFunctions;

StateMachine stateMachine;
HttpApi httpApi;


httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/start",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpStepFunctionsIntegration("StartExecutionIntegration", new HttpStepFunctionsIntegrationProps {
        StateMachine = stateMachine,
        Subtype = HttpIntegrationSubtype.STEPFUNCTIONS_START_EXECUTION
    })
});

httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/start-sync",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpStepFunctionsIntegration("StartSyncExecutionIntegration", new HttpStepFunctionsIntegrationProps {
        StateMachine = stateMachine,
        Subtype = HttpIntegrationSubtype.STEPFUNCTIONS_START_SYNC_EXECUTION
    })
});

httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/stop",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpStepFunctionsIntegration("StopExecutionIntegration", new HttpStepFunctionsIntegrationProps {
        StateMachine = stateMachine,
        Subtype = HttpIntegrationSubtype.STEPFUNCTIONS_STOP_EXECUTION,
        // For the `STOP_EXECUTION` subtype, it is necessary to specify the `executionArn`.
        ParameterMapping = new ParameterMapping().Custom("ExecutionArn", "$request.querystring.executionArn")
    })
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import sfn "github.com/aws/aws-cdk-go/awscdk"

var stateMachine StateMachine
var httpApi HttpApi


httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/start"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpStepFunctionsIntegration(jsii.String("StartExecutionIntegration"), &HttpStepFunctionsIntegrationProps{
		StateMachine: *StateMachine,
		Subtype: apigwv2.HttpIntegrationSubtype_STEPFUNCTIONS_START_EXECUTION,
	}),
})

httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/start-sync"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpStepFunctionsIntegration(jsii.String("StartSyncExecutionIntegration"), &HttpStepFunctionsIntegrationProps{
		StateMachine: *StateMachine,
		Subtype: apigwv2.HttpIntegrationSubtype_STEPFUNCTIONS_START_SYNC_EXECUTION,
	}),
})

httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/stop"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpStepFunctionsIntegration(jsii.String("StopExecutionIntegration"), &HttpStepFunctionsIntegrationProps{
		StateMachine: *StateMachine,
		Subtype: apigwv2.HttpIntegrationSubtype_STEPFUNCTIONS_STOP_EXECUTION,
		// For the `STOP_EXECUTION` subtype, it is necessary to specify the `executionArn`.
		ParameterMapping: apigwv2.NewParameterMapping().Custom(jsii.String("ExecutionArn"), jsii.String("$request.querystring.executionArn")),
	}),
})

Note:

  • The executionArn parameter is required for the STOP_EXECUTION subtype. It is necessary to specify the executionArn in the parameterMapping property of the HttpStepFunctionsIntegration object.
  • START_SYNC_EXECUTION subtype is only supported for EXPRESS type state machine.

SQS Integration ​

SQS integrations enable integrating an HTTP API route with AWS SQS. This allows the HTTP API to send, receive and delete messages from an SQS queue.

The following code configures a SQS integrations:

ts
import * as sqs from 'aws-cdk-lib/aws-sqs';
import { HttpSqsIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const queue: sqs.IQueue;
declare const httpApi: apigwv2.HttpApi;

// default integration (send message)
httpApi.addRoutes({
  path: '/default',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpSqsIntegration('defaultIntegration', {
    queue,
  }),
});
// send message integration
httpApi.addRoutes({
  path: '/send-message',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpSqsIntegration('sendMessageIntegration', {
    queue,
    subtype: apigwv2.HttpIntegrationSubtype.SQS_SEND_MESSAGE,
  }),
});
// receive message integration
httpApi.addRoutes({
  path: '/receive-message',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpSqsIntegration('receiveMessageIntegration', {
    queue,
    subtype: apigwv2.HttpIntegrationSubtype.SQS_RECEIVE_MESSAGE,
  }),
});
// delete message integration
httpApi.addRoutes({
  path: '/delete-message',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpSqsIntegration('deleteMessageIntegration', {
    queue,
    subtype: apigwv2.HttpIntegrationSubtype.SQS_DELETE_MESSAGE,
  }),
});
// purge queue integration
httpApi.addRoutes({
  path: '/purge-queue',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpSqsIntegration('purgeQueueIntegration', {
    queue,
    subtype: apigwv2.HttpIntegrationSubtype.SQS_PURGE_QUEUE,
  }),
});
python
import aws_cdk.aws_sqs as sqs
from aws_cdk.aws_apigatewayv2_integrations import HttpSqsIntegration

# queue: sqs.IQueue
# http_api: apigwv2.HttpApi


# default integration (send message)
http_api.add_routes(
    path="/default",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpSqsIntegration("defaultIntegration",
        queue=queue
    )
)
# send message integration
http_api.add_routes(
    path="/send-message",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpSqsIntegration("sendMessageIntegration",
        queue=queue,
        subtype=apigwv2.HttpIntegrationSubtype.SQS_SEND_MESSAGE
    )
)
# receive message integration
http_api.add_routes(
    path="/receive-message",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpSqsIntegration("receiveMessageIntegration",
        queue=queue,
        subtype=apigwv2.HttpIntegrationSubtype.SQS_RECEIVE_MESSAGE
    )
)
# delete message integration
http_api.add_routes(
    path="/delete-message",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpSqsIntegration("deleteMessageIntegration",
        queue=queue,
        subtype=apigwv2.HttpIntegrationSubtype.SQS_DELETE_MESSAGE
    )
)
# purge queue integration
http_api.add_routes(
    path="/purge-queue",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpSqsIntegration("purgeQueueIntegration",
        queue=queue,
        subtype=apigwv2.HttpIntegrationSubtype.SQS_PURGE_QUEUE
    )
)
java
import software.amazon.awscdk.services.sqs.*;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpSqsIntegration;

IQueue queue;
HttpApi httpApi;


// default integration (send message)
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/default")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpSqsIntegration.Builder.create("defaultIntegration")
                .queue(queue)
                .build())
        .build());
// send message integration
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/send-message")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpSqsIntegration.Builder.create("sendMessageIntegration")
                .queue(queue)
                .subtype(HttpIntegrationSubtype.SQS_SEND_MESSAGE)
                .build())
        .build());
// receive message integration
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/receive-message")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpSqsIntegration.Builder.create("receiveMessageIntegration")
                .queue(queue)
                .subtype(HttpIntegrationSubtype.SQS_RECEIVE_MESSAGE)
                .build())
        .build());
// delete message integration
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/delete-message")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpSqsIntegration.Builder.create("deleteMessageIntegration")
                .queue(queue)
                .subtype(HttpIntegrationSubtype.SQS_DELETE_MESSAGE)
                .build())
        .build());
// purge queue integration
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/purge-queue")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpSqsIntegration.Builder.create("purgeQueueIntegration")
                .queue(queue)
                .subtype(HttpIntegrationSubtype.SQS_PURGE_QUEUE)
                .build())
        .build());
csharp
using Amazon.CDK.AWS.SQS;
using Amazon.CDK.AwsApigatewayv2Integrations;

IQueue queue;
HttpApi httpApi;


// default integration (send message)
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/default",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpSqsIntegration("defaultIntegration", new HttpSqsIntegrationProps {
        Queue = queue
    })
});
// send message integration
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/send-message",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpSqsIntegration("sendMessageIntegration", new HttpSqsIntegrationProps {
        Queue = queue,
        Subtype = HttpIntegrationSubtype.SQS_SEND_MESSAGE
    })
});
// receive message integration
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/receive-message",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpSqsIntegration("receiveMessageIntegration", new HttpSqsIntegrationProps {
        Queue = queue,
        Subtype = HttpIntegrationSubtype.SQS_RECEIVE_MESSAGE
    })
});
// delete message integration
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/delete-message",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpSqsIntegration("deleteMessageIntegration", new HttpSqsIntegrationProps {
        Queue = queue,
        Subtype = HttpIntegrationSubtype.SQS_DELETE_MESSAGE
    })
});
// purge queue integration
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/purge-queue",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpSqsIntegration("purgeQueueIntegration", new HttpSqsIntegrationProps {
        Queue = queue,
        Subtype = HttpIntegrationSubtype.SQS_PURGE_QUEUE
    })
});
go
import sqs "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var queue IQueue
var httpApi HttpApi


// default integration (send message)
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/default"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpSqsIntegration(jsii.String("defaultIntegration"), &HttpSqsIntegrationProps{
		Queue: *Queue,
	}),
})
// send message integration
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/send-message"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpSqsIntegration(jsii.String("sendMessageIntegration"), &HttpSqsIntegrationProps{
		Queue: *Queue,
		Subtype: apigwv2.HttpIntegrationSubtype_SQS_SEND_MESSAGE,
	}),
})
// receive message integration
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/receive-message"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpSqsIntegration(jsii.String("receiveMessageIntegration"), &HttpSqsIntegrationProps{
		Queue: *Queue,
		Subtype: apigwv2.HttpIntegrationSubtype_SQS_RECEIVE_MESSAGE,
	}),
})
// delete message integration
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/delete-message"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpSqsIntegration(jsii.String("deleteMessageIntegration"), &HttpSqsIntegrationProps{
		Queue: *Queue,
		Subtype: apigwv2.HttpIntegrationSubtype_SQS_DELETE_MESSAGE,
	}),
})
// purge queue integration
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/purge-queue"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpSqsIntegration(jsii.String("purgeQueueIntegration"), &HttpSqsIntegrationProps{
		Queue: *Queue,
		Subtype: apigwv2.HttpIntegrationSubtype_SQS_PURGE_QUEUE,
	}),
})

SQS integration parameter mappings ​

You can configure the custom parameter mappings of the SQS integration using the parameterMapping property of the HttpSqsIntegration object.

The default parameter mapping settings for each subtype are as follows:

ts
import * as sqs from 'aws-cdk-lib/aws-sqs';
declare const queue: sqs.IQueue;

// SQS_SEND_MESSAGE
new apigwv2.ParameterMapping()
  .custom('QueueUrl', queue.queueUrl)
  // The `MessageBody` is expected to be in the request body.
  .custom('MessageBody', '$request.body.MessageBody');

// SQS_RECEIVE_MESSAGE
new apigwv2.ParameterMapping()
  .custom('QueueUrl', queue.queueUrl);

// SQS_DELETE_MESSAGE
new apigwv2.ParameterMapping()
  .custom('QueueUrl', queue.queueUrl)
  // The `ReceiptHandle` is expected to be in the request body.
  .custom('ReceiptHandle', '$request.body.ReceiptHandle');

// SQS_PURGE_QUEUE
new apigwv2.ParameterMapping()
  .custom('QueueUrl', queue.queueUrl);
python
import aws_cdk.aws_sqs as sqs
# queue: sqs.IQueue


# SQS_SEND_MESSAGE
apigwv2.ParameterMapping().custom("QueueUrl", queue.queue_url).custom("MessageBody", "$request.body.MessageBody")

# SQS_RECEIVE_MESSAGE
apigwv2.ParameterMapping().custom("QueueUrl", queue.queue_url)

# SQS_DELETE_MESSAGE
apigwv2.ParameterMapping().custom("QueueUrl", queue.queue_url).custom("ReceiptHandle", "$request.body.ReceiptHandle")

# SQS_PURGE_QUEUE
apigwv2.ParameterMapping().custom("QueueUrl", queue.queue_url)
java
import software.amazon.awscdk.services.sqs.*;
IQueue queue;


// SQS_SEND_MESSAGE
// SQS_SEND_MESSAGE
new ParameterMapping().custom("QueueUrl", queue.queueUrl).custom("MessageBody", "$request.body.MessageBody");

// SQS_RECEIVE_MESSAGE
// SQS_RECEIVE_MESSAGE
new ParameterMapping().custom("QueueUrl", queue.getQueueUrl());

// SQS_DELETE_MESSAGE
// SQS_DELETE_MESSAGE
new ParameterMapping().custom("QueueUrl", queue.queueUrl).custom("ReceiptHandle", "$request.body.ReceiptHandle");

// SQS_PURGE_QUEUE
// SQS_PURGE_QUEUE
new ParameterMapping().custom("QueueUrl", queue.getQueueUrl());
csharp
using Amazon.CDK.AWS.SQS;
IQueue queue;


// SQS_SEND_MESSAGE
// SQS_SEND_MESSAGE
new ParameterMapping().Custom("QueueUrl", queue.QueueUrl).Custom("MessageBody", "$request.body.MessageBody");

// SQS_RECEIVE_MESSAGE
// SQS_RECEIVE_MESSAGE
new ParameterMapping().Custom("QueueUrl", queue.QueueUrl);

// SQS_DELETE_MESSAGE
// SQS_DELETE_MESSAGE
new ParameterMapping().Custom("QueueUrl", queue.QueueUrl).Custom("ReceiptHandle", "$request.body.ReceiptHandle");

// SQS_PURGE_QUEUE
// SQS_PURGE_QUEUE
new ParameterMapping().Custom("QueueUrl", queue.QueueUrl);
go
import sqs "github.com/aws/aws-cdk-go/awscdk"
var queue IQueue


// SQS_SEND_MESSAGE
// SQS_SEND_MESSAGE
apigwv2.NewParameterMapping().Custom(jsii.String("QueueUrl"), queue.QueueUrl).Custom(jsii.String("MessageBody"), jsii.String("$request.body.MessageBody"))

// SQS_RECEIVE_MESSAGE
// SQS_RECEIVE_MESSAGE
apigwv2.NewParameterMapping().Custom(jsii.String("QueueUrl"), queue.QueueUrl)

// SQS_DELETE_MESSAGE
// SQS_DELETE_MESSAGE
apigwv2.NewParameterMapping().Custom(jsii.String("QueueUrl"), queue.QueueUrl).Custom(jsii.String("ReceiptHandle"), jsii.String("$request.body.ReceiptHandle"))

// SQS_PURGE_QUEUE
// SQS_PURGE_QUEUE
apigwv2.NewParameterMapping().Custom(jsii.String("QueueUrl"), queue.QueueUrl)

EventBridge Integration ​

EventBridge integrations enable integrating an HTTP API route with Amazon EventBridge using the PutEvents API. This allows the HTTP API to forward requests as events to an EventBridge event bus.

The following code configures EventBridge integrations:

ts
import * as events from 'aws-cdk-lib/aws-events';
import { HttpEventBridgeIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const bus: events.IEventBus;
declare const httpApi: apigwv2.HttpApi;

// default integration (PutEvents)
httpApi.addRoutes({
  path: '/default',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpEventBridgeIntegration('DefaultEventBridgeIntegration', {
    eventBusRef: bus.eventBusRef,
  }),
});

// explicit subtype
httpApi.addRoutes({
  path: '/put-events',
  methods: [apigwv2.HttpMethod.POST],
  integration: new HttpEventBridgeIntegration('ExplicitSubtypeIntegration', {
    eventBusRef: bus.eventBusRef,
    subtype: apigwv2.HttpIntegrationSubtype.EVENTBRIDGE_PUT_EVENTS,
  }),
});
python
import aws_cdk.aws_events as events
from aws_cdk.aws_apigatewayv2_integrations import HttpEventBridgeIntegration

# bus: events.IEventBus
# http_api: apigwv2.HttpApi


# default integration (PutEvents)
http_api.add_routes(
    path="/default",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpEventBridgeIntegration("DefaultEventBridgeIntegration",
        event_bus_ref=bus.event_bus_ref
    )
)

# explicit subtype
http_api.add_routes(
    path="/put-events",
    methods=[apigwv2.HttpMethod.POST],
    integration=HttpEventBridgeIntegration("ExplicitSubtypeIntegration",
        event_bus_ref=bus.event_bus_ref,
        subtype=apigwv2.HttpIntegrationSubtype.EVENTBRIDGE_PUT_EVENTS
    )
)
java
import software.amazon.awscdk.services.events.*;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpEventBridgeIntegration;

IEventBus bus;
HttpApi httpApi;


// default integration (PutEvents)
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/default")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpEventBridgeIntegration.Builder.create("DefaultEventBridgeIntegration")
                .eventBusRef(bus.getEventBusRef())
                .build())
        .build());

// explicit subtype
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/put-events")
        .methods(List.of(HttpMethod.POST))
        .integration(HttpEventBridgeIntegration.Builder.create("ExplicitSubtypeIntegration")
                .eventBusRef(bus.getEventBusRef())
                .subtype(HttpIntegrationSubtype.EVENTBRIDGE_PUT_EVENTS)
                .build())
        .build());
csharp
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AwsApigatewayv2Integrations;

IEventBus bus;
HttpApi httpApi;


// default integration (PutEvents)
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/default",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpEventBridgeIntegration("DefaultEventBridgeIntegration", new HttpEventBridgeIntegrationProps {
        EventBusRef = bus.EventBusRef
    })
});

// explicit subtype
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/put-events",
    Methods = new [] { HttpMethod.POST },
    Integration = new HttpEventBridgeIntegration("ExplicitSubtypeIntegration", new HttpEventBridgeIntegrationProps {
        EventBusRef = bus.EventBusRef,
        Subtype = HttpIntegrationSubtype.EVENTBRIDGE_PUT_EVENTS
    })
});
go
import events "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var bus IEventBus
var httpApi HttpApi


// default integration (PutEvents)
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/default"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpEventBridgeIntegration(jsii.String("DefaultEventBridgeIntegration"), &HttpEventBridgeIntegrationProps{
		EventBusRef: bus.EventBusRef,
	}),
})

// explicit subtype
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/put-events"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_POST,
	},
	Integration: awscdk.NewHttpEventBridgeIntegration(jsii.String("ExplicitSubtypeIntegration"), &HttpEventBridgeIntegrationProps{
		EventBusRef: bus.*EventBusRef,
		Subtype: apigwv2.HttpIntegrationSubtype_EVENTBRIDGE_PUT_EVENTS,
	}),
})

EventBridge integration parameter mappings ​

You can configure the custom parameter mappings of the EventBridge integration using the parameterMapping property of the HttpEventBridgeIntegration object.

By default, the integration expects the request body to contain Detail, DetailType, and Source fields. The EventBusName is automatically included from eventBusRef in all cases, even when a custom parameterMapping is provided (unless explicitly overridden). This ensures consistency and eliminates redundant configuration.

The default parameter mapping is as follows:

ts
import * as events from 'aws-cdk-lib/aws-events';
declare const bus: events.IEventBus;

new apigwv2.ParameterMapping()
  // The following fields are required for the EventBridge PutEvents integration
  .custom('Detail', '$request.body.Detail')
  .custom('DetailType', '$request.body.DetailType')
  .custom('Source', '$request.body.Source')
  // EventBusName is automatically included from eventBusRef
  .custom('EventBusName', bus.eventBusName);
python
import aws_cdk.aws_events as events
# bus: events.IEventBus


apigwv2.ParameterMapping().custom("Detail", "$request.body.Detail").custom("DetailType", "$request.body.DetailType").custom("Source", "$request.body.Source").custom("EventBusName", bus.event_bus_name)
java
import software.amazon.awscdk.services.events.*;
IEventBus bus;


new ParameterMapping().custom("Detail", "$request.body.Detail").custom("DetailType", "$request.body.DetailType").custom("Source", "$request.body.Source").custom("EventBusName", bus.getEventBusName());
csharp
using Amazon.CDK.AWS.Events;
IEventBus bus;


new ParameterMapping().Custom("Detail", "$request.body.Detail").Custom("DetailType", "$request.body.DetailType").Custom("Source", "$request.body.Source").Custom("EventBusName", bus.EventBusName);
go
import events "github.com/aws/aws-cdk-go/awscdk"
var bus IEventBus


apigwv2.NewParameterMapping().Custom(jsii.String("Detail"), jsii.String("$request.body.Detail")).Custom(jsii.String("DetailType"), jsii.String("$request.body.DetailType")).Custom(jsii.String("Source"), jsii.String("$request.body.Source")).Custom(jsii.String("EventBusName"), bus.EventBusName)

When providing a custom parameterMapping, you don't need to include EventBusName - it will be automatically added from eventBusRef:

Private Integration ​

Private integrations enable integrating an HTTP API route with private resources in a VPC, such as Application Load Balancers or Amazon ECS container-based applications. Using private integrations, resources in a VPC can be exposed for access by clients outside of the VPC.

The following integrations are supported for private resources in a VPC.

Application Load Balancer ​

The following code is a basic application load balancer private integration of HTTP API:

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

const vpc = new ec2.Vpc(this, 'VPC');
const lb = new elbv2.ApplicationLoadBalancer(this, 'lb', { vpc });
const listener = lb.addListener('listener', { port: 80 });
listener.addTargets('target', {
  port: 80,
});

const httpEndpoint = new apigwv2.HttpApi(this, 'HttpProxyPrivateApi', {
  defaultIntegration: new HttpAlbIntegration('DefaultIntegration', listener),
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpAlbIntegration


vpc = ec2.Vpc(self, "VPC")
lb = elbv2.ApplicationLoadBalancer(self, "lb", vpc=vpc)
listener = lb.add_listener("listener", port=80)
listener.add_targets("target",
    port=80
)

http_endpoint = apigwv2.HttpApi(self, "HttpProxyPrivateApi",
    default_integration=HttpAlbIntegration("DefaultIntegration", listener)
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpAlbIntegration;


Vpc vpc = new Vpc(this, "VPC");
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "lb").vpc(vpc).build();
ApplicationListener listener = lb.addListener("listener", BaseApplicationListenerProps.builder().port(80).build());
listener.addTargets("target", AddApplicationTargetsProps.builder()
        .port(80)
        .build());

HttpApi httpEndpoint = HttpApi.Builder.create(this, "HttpProxyPrivateApi")
        .defaultIntegration(new HttpAlbIntegration("DefaultIntegration", listener))
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;


var vpc = new Vpc(this, "VPC");
var lb = new ApplicationLoadBalancer(this, "lb", new ApplicationLoadBalancerProps { Vpc = vpc });
var listener = lb.AddListener("listener", new BaseApplicationListenerProps { Port = 80 });
listener.AddTargets("target", new AddApplicationTargetsProps {
    Port = 80
});

var httpEndpoint = new HttpApi(this, "HttpProxyPrivateApi", new HttpApiProps {
    DefaultIntegration = new HttpAlbIntegration("DefaultIntegration", listener)
});
go
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("VPC"))
lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("lb"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
})
listener := lb.AddListener(jsii.String("listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
listener.AddTargets(jsii.String("target"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
})

httpEndpoint := apigwv2.NewHttpApi(this, jsii.String("HttpProxyPrivateApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpAlbIntegration(jsii.String("DefaultIntegration"), listener),
})

When an imported load balancer is used, the vpc option must be specified for HttpAlbIntegration.

Network Load Balancer ​

The following code is a basic network load balancer private integration of HTTP API:

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

const vpc = new ec2.Vpc(this, 'VPC');
const lb = new elbv2.NetworkLoadBalancer(this, 'lb', { vpc });
const listener = lb.addListener('listener', { port: 80 });
listener.addTargets('target', {
  port: 80,
});

const httpEndpoint = new apigwv2.HttpApi(this, 'HttpProxyPrivateApi', {
  defaultIntegration: new HttpNlbIntegration('DefaultIntegration', listener),
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpNlbIntegration


vpc = ec2.Vpc(self, "VPC")
lb = elbv2.NetworkLoadBalancer(self, "lb", vpc=vpc)
listener = lb.add_listener("listener", port=80)
listener.add_targets("target",
    port=80
)

http_endpoint = apigwv2.HttpApi(self, "HttpProxyPrivateApi",
    default_integration=HttpNlbIntegration("DefaultIntegration", listener)
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpNlbIntegration;


Vpc vpc = new Vpc(this, "VPC");
NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "lb").vpc(vpc).build();
NetworkListener listener = lb.addListener("listener", BaseNetworkListenerProps.builder().port(80).build());
listener.addTargets("target", AddNetworkTargetsProps.builder()
        .port(80)
        .build());

HttpApi httpEndpoint = HttpApi.Builder.create(this, "HttpProxyPrivateApi")
        .defaultIntegration(new HttpNlbIntegration("DefaultIntegration", listener))
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;


var vpc = new Vpc(this, "VPC");
var lb = new NetworkLoadBalancer(this, "lb", new NetworkLoadBalancerProps { Vpc = vpc });
var listener = lb.AddListener("listener", new BaseNetworkListenerProps { Port = 80 });
listener.AddTargets("target", new AddNetworkTargetsProps {
    Port = 80
});

var httpEndpoint = new HttpApi(this, "HttpProxyPrivateApi", new HttpApiProps {
    DefaultIntegration = new HttpNlbIntegration("DefaultIntegration", listener)
});
go
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("VPC"))
lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("lb"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
})
listener := lb.AddListener(jsii.String("listener"), &BaseNetworkListenerProps{
	Port: jsii.Number(80),
})
listener.AddTargets(jsii.String("target"), &AddNetworkTargetsProps{
	Port: jsii.Number(80),
})

httpEndpoint := apigwv2.NewHttpApi(this, jsii.String("HttpProxyPrivateApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpNlbIntegration(jsii.String("DefaultIntegration"), listener),
})

When an imported load balancer is used, the vpc option must be specified for HttpNlbIntegration.

Cloud Map Service Discovery ​

The following code is a basic discovery service private integration of HTTP API:

ts
import * as servicediscovery from 'aws-cdk-lib/aws-servicediscovery';
import { HttpServiceDiscoveryIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

const vpc = new ec2.Vpc(this, 'VPC');
const vpcLink = new apigwv2.VpcLink(this, 'VpcLink', { vpc });
const namespace = new servicediscovery.PrivateDnsNamespace(this, 'Namespace', {
  name: 'boobar.com',
  vpc,
});
const service = namespace.createService('Service');

const httpEndpoint = new apigwv2.HttpApi(this, 'HttpProxyPrivateApi', {
  defaultIntegration: new HttpServiceDiscoveryIntegration('DefaultIntegration', service, {
    vpcLink,
  }),
});
python
import aws_cdk.aws_servicediscovery as servicediscovery
from aws_cdk.aws_apigatewayv2_integrations import HttpServiceDiscoveryIntegration


vpc = ec2.Vpc(self, "VPC")
vpc_link = apigwv2.VpcLink(self, "VpcLink", vpc=vpc)
namespace = servicediscovery.PrivateDnsNamespace(self, "Namespace",
    name="boobar.com",
    vpc=vpc
)
service = namespace.create_service("Service")

http_endpoint = apigwv2.HttpApi(self, "HttpProxyPrivateApi",
    default_integration=HttpServiceDiscoveryIntegration("DefaultIntegration", service,
        vpc_link=vpc_link
    )
)
java
import software.amazon.awscdk.services.servicediscovery.*;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpServiceDiscoveryIntegration;


Vpc vpc = new Vpc(this, "VPC");
VpcLink vpcLink = VpcLink.Builder.create(this, "VpcLink").vpc(vpc).build();
PrivateDnsNamespace namespace = PrivateDnsNamespace.Builder.create(this, "Namespace")
        .name("boobar.com")
        .vpc(vpc)
        .build();
Service service = namespace.createService("Service");

HttpApi httpEndpoint = HttpApi.Builder.create(this, "HttpProxyPrivateApi")
        .defaultIntegration(HttpServiceDiscoveryIntegration.Builder.create("DefaultIntegration", service)
                .vpcLink(vpcLink)
                .build())
        .build();
csharp
using Amazon.CDK.AWS.ServiceDiscovery;
using Amazon.CDK.AwsApigatewayv2Integrations;


var vpc = new Vpc(this, "VPC");
var vpcLink = new VpcLink(this, "VpcLink", new VpcLinkProps { Vpc = vpc });
var namespace = new PrivateDnsNamespace(this, "Namespace", new PrivateDnsNamespaceProps {
    Name = "boobar.com",
    Vpc = vpc
});
var service = namespace.CreateService("Service");

var httpEndpoint = new HttpApi(this, "HttpProxyPrivateApi", new HttpApiProps {
    DefaultIntegration = new HttpServiceDiscoveryIntegration("DefaultIntegration", service, new HttpServiceDiscoveryIntegrationProps {
        VpcLink = vpcLink
    })
});
go
import servicediscovery "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("VPC"))
vpcLink := apigwv2.NewVpcLink(this, jsii.String("VpcLink"), &VpcLinkProps{
	Vpc: Vpc,
})
namespace := servicediscovery.NewPrivateDnsNamespace(this, jsii.String("Namespace"), &PrivateDnsNamespaceProps{
	Name: jsii.String("boobar.com"),
	Vpc: Vpc,
})
service := namespace.CreateService(jsii.String("Service"))

httpEndpoint := apigwv2.NewHttpApi(this, jsii.String("HttpProxyPrivateApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpServiceDiscoveryIntegration(jsii.String("DefaultIntegration"), service, &HttpServiceDiscoveryIntegrationProps{
		VpcLink: *VpcLink,
	}),
})

Request Parameters ​

Request parameter mapping allows API requests from clients to be modified before they reach backend integrations. Parameter mapping can be used to specify modifications to request parameters. See Transforming API requests and responses.

The following example creates a new header - header2 - as a copy of header1 and removes header1.

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

declare const lb: elbv2.ApplicationLoadBalancer;
const listener = lb.addListener('listener', { port: 80 });
listener.addTargets('target', {
  port: 80,
});

const httpEndpoint = new apigwv2.HttpApi(this, 'HttpProxyPrivateApi', {
  defaultIntegration: new HttpAlbIntegration('DefaultIntegration', listener, {
    parameterMapping: new apigwv2.ParameterMapping()
      .appendHeader('header2', apigwv2.MappingValue.requestHeader('header1'))
      .removeHeader('header1'),
  }),
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpAlbIntegration

# lb: elbv2.ApplicationLoadBalancer

listener = lb.add_listener("listener", port=80)
listener.add_targets("target",
    port=80
)

http_endpoint = apigwv2.HttpApi(self, "HttpProxyPrivateApi",
    default_integration=HttpAlbIntegration("DefaultIntegration", listener,
        parameter_mapping=apigwv2.ParameterMapping().append_header("header2", apigwv2.MappingValue.request_header("header1")).remove_header("header1")
    )
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpAlbIntegration;

ApplicationLoadBalancer lb;

ApplicationListener listener = lb.addListener("listener", BaseApplicationListenerProps.builder().port(80).build());
listener.addTargets("target", AddApplicationTargetsProps.builder()
        .port(80)
        .build());

HttpApi httpEndpoint = HttpApi.Builder.create(this, "HttpProxyPrivateApi")
        .defaultIntegration(HttpAlbIntegration.Builder.create("DefaultIntegration", listener)
                .parameterMapping(new ParameterMapping().appendHeader("header2", MappingValue.requestHeader("header1")).removeHeader("header1"))
                .build())
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

ApplicationLoadBalancer lb;

var listener = lb.AddListener("listener", new BaseApplicationListenerProps { Port = 80 });
listener.AddTargets("target", new AddApplicationTargetsProps {
    Port = 80
});

var httpEndpoint = new HttpApi(this, "HttpProxyPrivateApi", new HttpApiProps {
    DefaultIntegration = new HttpAlbIntegration("DefaultIntegration", listener, new HttpAlbIntegrationProps {
        ParameterMapping = new ParameterMapping().AppendHeader("header2", MappingValue.RequestHeader("header1")).RemoveHeader("header1")
    })
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var lb ApplicationLoadBalancer

listener := lb.AddListener(jsii.String("listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
listener.AddTargets(jsii.String("target"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
})

httpEndpoint := apigwv2.NewHttpApi(this, jsii.String("HttpProxyPrivateApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpAlbIntegration(jsii.String("DefaultIntegration"), listener, &HttpAlbIntegrationProps{
		ParameterMapping: apigwv2.NewParameterMapping().AppendHeader(jsii.String("header2"), apigwv2.MappingValue_RequestHeader(jsii.String("header1"))).RemoveHeader(jsii.String("header1")),
	}),
})

To add mapping keys and values not yet supported by the CDK, use the custom() method:

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

declare const lb: elbv2.ApplicationLoadBalancer;
const listener = lb.addListener('listener', { port: 80 });
listener.addTargets('target', {
  port: 80,
});

const httpEndpoint = new apigwv2.HttpApi(this, 'HttpProxyPrivateApi', {
  defaultIntegration: new HttpAlbIntegration('DefaultIntegration', listener, {
    parameterMapping: new apigwv2.ParameterMapping().custom('myKey', 'myValue'),
  }),
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpAlbIntegration

# lb: elbv2.ApplicationLoadBalancer

listener = lb.add_listener("listener", port=80)
listener.add_targets("target",
    port=80
)

http_endpoint = apigwv2.HttpApi(self, "HttpProxyPrivateApi",
    default_integration=HttpAlbIntegration("DefaultIntegration", listener,
        parameter_mapping=apigwv2.ParameterMapping().custom("myKey", "myValue")
    )
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpAlbIntegration;

ApplicationLoadBalancer lb;

ApplicationListener listener = lb.addListener("listener", BaseApplicationListenerProps.builder().port(80).build());
listener.addTargets("target", AddApplicationTargetsProps.builder()
        .port(80)
        .build());

HttpApi httpEndpoint = HttpApi.Builder.create(this, "HttpProxyPrivateApi")
        .defaultIntegration(HttpAlbIntegration.Builder.create("DefaultIntegration", listener)
                .parameterMapping(new ParameterMapping().custom("myKey", "myValue"))
                .build())
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

ApplicationLoadBalancer lb;

var listener = lb.AddListener("listener", new BaseApplicationListenerProps { Port = 80 });
listener.AddTargets("target", new AddApplicationTargetsProps {
    Port = 80
});

var httpEndpoint = new HttpApi(this, "HttpProxyPrivateApi", new HttpApiProps {
    DefaultIntegration = new HttpAlbIntegration("DefaultIntegration", listener, new HttpAlbIntegrationProps {
        ParameterMapping = new ParameterMapping().Custom("myKey", "myValue")
    })
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var lb ApplicationLoadBalancer

listener := lb.AddListener(jsii.String("listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
listener.AddTargets(jsii.String("target"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
})

httpEndpoint := apigwv2.NewHttpApi(this, jsii.String("HttpProxyPrivateApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpAlbIntegration(jsii.String("DefaultIntegration"), listener, &HttpAlbIntegrationProps{
		ParameterMapping: apigwv2.NewParameterMapping().Custom(jsii.String("myKey"), jsii.String("myValue")),
	}),
})

WebSocket APIs ​

WebSocket integrations connect a route to backend resources. The following integrations are supported in the CDK.

Lambda WebSocket Integration ​

Lambda integrations enable integrating a WebSocket API route with a Lambda function. When a client connects/disconnects or sends a message specific to a route, the API Gateway service forwards the request to the Lambda function

The API Gateway service will invoke the Lambda function with an event payload of a specific format.

The following code configures a sendMessage route with a Lambda integration

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

const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
new apigwv2.WebSocketStage(this, 'mystage', {
  webSocketApi,
  stageName: 'dev',
  autoDeploy: true,
});

declare const messageHandler: lambda.Function;
webSocketApi.addRoute('sendMessage', {
  integration: new WebSocketLambdaIntegration('SendMessageIntegration', messageHandler),
});
python
from aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration

# message_handler: lambda.Function


web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
apigwv2.WebSocketStage(self, "mystage",
    web_socket_api=web_socket_api,
    stage_name="dev",
    auto_deploy=True
)
web_socket_api.add_route("sendMessage",
    integration=WebSocketLambdaIntegration("SendMessageIntegration", message_handler)
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;

Function messageHandler;


WebSocketApi webSocketApi = new WebSocketApi(this, "mywsapi");
WebSocketStage.Builder.create(this, "mystage")
        .webSocketApi(webSocketApi)
        .stageName("dev")
        .autoDeploy(true)
        .build();
webSocketApi.addRoute("sendMessage", WebSocketRouteOptions.builder()
        .integration(new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler))
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function messageHandler;


var webSocketApi = new WebSocketApi(this, "mywsapi");
new WebSocketStage(this, "mystage", new WebSocketStageProps {
    WebSocketApi = webSocketApi,
    StageName = "dev",
    AutoDeploy = true
});
webSocketApi.AddRoute("sendMessage", new WebSocketRouteOptions {
    Integration = new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler)
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var messageHandler Function


webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
apigwv2.NewWebSocketStage(this, jsii.String("mystage"), &WebSocketStageProps{
	WebSocketApi: WebSocketApi,
	StageName: jsii.String("dev"),
	AutoDeploy: jsii.Boolean(true),
})
webSocketApi.AddRoute(jsii.String("sendMessage"), &WebSocketRouteOptions{
	Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("SendMessageIntegration"), messageHandler),
})

AWS WebSocket Integration ​

AWS type integrations enable integrating with any supported AWS service. This is only supported for WebSocket APIs. When a client connects/disconnects or sends a message specific to a route, the API Gateway service forwards the request to the specified AWS service.

The following code configures a $connect route with a AWS integration that integrates with a dynamodb table. On websocket api connect, it will write new entry to the dynamodb table.

ts
import { WebSocketAwsIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as iam from 'aws-cdk-lib/aws-iam';

const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
new apigwv2.WebSocketStage(this, 'mystage', {
  webSocketApi,
  stageName: 'dev',
  autoDeploy: true,
});

declare const apiRole: iam.Role;
declare const table: dynamodb.Table;
webSocketApi.addRoute('$connect', {
  integration: new WebSocketAwsIntegration('DynamodbPutItem', {
    integrationUri: `arn:aws:apigateway:${this.region}:dynamodb:action/PutItem`,
    integrationMethod: apigwv2.HttpMethod.POST,
    credentialsRole: apiRole,
    requestTemplates: {
      'application/json': JSON.stringify({
        TableName: table.tableName,
        Item: {
          id: {
            S: '$context.requestId',
          },
        },
      }),
    },
  }),
});
python
from aws_cdk.aws_apigatewayv2_integrations import WebSocketAwsIntegration
import aws_cdk.aws_dynamodb as dynamodb
import aws_cdk.aws_iam as iam

# api_role: iam.Role
# table: dynamodb.Table


web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
apigwv2.WebSocketStage(self, "mystage",
    web_socket_api=web_socket_api,
    stage_name="dev",
    auto_deploy=True
)
web_socket_api.add_route("$connect",
    integration=WebSocketAwsIntegration("DynamodbPutItem",
        integration_uri=f"arn:aws:apigateway:{this.region}:dynamodb:action/PutItem",
        integration_method=apigwv2.HttpMethod.POST,
        credentials_role=api_role,
        request_templates={
            "application/json": JSON.stringify({
                "TableName": table.table_name,
                "Item": {
                    "id": {
                        "S": "$context.requestId"
                    }
                }
            })
        }
    )
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketAwsIntegration;
import software.amazon.awscdk.services.dynamodb.*;
import software.amazon.awscdk.services.iam.*;

Role apiRole;
Table table;


WebSocketApi webSocketApi = new WebSocketApi(this, "mywsapi");
WebSocketStage.Builder.create(this, "mystage")
        .webSocketApi(webSocketApi)
        .stageName("dev")
        .autoDeploy(true)
        .build();
webSocketApi.addRoute("$connect", WebSocketRouteOptions.builder()
        .integration(WebSocketAwsIntegration.Builder.create("DynamodbPutItem")
                .integrationUri(String.format("arn:aws:apigateway:%s:dynamodb:action/PutItem", this.region))
                .integrationMethod(HttpMethod.POST)
                .credentialsRole(apiRole)
                .requestTemplates(Map.of(
                        "application/json", JSON.stringify(Map.of(
                                "TableName", table.getTableName(),
                                "Item", Map.of(
                                        "id", Map.of(
                                                "S", "$context.requestId"))))))
                .build())
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.IAM;

Role apiRole;
Table table;


var webSocketApi = new WebSocketApi(this, "mywsapi");
new WebSocketStage(this, "mystage", new WebSocketStageProps {
    WebSocketApi = webSocketApi,
    StageName = "dev",
    AutoDeploy = true
});
webSocketApi.AddRoute("$connect", new WebSocketRouteOptions {
    Integration = new WebSocketAwsIntegration("DynamodbPutItem", new WebSocketAwsIntegrationProps {
        IntegrationUri = $"arn:aws:apigateway:{this.region}:dynamodb:action/PutItem",
        IntegrationMethod = HttpMethod.POST,
        CredentialsRole = apiRole,
        RequestTemplates = new Dictionary<string, string> {
            { "application/json", JSON.Stringify(new Dictionary<string, object> {
                { "TableName", table.TableName },
                { "Item", new Struct {
                    Id = new Struct {
                        S = "$context.requestId"
                    }
                } }
            }) }
        }
    })
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import dynamodb "github.com/aws/aws-cdk-go/awscdk"
import iam "github.com/aws/aws-cdk-go/awscdk"

var apiRole Role
var table Table


webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
apigwv2.NewWebSocketStage(this, jsii.String("mystage"), &WebSocketStageProps{
	WebSocketApi: WebSocketApi,
	StageName: jsii.String("dev"),
	AutoDeploy: jsii.Boolean(true),
})
webSocketApi.AddRoute(jsii.String("$connect"), &WebSocketRouteOptions{
	Integration: awscdk.NewWebSocketAwsIntegration(jsii.String("DynamodbPutItem"), &WebSocketAwsIntegrationProps{
		IntegrationUri: fmt.Sprintf("arn:aws:apigateway:%v:dynamodb:action/PutItem", this.Region),
		IntegrationMethod: apigwv2.HttpMethod_POST,
		CredentialsRole: apiRole,
		RequestTemplates: map[string]*string{
			"application/json": JSON.stringify(map[string]interface{}{
				"TableName": table.tableName,
				"Item": map[string]map[string]*string{
					"id": map[string]*string{
						"S": jsii.String("$context.requestId"),
					},
				},
			}),
		},
	}),
})

You can also set additional properties to change the behavior of your integration, such as contentHandling. See Working with binary media types for WebSocket APIs.

Mock WebSocket Integration ​

API Gateway also allows the creation of mock integrations, allowing you to generate API responses without the need for an integration backend. These responses can range in complexity from a static message to a templated response with parameters extracted from the input request or the integration's context. See Set up data mapping for WebSocket APIs in API Gateway and WebSocket API mapping template reference for API Gateway for more information.

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

const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
new apigwv2.WebSocketStage(this, 'mystage', {
  webSocketApi,
  stageName: 'dev',
  autoDeploy: true,
});


webSocketApi.addRoute('sendMessage', {
  integration: new WebSocketMockIntegration('DefaultIntegration', {
    requestTemplates: { 'application/json': JSON.stringify({ statusCode: 200 }) },
    templateSelectionExpression: '\\$default',
  }),
  returnResponse: true,
});
python
from aws_cdk.aws_apigatewayv2_integrations import WebSocketMockIntegration


web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
apigwv2.WebSocketStage(self, "mystage",
    web_socket_api=web_socket_api,
    stage_name="dev",
    auto_deploy=True
)

web_socket_api.add_route("sendMessage",
    integration=WebSocketMockIntegration("DefaultIntegration",
        request_templates={"application/json": JSON.stringify({"status_code": 200})},
        template_selection_expression="\\$default"
    ),
    return_response=True
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketMockIntegration;


WebSocketApi webSocketApi = new WebSocketApi(this, "mywsapi");
WebSocketStage.Builder.create(this, "mystage")
        .webSocketApi(webSocketApi)
        .stageName("dev")
        .autoDeploy(true)
        .build();

webSocketApi.addRoute("sendMessage", WebSocketRouteOptions.builder()
        .integration(WebSocketMockIntegration.Builder.create("DefaultIntegration")
                .requestTemplates(Map.of("application/json", JSON.stringify(Map.of("statusCode", 200))))
                .templateSelectionExpression("\\$default")
                .build())
        .returnResponse(true)
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;


var webSocketApi = new WebSocketApi(this, "mywsapi");
new WebSocketStage(this, "mystage", new WebSocketStageProps {
    WebSocketApi = webSocketApi,
    StageName = "dev",
    AutoDeploy = true
});

webSocketApi.AddRoute("sendMessage", new WebSocketRouteOptions {
    Integration = new WebSocketMockIntegration("DefaultIntegration", new WebSocketMockIntegrationProps {
        RequestTemplates = new Dictionary<string, string> { { "application/json", JSON.Stringify(new Dictionary<string, int> { { "statusCode", 200 } }) } },
        TemplateSelectionExpression = "\\$default"
    }),
    ReturnResponse = true
});
go
import "github.com/aws/aws-cdk-go/awscdk"


webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
apigwv2.NewWebSocketStage(this, jsii.String("mystage"), &WebSocketStageProps{
	WebSocketApi: WebSocketApi,
	StageName: jsii.String("dev"),
	AutoDeploy: jsii.Boolean(true),
})

webSocketApi.AddRoute(jsii.String("sendMessage"), &WebSocketRouteOptions{
	Integration: awscdk.NewWebSocketMockIntegration(jsii.String("DefaultIntegration"), &WebSocketMockIntegrationProps{
		RequestTemplates: map[string]*string{
			"application/json": JSON.stringify(map[string]*f64{
				"statusCode": jsii.Number(200),
			}),
		},
		TemplateSelectionExpression: jsii.String("\\$default"),
	}),
	ReturnResponse: jsii.Boolean(true),
})

Import Issues ​

jsiirc.json file is missing during the stablization process of this module, which caused import issues for DotNet and Java users who attempt to use this module. Unfortunately, to guarantee backward compatibility, we cannot simply correct the namespace for DotNet or package for Java. The following outlines the workaround.

DotNet Namespace ​

Instead of the conventional namespace Amazon.CDK.AWS.Apigatewayv2.Integrations, you would need to use the following namespace:

cs
using Amazon.CDK.AwsApigatewayv2Integrations;

Java Package ​

Instead of conventional package import software.amazon.awscdk.services.apigatewayv2_integrations.*, you would need to use the following package:

java
import software.amazon.awscdk.aws_apigatewayv2_integrations.*;

// If you want to import a specific construct
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketAwsIntegration;

Types ​

NameKindSummary
HttpAlbIntegrationClassThe Application Load Balancer integration resource for HTTP API.
HttpAlbIntegrationPropsStructProperties to initialize HttpAlbIntegration.
HttpEventBridgeIntegrationClassThe EventBridge PutEvents integration resource for HTTP API.
HttpEventBridgeIntegrationPropsStructProperties to initialize HttpEventBridgeIntegration.
HttpLambdaIntegrationClassThe Lambda Proxy integration resource for HTTP API.
HttpLambdaIntegrationPropsStructLambda Proxy integration properties.
HttpNlbIntegrationClassThe Network Load Balancer integration resource for HTTP API.
HttpNlbIntegrationPropsStructProperties to initialize HttpNlbIntegration.
HttpPrivateIntegrationOptionsStructBase options for private integration.
HttpServiceDiscoveryIntegrationClassThe Service Discovery integration resource for HTTP API.
HttpServiceDiscoveryIntegrationPropsStructProperties to initialize HttpServiceDiscoveryIntegration.
HttpSqsIntegrationClassThe Sqs integration resource for HTTP API.
HttpSqsIntegrationPropsStructProperties to initialize HttpSqsIntegration.
HttpStepFunctionsIntegrationClassThe StepFunctions integration resource for HTTP API.
HttpStepFunctionsIntegrationPropsStructProperties to initialize HttpStepFunctionsIntegration.
HttpUrlIntegrationClassThe HTTP Proxy integration resource for HTTP API.
HttpUrlIntegrationPropsStructProperties to initialize a new HttpProxyIntegration.
WebSocketAwsIntegrationClassAWS WebSocket AWS Type Integration.
WebSocketAwsIntegrationPropsStructProps for AWS type integration for a WebSocket Api.
WebSocketLambdaIntegrationClassLambda WebSocket Integration.
WebSocketLambdaIntegrationPropsStructProps for Lambda type integration for a WebSocket Api.
WebSocketMockIntegrationClassMock WebSocket Integration.
WebSocketMockIntegrationPropsStructProps for Mock type integration for a WebSocket Api.