How to add an API key to a Serverless function
A step by step tutorial on adding an API key to a Serverless function.
The following tutorial builds off our Open Source starter project and walks you through how to create an API using an AWS Lambda function and an API Gateway through Serverless and Typescript.
Please note that this tutorial assumes that you have setup Serverless for deploying to AWS. For a comprehensive breakdown on how to do this, please follow the tutorial below.
We recommend downloading our Open Source project, checking out the tutorial/lambda-hello-world branch and carrying out the steps outlined below. All relevant changes can be found on the tutorial/api-key branch.
git clone firstname.lastname@example.org:delasign/typescript-serverless-starter.git
Step One: Update your Serverless.yml
First, include an API gateway key by adding it under the provider section. Please note that you must name your key - we have called it typescript-serverless-starter-key-dev as each stage should have its own key.
Subsequently, make the function private. This will let Serverless know that you want it to use an API key.
Finally, under cors, set the relevant headers in the function and set the allowCredentials to false.
Step Two: Deploy
In your terminal, set the current directory to that of the serverless project and run sls deploy.
At the end of the deploy, the console will inform you of the path of your API.
Please note that this requires you to have setup AWS credentials for your Serverless client.
Step Three: Verify
Verify that your API call works using the information gathered in Step 2, applying the x-api-key header for the api key that was produced.
If you would like to learn how to make an API call in Postman, use the tutorial linked below.
We are actively looking for feedback on how to improve this resource. Please send us a note to email@example.com with any thoughts or feedback you may have.