To explore the RESTful nature of Drupal 8, we will need to enable the following modules:
In Core
- HAL - Serializes entities using Hypertext Application Language.
- HTTP Basic Authentication - Provides the HTTP Basic authentication provider.
- RESTful Web Services - Exposes entities and other resources as RESTful web API
- Serialization - Provides a service for (de)serializing data to/from formats such as JSON and XML.
Contributed
- REST UI - Provides a user interface to manage REST resources.
RESTful Resources
Every entity in D8 is a resource, which has an end point. Since, its RESTful, the same end-point is used for CRUD (Create, Read, Update, Delete) operations with different HTTP verbs. Postman is an excellent tool to explore / test RESTful services. Drupal 8 allows you to selectively choose & enable a REST API. e.g., we can choose to expose only nodes via a REST API & not other entities like users, taxonomy, comments etc.
After enabling REST_UI module we can see list of all RESTful resources at /admin/config/services/rest. In addition to ability to choose the entity one can enable, we can also choose the authentication method per resource & enable specific CRUD operations per resource.
Let us take a look at what the REST APIs for User entity would be after we save the configuration in the above screenshot.
User
POST
Header
Note: Drupal 8 doesn't allow anonymous user to send a POST on user resource. It is already fixed in 8.3.x branch but for now we can pass the credentials of the user who have permission to create users. If you are interested in taking a deeper look at the issue, you can follow https://www.drupal.org/node/2291055.
Response: You will get a user object with "200 OK" response code
PATCH
Note: Now as user have permission to update his own profile so we can pass current user's credentials in authentication header.
Response: You will get "204 No Content" in response code.
GET
Response: You will get a user object with "200 OK" response code.
DELETE
Response: You will get "204 No Content" in response code.
RESTful Views and Authentication
Drupal 8 also allows us to export views as a REST service. It allows you to use all the available authentication mechanism in views itself.
JSON API Module
JSON API module provides a new format called "api_json" which is soon becoming the de-facto standard for Javascript Frontend frameworks, If you plan to use completely de-coupled Drupal with frontend framework like Angular / React / Ember then its worth a look. To read more about JSON API you can visit the site.This article assumes you are familiar with what RESTful is & what do we mean when we use the term REST API. Some of you might have already worked with RESTful Web Services module in D7, it exposes all entity types as web services using REST architecture. Drupal 8 out of the box is RESTful with core support. All entities (provided by core + ones created using Entity API) are RESTful resources.