Skip to content

Instantly share code, notes, and snippets.

@SalvoCozzubo
Last active July 23, 2022 15:46
Show Gist options
  • Save SalvoCozzubo/b0247634def27424704985335188344b to your computer and use it in GitHub Desktop.
Save SalvoCozzubo/b0247634def27424704985335188344b to your computer and use it in GitHub Desktop.
AWS CDK api gateway direct integration with AWS SQS
import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as IAM from 'aws-cdk-lib/aws-iam';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as ApiGW from 'aws-cdk-lib/aws-apigateway';
export class AwsSqsDirectIntegrationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// role
const integrationRole = new IAM.Role(this, 'integration-role', {
assumedBy: new IAM.ServicePrincipal('apigateway.amazonaws.com'),
});
// queue
const queue = new sqs.Queue(this, 'queue', {
encryption: sqs.QueueEncryption.KMS_MANAGED,
});
// grant sqs:SendMessage* to Api Gateway Role
queue.grantSendMessages(integrationRole);
// Api Gateway Direct Integration
const sendMessageIntegration = new ApiGW.AwsIntegration({
service: 'sqs',
path: `${process.env.CDK_DEFAULT_ACCOUNT}/${queue.queueName}`,
integrationHttpMethod: 'POST',
options: {
credentialsRole: integrationRole,
requestParameters: {
'integration.request.header.Content-Type': `'application/x-www-form-urlencoded'`,
},
requestTemplates: {
'application/json': 'Action=SendMessage&MessageBody=$input.body',
},
integrationResponses: [
{
statusCode: '200',
},
{
statusCode: '400',
},
{
statusCode: '500',
}
]
},
});
// Rest Api
const api = new ApiGW.RestApi(this, 'api', {});
// post method
api.root.addMethod('POST', sendMessageIntegration, {
methodResponses: [
{
statusCode: '400',
},
{
statusCode: '200',
},
{
statusCode: '500',
}
]
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment