An Introduction to RESTful Web Services in Drupal 8

One of the Drupal 8 initiatives that really excites me is Web Services. Drupal has never been easy to work with as a web service, but all that is about to change! In this article I am going to explore what has been going on behind the scenes with RESTful Web Services in Drupal Core and attempt to implement some working examples. After reading, you will be able to create a new node on your site via the Drupal 8 Core REST API.

Please remember that Drupal 8 is still in the alpha stage. Therefore, it is buggy and constantly changing. Your results may differ from those shown here.

What is REST?

It’s best that I first make sure everyone is on the same page. Web Services make it possible for external applications to interact with our application (in this case our Drupal site). These interactions are most commonly reading, creating, updating, and deleting resources.

REST is one of the most popular ways of making Web Services work. There are other formats such as SOAP or XML-RPC, but we are only going to focus on REST because it is the Drupal standard. REST utilizes HTTP methods, such as GET, POST, and DELETE.

As an example, a popular usage of a REST interface is a mobile application that needs to read and write data from your site's database.

Drupal 8 Core

Web Services have been implemented in Drupal 8 Core with the following modules:

  • RESTful Web Services (rest)
    Exposes entities and other resources via a RESTful web API. It depends on the Serialization module for the serialization of data that is sent to and from the API.

  • Serialization (serialization)
    Provides a service for serialization of data to and from formats such as JSON and XML.

  • Hypertext Application Language (hal)
    Extends the Serialization module to provide the HAL hypermedia format. This is what is used as the primary format in Drupal 8 Core. It only adds two reserved keywords, ‘_links’ for link relations (also used by Github's Pull Request API) and ‘_embedded’ for embedded resources. The HAL hypermedia format can be encoded in both JSON and XML. For more details see the initial HAL proposal.

  • HTTP Basic Authentication (basic_auth)
    This module implements basic user authentication using the HTTP Basic authentication provider. It faciliates the use of an username and password for authentication when making calls to the REST API. It is required for the examples shown in this blog post, and I would advise configuring SSL if you use it in production. For anyone lookiing for a more secure option, check out the contrib OAuth module which already has a Drupal 8 branch.

Getting started

Start by grabbing the latest alpha of Drupal 8 Core and installing your site. I am using alpha6 at the time of writing this post. See the Releases for Drupal Core to find the latest download.

Enable the following modules: REST, Serialization, HAL, and HTTP Basic Authentication.

By default, the REST module enables the node entity resource for all GET, POST, PATCH, and DELETE operations. It supports basic or cookie authentication and the HAL or JSON formats. You can see these default settings in sites/default/files/config_XXXX/active/rest.settings.yml. To enable REST on other entities (e.g. users, files, or fields), you’ll need to edit this file. There is, however, a handy Contrib module created by our very own Juampy named REST UI. This module provides a user interface for enabling and disabling resources, serialization formats, and authentication providers. See the screenshot below for an example of the configuration options REST UI provides.

Let me take this opportunity to explain the available resource options, GET, POST, PATCH, and DELETE. These are all common HTTP methods. Each operation signifies a type of action to be performed on a resource. For example, your browser used GET when you requested to view this blog post. To read a resource, we GET. To create a resource, we POST. To update a resource, we PATCH. And to delete a resource, we DELETE. Read this post if you’re wondering why we use PATCH and not PUT.

Now back to our setup. For all enabled resources, the REST module can set user permissions. Go to admin/people/permissions and set up your permissions, as required. Here is an example of how I set mine:

You should create also a new authenticated user for testing purposes. If you test your API with User 0 administrator account credentials, you will likely miss permission settings that you need to be set.

Using the REST API

Now we’re ready to start using our REST API. I recommend the Dev HTTP Client Chrome extension for testing calls to any API. You can also write scripts in Guzzle, which is a great new tool included in Drupal 8 Core or cURL via the command line or PHP.

Start by creating a node entity. To do this, we must send a POST to /entity/node with the Content-Type header set to application/hal+json and declare the required type and title fields in the request BODY. But don't forget that as we are using Basic Auth. We need to set the headers PHP_AUTH_USER and PHP_AUTH_PW to authenticate as our user. Here is how it looks in the Dev HTTP Client:

Or, if you prefer, you can try cURL from the command line:

curl --include --request POST --user drupaljoe:mango --header 'Content-type: application/hal+json' http://localhost:8082/d8/entity/node --data-binary '{"_links":{"type":{"href":"http://localhost:8082/d8/rest/type/node/page"}}, "title":[{"value":"My first page"}]}'

You'll notice the request is returning 403 Forbidden. It’s important to remember that although you have given authenticated users permission to Access POST on Content resource they still need permission to perform the underlying action which, in this case, is creating a new page node. So head back to the permissions page and make sure authenticated users have at least the Page: Create new content, Page: Edit own content and Page: Delete own content permissions.

Try again and you’ll now get a nice green 201 Created response. Congratulations! You just created a node entirely via your new REST API!

If you go to view the node you will notice that the author is set to Anonymous. This is because of a Drupal 8 core bug that is present at the time of writing this and is detailed in this issue: https://drupal.org/node/2113681#comment-8340037

You can now GET the node we just created. Send a GET to /entity/node/<nid> with the Accept header set to application/hal+json and you should receive a 200 OK with the BODY containing a HAL representation of the entire node entity. For a simpler JSON representation, set the header to application/json and compare the results.

You should now have a general understanding of REST in Drupal 8 and the basics behind manipulating single Drupal entities via the REST API. We only used POST and GET, but PATCH and DELETE work similarly. Feel free to try them in your own time!

I hope to write more posts about REST in Drupal 8 on topics such as setting custom entity field values and retrieving lists of entities using Views. I'd like to look also into setting up more secure REST API authentication using modules such as OAuth.

Update: My blog post on RESTful Views in Drupal 8 has been released.

Please leave your comments and queries below and I’ll do my best to answer what I can!

Further reading

 

Related Topics: 

Comments

Great post!!

Thank you very much for sharing.

Just one typo in the line regarding "(Read this post if you’re wondering why we use PUT and not PATCH.)". I guess you mean the opposite: "(Read this post if you’re wondering why we use PATCH and not PUT.)"

Regards.

Aha, I confused even myself on that one. Thanks very much Ruben, I've updated the article text.

Nice introduction, thanks. The only thing I don't understand is why the node type is defined as a "_links" property referring to a URL. Simply {"type":"page"} would have made sense IMHO...

You can use the simple JSON format which would allow you to write syntax that way. However, the default mediatype format in Drupal 8 is HAL. You can read up more about HAL here: http://stateless.co/hal_specification.html

 

My understanding is that HAL offers developers that use the API more insight into navigating around the API therefore making it easier to work with and more appealing. I would also recommend watching the REST and Serialization in Drupal 8 DrupalCon Prague 2013 presentation as they touch on this topic too.

Thanks!

I wonder if you meant to talk about Guzzle Oauth (https://drupal.org/project/guzzle_oauth) instead of Oauth? If not, I'd love to know why exactly?

Guzzle OAuth seems to be for signing requests to other external APIs with our OAuth credentials. For example, as shown on the modules front page, when calling the Twitter API you can use Guzzle OAuth to easily add your API credentials.

 

What we want to do here is use the OAuth module to set up server side authentication of other users calling our own website via our REST API.

This is a great overview - thanks !

Any idea if the Field API has been cleaned up a bit in D8? A big headache with services in D7 was the data structure was all over the place. I had to use Tamper Data Firefox plugin to see exactly what was expected in the POST data to CREATE/UPDATE entity fields using the services module. It was also nearly impossible to establish a pattern to automate client side editing to send through to Drupal Services

Hey Marcus. I'm not actually sure how accessible the Field API is through REST in Drupal 8 yet. It's something I hope to dive in soon so if I do figure something out, I'll let you know!

Great post!! My understanding is that HAL offers developers that use the API more insight into navigating around the API therefore making it easier to work with and more appealing. Thank you very much for sharing.

This is great. It got me headed in the right direction. I have been working with AngularJS but am having trouble figuring out the exact syntax to use for my GET to be sent to my Drupal 8 site. Any idea where some tutorials specific to tying AngularJS/Drupal 8 REST might reside? Thanks.

I'm not too familiar with how AngularJS builds GET requests but the $http service might be what you need. http://docs.angularjs.org/api/ng/service/$http

Hi,

I just wanted to see how the custom resources (especially the POST method) works in the Drupal 8 RESTful services.

Let's say i have a custom table 'xyz' and i just wanted to create a RESTful resource which will GET and POST data to these tables. Can you please show me some pointers in this?

Hi Nagarajn, you can indeed turn a custom module into a RESTful resource. You would need to create a 'resource plugin' like the rest module in core does for entities out of the box. There isn't much documentation out about this at the moment but there is a couple of slides on the subject by Lin Clark that might prove useful. http://lin-clark.com/d8-rest-slides/#36

Alternatively, if you can turn your custom data into an entity then you wouldn't need to write your own plugins. Good luck!

Thanks! I have created the custom resource using the 'resource plugin' and i can view the data fro the GET method. But when it comes to PST method, am getting the error saying "error":"Could not denormalize object of type , no supporting normalizer found."}

Also the Lin Clark's slides gave me a good start.

Please change URI to /node/1 instead of entity/node/1
Since https://drupal.org/node/2199185 happened. Update the article :)
Thank you.

Add new comment