Web Services
From RESTful Web Services API overview:
The RESTful Web Services API was first introduced in Drupal 8. Expose entities as REST resources either to build a decoupled Drupal site, to let a native mobile iOS/Android app talk consume/feed a Drupal site, or to integrate with some web service.
Modules
The following Web Services modules are available in core:
- HAL - Serializes entities using Hypertext Application Language.
- HTTP Basic Authentication - Provides the HTTP Basic authentication provider based on Drupal user names and passwords.
- RESTful Web Services - Enables Web Services
- Serialization - Serializes data via xml/json.
REST Request Fundamentals
Safe HTTP Methods (read-only):
GET
- Request data from a URIHEAD
- Retrieve headers from a URIOPTIONS
- Request available communication optionsTRACE
- Echoes back request sent to server
Unsafe HTTP Methods (write)
CONNECT
- Opens a raw connection to a host through a proxy chainDELETE
- Requests that a server delete the resource at URIPATCH
- Request changes on a URIPOST
- Submit data to a URIPUT
- Request submitted data be stored under a URI (currently not supported)
All unsafe methods require X-CSRF-Token
request header, which can be retrieved at /rest/session/token
.
Serialization Formats
From RESTful Web Services API overview:
- Always specify the
?_format
query argument, e.g.http://example.com/node/1?_format=json
- When sending a request body containing data in that format, specify the
Content-Type
request header. This is the case forPOST
andPATCH
.
Authentication
From RESTful Web Services API overview:
basic
- The quickest way to get started is to use basic HTTP Authentication. Enable the Basic Auth module found in core, then send your drupal username and password using HTTP Authorization Headerscookie
- Use the cookie granted to an authenticated user.
You can also use third-party modules to provide support for other authentication such as OAuth.
REST Configuration
Configuration Methods
Configurations are managed with YAML but can setup via REST UI module.
From RESTful Web Services API overview:
Each REST resource has a
\Drupal\rest\RestResourceConfigInterface
config entity that corresponds to a@RestResource
plugin. Without such a config entity, the REST resource plugin will not be available for use.There are two methods for configuring resources:
granularity: method
: Set serialization formats and authentication per HTTP method.granularity: resource
: Set serialization formats and authentication per resource.
Examples:
...
granularity: method
configuration:
GET:
supported_formats:
- json
supported_auth:
- basic_auth
- cookie
...
...
granularity: resource
configuration:
methods:
- GET
...
formats:
- json
...
authentication:
- basic_auth
...
Examples
Using lessons learned in 2.7 - Configuration Management, import the following configuration, specifying REST resource configuration
as the configuration type:
id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
methods:
- GET
- POST
- PATCH
- DELETE
formats:
- json
- hal_json
- xml
authentication:
- basic_auth
- cookie
The above configuration supports GET
/POST
/PATCH
/DELETE
requests.
Since this creates a generic endpoint, this data can now be consumed by any number of languages, frameworks and applications. The following examples illustrate a few different options:
GET
Assuming you have a node previously setup with nid
of 1, you can test this by navigating to /node/1?_format=json
in your browser. If setup correctly, you should see your node represented by JSON instead of HTML.
For more detailed examples, see GET for reading content entities example.
POST
x_csrf_token=$(curl --silent http://localhost:8888/rest/session/token)
curl --include \
--request POST \
--user admin:password \
--header 'Content-type: application/hal+json' \
--header "X-CSRF-Token: $x_csrf_token" \
http://localhost:8888/entity/node?_format=hal_json \
--data-binary '{"_links":{"type":{"href":"http://localhost:8888/rest/type/node/article"}},"title":[{"value":"My Node Title"}],"type":[{"target_id":"article"}]}'
Notes:
- This example requires the HAL module
- For security reasons it is considered bad practice to type passwords directly into your terminal. More secure methods of authentication should be considered.
For more detailed examples, see POST for creating content entities example.
PATCH
function getCsrfToken(callback) {
jQuery
.get(Drupal.url('rest/session/token'))
.done(function (data) {
var csrfToken = data;
callback(csrfToken);
});
}
function patchNode(csrfToken, node) {
jQuery.ajax({
url: 'http://localhost:8888/node/1?_format=hal_json',
method: 'PATCH',
headers: {
'Content-Type': 'application/hal+json',
'X-CSRF-Token': csrfToken
},
data: JSON.stringify(node),
success: function (node) {
console.log(node);
}
});
}
var newNode = {
_links: {
type: {
href: 'http://localhost:8888/rest/type/node/article'
}
},
type: {
target_id: 'article'
},
title: {
value: 'This is my brand new title'
}
};
getCsrfToken(function (csrfToken) {
patchNode(csrfToken, newNode);
});
Notes:
- This example requires the HAL module
- This example assumed cookie-based authentication, which means you need to be running under the same domain name.
For more detailed examples, see PATCH for updating content entities example.
DELETE
<?php
$response = \Drupal::httpClient()
->delete('http://localhost:8888/node/1?_format=json', [
'auth' => ['admin', 'password'],
'body' => '',
'headers' => [
'X-CSRF-Token' => $x_csrf_token
],
]);
?>
Notes:
- This example assumes you already have the
$x_csrf_token
value to the value from/rest/session/token
.
For more detailed examples, see DELETE for deleting content entities example
Exposing Views via Web Services
To expose a view via Web Services:
- Edit your view.
- Under
Displays
click+ Add
and selectREST export
. - Under
Path Settings
set a path for your export. - You can adjust various settings in regards to format and fields to display as you would with any other view.
- Once you are finished, save your view
- Navigate to the path specified above in your browser. If everything went as expected, you should see your view in your specified format:
Additional Resources
- drupal.org - RESTful Web Services API overview
- drupal.org - RESTful Web Services module overview
- drupal.org - Authentication API
- w3.org - HTTP 1.1/Method Definitions
Questions
What is the purpose of Drupal's RESTful Web Services API?
The RESTful Web Services API in Drupal allows for exposing entities as REST resources, facilitating the creation of decoupled Drupal sites, enabling native mobile apps to interact with Drupal, and integrating with other web services.
Which core modules in Drupal provide web services functionality?
The core modules that provide web services functionality are, HAL
: Serializes entities using Hypertext Application Language, HTTP Basic Authentication
: Provides HTTP Basic authentication based on Drupal usernames and passwords, RESTful Web Services
: Enables web services, Serialization
: Serializes data via XML/JSON.
What are the safe HTTP methods and unsafe HTTP methods supported by Drupal's RESTful Web Services, and what are their purposes?
Safe HTTP methods are read-only operations: GET
: Requests data from a URI, HEAD
: Retrieves headers from a URI, OPTIONS
: Requests available communication options and TRACE
: Echoes back the request sent to the server. Unsafe HTTP methods are write operations: CONNECT
: Opens a raw connection to a host through a proxy chain, DELETE
: Requests that the server delete the resource at the URI, PATCH
: Requests changes to a resource at the URI, POST
: Submits data to a URI and PUT
: Requests that submitted data be stored under a URI (currently not supported in Drupal). All unsafe methods require X-CSRF-Token
request header, which can be retrieved at /rest/session/token
.
What authentication methods are available for Drupal's RESTful Web Services?
Basic Authentication
: Enable the Basic Auth module and send your Drupal username and password using HTTP Authorization headers. Cookie-based Authentication
: Use the session cookie granted to an authenticated user. Also third-party modules can provide support for other authentication methods, such as OAuth
.
How can REST resources be configured in Drupal, and what are the two methods?
REST resources in Drupal can be configured using YAML configuration files or via the REST UI module. The two methods for configuring resources are: Granularity Method
: Set serialization formats and authentication per HTTP method and Granularity Resource
: Set serialization formats and authentication per resource.