How to add an API Key to a RESTful endpoint in Craft CMS

Oscar de la Hera Gomez
A flower that represents Craft CMS. Beneath it sits the text "API Key."

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

A screenshot of our .env file with the API Key environment variable that we created highlighted. Follow the tutorial linked below to learn how to create and use Environment Variables.

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

A screenshot of VSCode with the function offered below that verifies if the API key matches that of the API call and if not returns a 403 Forbidden error.

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

A screenshot of Terminal running composer dump-autoload -a.

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

A screenshot of Postman showing a successful API call using the API Key.

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.

A screenshot of Postman showing a forbidden response from an API call using the wrong API Key.

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.

delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details