Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CORS header to AWS API Gateway response with lambda proxy integration activate

I use lambda as backend for AWS API Gateway with lambda proxy integration and want to add CORS into response header.

According to documentation:

http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

However, you must rely on the back end to return the Access-Control-Allow-Origin headers because the integration response is disabled for the proxy integration.

How can I program it in my lambda function with Python.

like image 253
Hello lad Avatar asked May 03 '17 10:05

Hello lad


1 Answers

To create OPTIONS method you can enable it from the Gateway

  1. Navigate to your Gateaway, Select Resources from left side
  2. Select endpoint, on top there will a button "Action", there you will need to select "Enable CORS", save the settings.
  3. Deploy the Gateway.

It will create a method OPTIONS on the resource(endpoint)

for GET/POST other HTTP Verbs you will need to manage it from your code, in case of python

return {
    'statusCode': "200",
    'body': json.dumps({"test" : "123"}),
    'headers': {
        "Content-Type" : "application/json",
        "Access-Control-Allow-Origin" : "*",
        "Allow" : "GET, OPTIONS, POST",
        "Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
        "Access-Control-Allow-Headers" : "*"
    }
}

for other unhandled cases like IntegrationTimeout (504) or Error in your code (502), you can configure default response headers at API Gateway Level. refer Default Response Headers: AWS API Gateway w/ Proxy Integration

like image 117
Fahad Ali Shaikh Avatar answered Nov 15 '22 08:11

Fahad Ali Shaikh