Update the mapping template of OPTIONS method using AWS CDK

1

Hello Team

I am using AWS CDK to deploy a REST API with Lambda integration. Here is the sample code I am using to create API Gateway resource:

import { LambdaIntegration, RestApi} from 'aws-cdk-lib/aws-apigateway';
import { AssetCode, Function, Runtime } from 'aws-cdk-lib/aws-lambda';
    // Lambda Definition
    const SampleFunction = new Function(this, 'api-sample', {
      code: new AssetCode(join(__dirname,'/src')),
      handler: 'lambda_function.handler',
      runtime: Runtime.PYTHON_3_9,
      environment: {}
    });    

    // Rest API Definition
    const api = new RestApi(this, 'web-api', {
      description: 'Web UI Rest API',
      deployOptions: {
        stageName: 'v1',
      },
      //Enable Default CORS (for now)
      defaultCorsPreflightOptions: {
        allowHeaders: [
          'Content-Type',
          'X-Amz-Date',
          'Authorization',
          'X-Api-Key',
        ],
        allowMethods: ['OPTIONS', 'GET', 'PUT'],
        allowCredentials: true,
        allowOrigins: ['*'],
      }
    });

    const contents = api.root.addResource('content');

    const contentResource = contents.addResource('{content}');

    contentResource.addMethod('GET', new LambdaIntegration(SampleFunction,{proxy: true,})
       });

It deploys a "GET" API in API Gateway that returns the response by executing the lambda function in the backend. However, there is one configuration of the "OPTIONS" method that I am not able to update using AWS CDK.

I want to update the "mapping template" in the OPTIONS integration request to the recommended (second option) setting. By default it is set to the first option i.e., When no template matches the request Content-Type header but I want to update the same to the recommended setting i.e., When there are no templates defined (recommended)

Here is a screenshot for reference: Enter image description here

Is there a way to do this through CDK code? Have you faced a similar problem?

  1. Stackoverflow- cdk-add-mapping-templates-to-lambdaintegration
  2. AWS CDK Documentation

I have referred these and updated my code accordingly but none of these help me update OPTIONS configuration through CDK.

1 Answer
0

Based off of this reference to the CDK interface MethodOptions, I believe you could update the mapping template of the OPTIONS by using the addMethod function on the resource and specifying the OPTIONS method. In the integration parameter of this function, you can specify the requestTemplates property to define the mapping templates for the OPTIONS method. Here's an example:

contentResource.addMethod('OPTIONS', new apigateway.MockIntegration({
  integrationResponses: [{
    statusCode: '200',
    responseParameters: {
      'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
      'method.response.header.Access-Control-Allow-Origin': "'*'",
      'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT'"
    }
  }],
  passthroughBehavior: apigateway.PassthroughBehavior.NEVER,
  requestTemplates: {
    "application/json": "{\"statusCode\": 200}"
  }
}), {
  methodResponses: [{
    statusCode: '200',
    responseParameters: {
      'method.response.header.Access-Control-Allow-Headers': true,
      'method.response.header.Access-Control-Allow-Methods': true,
      'method.response.header.Access-Control-Allow-Origin': true,
    }
  }]
});

Hope this helps!

-Zac

profile picture
Zac Dan
answered 10 months ago
  • Hello Zac

    Thanks for your response. I have tried this approach before, however when I build the app using npm run build and then run cdk synth, this throws error Error: There is already a Construct with name 'OPTIONS' in Resource [{content}]. It seems there is already an OPTIONS method defined by default.

    Do you think removing the defaultCorsPreflightOptions in RestApi definition and then adding this section addMethod('OPTIONS',... would work?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions