'Specify content-type in API Gateway method response using CDK
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.
Solution 1:[1]
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'
}]
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ntalbs |