CORS, API Gateway and Python Lambda

Where to look and what to look for

Short version:
Don’t forget to return the following HTML headers in your Lambda function:

'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'

Longer version:

As background, I’m currently building a Chrome extension that based on data on the web screen pulls data out of a DynamoDB table via a Lambda function.

I got the data into the database, see my story here for more on that:

I got the Lambda function up and running for retrieving data from DynamoDB, tested it through the Lambda service console, and created the API Gateway REST API. AWS has some pretty good documentation on how to do that: Create a REST API with Lambda integrations in Amazon API Gateway. I’m using the Lambda Proxy integration option.

I tested it in the API Gateway service console. Again, everything was working. Great!

I generated the SDK (Generate the JavaScript SDK of an API), saved it in S3 with a read-only bucket policy, and wrote the code in my javascript to run it (Use a JavaScript SDK generated by API Gateway for a REST API).

Then I went to test out my browser javascript code, and got this error:

Never heard of ‘CORS’ before, sounded like a beer to me. Apparently it stands for Cross-Origin Resource Sharing, that is just a fancy way of keeping web sites free of potentially malicious cross-domain interactions.

I went back to the AWS documentation and found this: Enable CORS on a resource using the API Gateway console. I thought I had this figured out. I went ahead and followed the instructions, refreshed my browser. Same error. Agh.

I went through alot of documentation, code examples, forums until I found (and thoroughly read!) Enabling CORS for a REST API resource. Yep, there at the bottom are the headers I needed to add to my Lambda function return.

I can‘t say I completely understand the whole mechanism, apparently there’s also some preflight request going on. Not sure I care, as long as it works.

As I wrote this down several days past the whole event, if you find any mistakes please please let me know so that I’ll correct them.

I think in my next story I’ll shed some light on access patterns and on Partition Keys in DynamoDB. I’m getting some conflicting info that I need to dig into.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store