Khanh Hoang - Kenn
Kenn is a user experience designer and front end developer who enjoys creating beautiful and usable web and mobile experiences.
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.
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.
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.
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.
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.
Please leave your comments and queries below and I’ll do my best to answer what I can!
Bình luận (0)
Add Comment