user898082
user898082

Reputation:

CDK add mapping templates to LambdaIntegration

I have a Lambda function which can be accessed by api gateway.

How can I make CDK to add an Mapping template like in this Screenshot:

enter image description here

I tried multiple variants of this:

....

const restApi = new apigateway.LambdaRestApi(this, "dyndns-api", {
  handler: dyndnsLambda,
  proxy: false,
  domainName: {
    domainName: siteDomain,
    certificate: certificate,
    endpointType: apigateway.EndpointType.REGIONAL
  }
});

const methodResponse: apigateway.MethodResponse = {
  statusCode: "200", 
  responseModels: {"application/json": apigateway.Model.EMPTY_MODEL}
}

const requestTemplate = {
  "execution_mode" : "$input.params('mode')",
  "source_ip" : "$context.identity.sourceIp",
  "set_hostname" : "$input.params('hostname')",
  "validation_hash" : "$input.params('hash')"
}

const dnydnsIntegration = new apigateway.LambdaIntegration(dyndnsLambda, {
  allowTestInvoke: true,
  passthroughBehavior: apigateway.PassthroughBehavior.WHEN_NO_TEMPLATES,
  requestTemplates: { "application/json": JSON.stringify(requestTemplate) },
});

restApi.root.addMethod("GET", dnydnsIntegration, {
  methodResponses: [methodResponse]
});

But with not effect, it does not seem to arrive in the console, as I would expect.

Upvotes: 2

Views: 4612

Answers (1)

user898082
user898082

Reputation:

solved it like this: needed to add proxy setting to restApi, so the requestTemplate gets accepted. also needed integrationResponse.

const restApi = new apigateway.LambdaRestApi(this, "dyndns-api", {
  handler: dyndnsLambda,
  proxy: false,
  domainName: {
    securityPolicy: apigateway.SecurityPolicy.TLS_1_2,
    domainName: siteDomain,
    certificate: certificate,
    endpointType: apigateway.EndpointType.REGIONAL
  }
});

const methodResponse: apigateway.MethodResponse = {
  statusCode: "200", 
  responseModels: {"application/json": apigateway.Model.EMPTY_MODEL}
}

const integrationResponse: apigateway.IntegrationResponse = {
  statusCode: "200",
  contentHandling: apigateway.ContentHandling.CONVERT_TO_TEXT
}

const requestTemplate = {
  "execution_mode" : "$input.params('mode')",
  "source_ip" : "$context.identity.sourceIp",
  "set_hostname" : "$input.params('hostname')",
  "validation_hash" : "$input.params('hash')"
}

const dnydnsIntegration = new apigateway.LambdaIntegration(dyndnsLambda, {
  allowTestInvoke: true,
  proxy: false,
  integrationResponses: [integrationResponse],
  passthroughBehavior: apigateway.PassthroughBehavior.WHEN_NO_TEMPLATES,
  requestTemplates: { "application/json": JSON.stringify(requestTemplate) },
});

restApi.root.addMethod("GET", dnydnsIntegration, {
  methodResponses: [methodResponse]
});

Upvotes: 5

Related Questions