6

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.

1
  • The AWS documentation is poor on this. The grammar doesn't help either. An example would be so useful. Commented Apr 30, 2018 at 13:57

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Goodness you're a hero for this.
7

you need to add a method "options" to your api gateway and using a proxy lambda... return

result.headers = { "Access-Control-Allow-Origin": "domain.com" }

so when the browser will first call options to your server it will return the CORS headers.

the thing is that, by default your lambda method will be called for "any" method, so you need to change the default one to get,post or whatever you need

note: you could also use the same method, like any or options,get,post and if it is a options call, only return status 200 and the cors header. it depends if you are using or not an auth method for get,post,etc

there is an option in Lambda console "Enable CORS" if you are just using lambda with nothing strange

4 Comments

"enable CORS" is in: select your lambda method, and in the actions button sub options
thanks for the response. sadly it is not possible under lambda proxy integration configuration.
are you sure? I'm using it, with proxy integration. are you using any specific authentication/auth method? or is a public lambda method? if it is passing by any auth, you need to separate options method so it doesn't need the auth to be called
yes. It is so documented and verified in my experiment. I have ended up the solution to add the header into lambda function code. "Enable CORS" only activate the OPTION method with a MOCK UP backend, but if one has a GET method with lambda backend and proxy integration ticked, it is not yet supported.
0

If you use Mangum and FastAPI you can override the headers of the response by defining a custom class:

from fastapi import FastAPI

class AWSMangum(Mangum):
    """
    It overwrites the __call__ method of the Mangum class to add CORS headers to the response.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        response = super().__call__(*args, **kwargs)
        logger.info(response)
        response["headers"]["Access-Control-Allow-Origin"] = "*"

        return response


app = FastAPI(...)

handler = AWSMangum(app)

Comments

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.