How to build an API that returns all the entries of a section in Craft CMS

Oscar de la Hera Gomez
A flower that represents Craft CMS with the text "GET All Entries Endpoint" beneath it.

A step by step walkthrough in creating a GET RESTful endpoint in Craft CMS that uses a controller action to return all the entries of a section.

The following tutorial walks you through how to use a Controller action to gather all the entries of a section and return them as part of a Craft CMS GET API. The tutorial forms part of our Open Source series that details how to create API endpoints that manage the subscribers to the delasign website.

This tutorial assumes that you have created a channel called subscribers, but we would like to note that the knowledge shared in this tutorial can be adapted to suit your needs.

We recommend downloading and setting up our Open Source Craft CMS starter project and checking out the main branch and carrying out the steps below. The changes carried out can be found on tutorial/get-all.

git clone git@github.com:delasign/craft-cms-starter.git

Step One: Create your API endpoint base

A screenshot of Postman showing a succesful API call for the GET endpoint.

Please follow the tutorials linked below to create your RESTful API with an API key. We recommend testing it in Postman before continuing.

Please note that you must run this line after creating the API base for the API to register:

composer dump-autoload -a

Step Two: Complete the API

A screenshot of VSCode of the completed API. The sample code is provided below.

To gather your entries you must import the craft\elements\Entry at the top of your PHP file by adding the line:

use craft\elements\Entry;

Subsequently, in your Controller action you must gather all entries by using code similar to the one below and replacing YOUR_SECTION with the section handle of the section that you are seeking to filter by.

$entries = Entry::find()->section(["YOUR_SECTION"])->all();

Finally, you must return it through a standardized response:

return $this->sendResponse(200, null, $entries);

Here is a sample Controller that gathers all the subscriber and returns them, using a standardized response as a JSON.

We recommend using standardized responses so that your API's always read the same way.

Step Three: Test

A screenshot of Postman showing all the Subscriber entries. This proves that the endpoint works as expected.

Confirm that the API functions as expected by making a Postman call to your endpoint.

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