Setting up an API endpoint to serve Drupal content

It's been almost two years since Dries Buytaert announced the API-first initiative for Drupal. In that time, significant progress has been made towards this objective.

There are a couple of projects (see here and here) that aim to provide an API-first experience out-of-the-box. But if those distributions do not meet your needs, or you are working with an already established Drupal 8 site, the good news is that serving your content via API has become a lot simpler over the last few months thanks to the efforts of Drupal's developers.

This blog post will explain how to create an API endpoint to serve Drupal content.

The first thing to do, it to enable the RESTful Web Services and Serialization modules. With Drupal 8, these modules are included in core, but are disabled by default.


Enable these core modules to get started


Once those are enabled, you can create a REST export display from any view:

REST export display option


On the REST export display, set a path. This will be the API endpoint from where your data will be served. In this case, I am using api/v1/default-content. It's good practice to version your API, so that you can introduce improvements without breaking anything that relies on it.

REST export path

Once you have saved the view, you will be able to pull content by submitting a request the specified path.

As with other views, you have access to many options such as permissions, filters, orders, number of items to display and more.

Using the fields shown in the image below, you can choose the format and fields that should be returned.

The default option "Entity" returns the entire node object in serialized form. You can modify it to return only select fields.

Views data format fields

In the example below, I'm choosing to return only the title, body, comment count, and authored by fields. I'm also filtering out unpublished content, and sorting by date.

In the right column, I have the "View published content" permission set, and have a limit of five items to be returned.

REST display options

To view the response to a GET request, you can enter the address in your browser's URL bar.

Here is what a query looks like in Postman:

A GET request

As you can see, five items are returned, each with four fields. Note how the title and body fields return content with HTML tags. These can easily be stripped out using the configuration options.

Strip HTML tags

Drupal developers know of the awesome power provided by Views to Drupal websites. But now with the assistance of Drupal REST services, this power can be harnessed to provide content to external systems too.