Search code examples
amazon-web-servicesrestaws-api-gatewayapi-key

In AWS how do I add an API key to my API?


Hello: I've been following two tutorials in the AWS documentation:

creating the sample pet store API (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-from-example.html)

...and creating an API key (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-setup-api-key-with-console.html#api-gateway-usage-plan-create-apikey).

When I test the pet store get method with the provided URL, it returns:

Welcome to your Pet Store API You have successfully deployed your first API. You are seeing this HTML page because the GET method to the root resource of your API returns this content as a Mock integration.

The Pet Store API contains the /pets and /pets/{petId} resources. By making a GET request to /pets you can retrieve a list of Pets in your API. If you are looking for a specific pet, for example the pet with ID 1, you can make a GET request to /pets/1.

You can use a REST client such as Postman to test the POST methods in your API to create a new pet. Use the sample body below to send the POST request:

{ "type" : "cat", "price" : 123.11 }

Now I go to the API Gateway -> API -> Resources -> -> Method Request -> API Key Required and change it to "True" and redeploy.

When I go to the provided URL to test, now the page returns:

{"message":"Forbidden"}

Which makes sense... I told it API required = true, right?

So my question is, how do I pass the API key? So that I don't get the "forbidden" result? I didn't see that in the tutorial links I pasted above and haven't been able to find elsewhere.


Solution

    1. You Create a Usage Plans
    2. Attach this usage plan to your API and Stage
    3. Create an API Key
    4. Now invoke your API with header named x-api-key and value of it is the API Key created in step-3

    Sample: curl -i -H "x-api-key: Cd2YiWs8Fv8Lg6njI0wXf1iiNOE94XjM3EQe8567" -X GET https://7r9cvghbf4.execute-api.ap-northeast-2.amazonaws.com/dd/pets