Search code examples
amazon-web-servicesaws-cdkaws-http-api

Create an aws integration in Http API using AWS CDK


I'm using AWS CDK to build a cloudformation stack with HttpApi in it. HttpApi will have an integration with SQS.

I have the following snippet:

import * as ApiGW2 from "@aws-cdk/aws-apigatewayv2-alpha";

const httpApi = new ApiGW2.HttpApi(this, "http-api", {
  apiName: "dev-api"
});

const int = new ApiGW2.HttpIntegration(this, "int1", {
  httpApi,
  integrationType: ApiGW2.HttpIntegrationType.AWS_PROXY,
  integrationSubtype: ApiGW2.HttpIntegrationSubtype.SQS_SEND_MESSAGE,
  payloadFormatVersion: ApiGW2.PayloadFormatVersion.VERSION_1_0,
})

But I get an error when running this code:

UPDATE_ROLLBACK_COMPLETE: Role ARN must be specified for AWS integration configuration with Subtype: SQS-SendMessage


Solution

  • The API Gateway service needs permission to send messages to your queue. Create a role assumable by the API Gateway service. Grant the role send permissions on your queue. Pass the role to the integration in the credentials prop:

    const sqsRole = new iam.Role(this, "Role", {
      assumedBy: new iam.ServicePrincipal("apigateway.amazonaws.com"),
    });
    
    myQueue.grantSendMessages(sqsRole);
    
    const credentials = ApiGW2.IntegrationCredentials.fromRole(sqsRole);
    
    const int = new ApiGW2.HttpIntegration(this, "int1", {
      httpApi,
      integrationType: ApiGW2.HttpIntegrationType.AWS_PROXY,
      integrationSubtype: ApiGW2.HttpIntegrationSubtype.SQS_SEND_MESSAGE,
      payloadFormatVersion: ApiGW2.PayloadFormatVersion.VERSION_1_0,
      credentials, // <-- connects the role to the integration
    })