I want to use AWS CDK to define an API Gateway and a lambda that the APIG will proxy to.
The OpenAPI spec supports a x-amazon-apigateway-integration
custom extension to the Swagger spec (detailed here), for which an invocation URL of the lambda is required. If the lambda is defined in the same stack as the API, I don't see how to provide this in the OpenAPI spec. The best I can think of would be to define one stack with the lambda in, then get the output from this and run sed
to do a find-and-replace in the OpenAPI spec to insert the uri, then create a second stack with this modified OpenAPI spec.
Example:
/items:
post:
x-amazon-apigateway-integration:
uri: "arn:aws:apigateway:eu-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-2:123456789012:function:MyStack-SingletonLambda4677ac3018fa48679f6-B1OYQ50UIVWJ/invocations"
passthroughBehavior: "when_no_match"
httpMethod: "POST"
type: "aws_proxy"
Q1. This seems like a chicken-and-egg problem, is the above the only way to do this?
I tried to use the defaultIntegration
property of the SpecRestApi CDK construct. The documentation states:
An integration to use as a default for all methods created within this API unless an integration is specified.
This seems like a should be able to define a default integration using a lambda defined in the CDK spec and therefore have all methods use this integration, without needing to know the uri of the lambda in advance.
Thus I tried this:
SingletonFunction myLambda = ...
SpecRestApi openapiRestApi = SpecRestApi.Builder.create(this, "MyApi")
.restApiName("MyApi")
.apiDefinition(ApiDefinition.fromAsset("openapi.yaml"))
.defaultIntegration(LambdaIntegration.Builder.create(myLambda)
.proxy(false)
.build())
.deploy(true)
.build();
The OpenAPI spec defined in openapi.yaml
does not include a x-amazon-apigateway-integration
stanza; it just has a single GET method defined within a standard OpenApi 3 specification.
However, when I try to deploy this, I get an error:
No integration defined for method (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException; Request ID: 56113150-1460-4ed2-93b9-a12618864582)
This seems like a bug, so I filed one here.
Q2. How do I define an API Gateway and Lambda using CDK and wire the two together via an OpenAPI spec?