Using AWS API Gateway to Enable CORS for Cloud Search

When designing new solutions one of our key goals is to shift as much load as we can off of server instances that we manage to services that are automatically scaled in the cloud. This practice reduces infrastructure complexity while increasing availability and reducing cost.

Recently I began designing a new feature that required searching from a browser. Calling Cloud Search directly from the browser seemed like a great solution. Unfortunately doing this requires CORS, which I discovered isn't supported natively on the Cloud Search service. Luckily I found a work around with the Amazon API Gateway, let me explain.

A Little Backgound on API Gateway
API Gateway allows you to host your own REST API without the need to manage the underlying instances to host your services. It can proxy API requests to other HTTP URLs or to Lamda Functions. As I discovered, it can also be configured to support CORS.

Armed with the API gateway I set off to create a publicly available Cloud Search index that I could search directly from a browser. Here is what I did:

1. Create a New API
The first step was just to create a new API using the AWS Console and set it up to proxy to the Cloud Search service. I went with a GET API and the configuration looks something like this:

2. Enable Querystring Parameters
Once you setup the API, you need to tell the API Gateway to allow the "q" query string variable (and any others you may want to use) through to the service. This is a two step process:

1. In the Method Request configuration I added a URL Querystring Paramater "q" (I left caching unchecked).

2. In the Integration Request configuartion I added the URL Query String Parameter "q" again and set it to method.request.querystring.q (again, left caching unchecked).

What are you basically doing in this section is allowing the "q" variable and enabling it to pass through to the Cloud Search endpoint. You need to repeat this if there are other parameters you want to pass to Cloud Search.

3. Enable CORS
The last step was to enable CORS on the new API. I followed the Amazon Documentation for Enabling CORS on API Gateway (I found that steps 18-24 to be repetitive, it might just be a documentation typo, so I skipped 18-24). Be careful to keep Response and Request straight when configuring the API.

Deploy and Call the new API
All that is left to do is to deploy the new API. When you deploy you will get a URL to use for the API which you can then plumb into your app.