4

I am creating proxy API gateway to non-public S3 bucket using CDK. The S3 bucket contains html, javascript, and css files.

I created an api using CDK like this:

const api = new apigw.RestApi(this, 'Test-Web')

api.root
  .addResource('{file}')
  .addMethod('GET', new apigw.AwsIntegration({
    service: 's3',
    integrationHttpMethod: 'GET',
    path: `${bucket.bucketName}/{file}`,
    options: {
      credentialsRole: role,
      requestParameters: {
        'integration.request.path.file': 'method.request.path.file'
      },
      integrationResponses: [{
        statusCode: '200'
      }]
    }
  }), {
    requestParameters: {
      'method.request.path.file': true
    },
    methodResponses: [{
      statusCode: '200'
    }]
  })

It works fine, but has a problem. The content type of the response is always set to application/json. I could see that the content type of integration responses (responses from S3) varies from text/html to text/css, application/javascript depending on the file.

How can I set this API to return correct content type on each file by passing the same content type header value of integration response to method response? Best if I can pass the content-type header from S3 as it already returns correctly.

1 Answer 1

7

CDK documentation is not great. I managed to find a solution: I had to add responseParameters in integrationResponses to set Content-Type header from S3 to API gateway response. Please see below, especially the line marked with <<<--.

api.root
  .addResource('{file}')
  .addMethod(
    'GET',
    new apigw.AwsIntegration({
      service: 's3',
      integrationHttpMethod: 'GET',
      path: `${bucket.bucketName}/{file}`,
      options: {
        credentialsRole: role,
        requestParameters: {
          'integration.request.path.file': 'method.request.path.file'
        },
        integrationResponses: [{
          statusCode: '200',
          selectionPattern: '2..',
          responseParameters: {
            'method.response.header.Content-Type': 'integration.response.header.Content-Type' // <<<--
          },
        }, {
          statusCode: '403',
          selectionPattern: '4..'
        }]
      }
    }), {
      requestParameters: {
        'method.request.path.file': true
      },
      methodResponses: [{
        statusCode: '200',
        responseParameters: {
          'method.response.header.Content-Type': true // <<<-- 
        }
      }, {
        statusCode: '404'
      }]
    })
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I used hard-coded "'application/json'" instead of "integration.response.header.Content-Type"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.