How to add an API Key to a RESTful endpoint in Craft CMS
A step by step tutorial on adding API keys to a RESTful Craft CMS endpoint.
The following tutorial builds on our Open Source tutorial series and demonstrates how to add an API key to an existing Craft CMS Restful API. For details on how we created our Open Source Craft CMS starter project, how to set it up or create an RESTful API, please consult the tutorials listed below.
We recommend downloading our Open Source project, checking out the tutorial/api branch, completing the setup listed in the tutorial linked below and carrying out the steps outlined below. All relevant changes can be found on the tutorial/api-key branch.
git clone git@github.com:delasign/craft-cms-starter.git
Step One: Add the API Key
Create a new environment variable called API_Key and add a secure key.
We recommend using LastPass and generating a 32-50 character, secure string.
Step Two: Add the API verification to your endpoint
Complete your API endpoint by checking for the API Key in the beforeAction functionality.
Sample code on how to do so can be found below.
Step Three: Reload Modules
To make Craft CMS registers the API key, run the following line in Terminal with the current directory set to that of your Craft CMS project:
composer dump-autoload -a
Step Four: Test
Postman request showing the API call working.
In Postman, try hitting your endpoint with and without the x-api-key parameter, or whatever parameter you used for your API key in Step 2, as well as with the correct API key and a random string to test all scenarios.
Postman request showing the API call returning a forbidden, as the wrong API key is passed in the parameter.
Any Questions?
We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.