How To Request A Node via REST Using Web Services in Drupal 8

Jul 8, 2015 · 482 words · 3 minute read php development

Drupal 8 is going to be a central place to store data and can easily connect with different third-party applications. Dries Buytaert has talked about this idea multiple times in DrupalCon Austin and DrupalCon Bogota, where Drupal 8 is going to be an API to connect to other places. For this reason, Drupal 8 is now integrated with web services in core. In other words, this is an easy way to export data into Hal-JSON, JSON, and XML. I decided to start playing with web services in Drupal 8 to see how I can export my data in JSON format and connected with third party app. I found many tutorials that talks about Drupal how to export JSON data using the Views module, which for many use cases can be very good. I started to think, “What if I just want the data from only one node? I do not want to generate a view for every single page that I wanted in JSON.” So I found a way to get my node data either on Hal-JSON, JSON, and/or XML automatic without creating a view every single time.

Warning

This will only work with Drupal 8 beta 12 or later.

First you need to install the Rest UI (restui-8.x-1.x) and enable HAL, HTTP Basic Authentication, RESTful Web Services, and Serialization module. In the Rest UI configuration page, click edit on the “Content” Resource:

‘Rest UI admin’

Then configure this page like this:

‘Rest UI Admin GET’

This would allow us to enable rest in our nodes.

After configuring Rest UI module, you would have to provide permission to anonymous user to GET, POST, DELETE, PATCH, your data.

Warning Most website will only need GET, if all you want is to get data out of the website only enable the GET permission.

‘Rest UI Admin Permission’

Once anonymous users have permission to GET, POST, DELETE, PATCH, all you need to do is to add the _format at the end of the URL with the equal sign and the name of the web services. For instance, if you want your data to be exported to JSON, the resulting URL would look like this www.example.com/node/1?_format=json, for Hal-JSON it would look like www.example.com/node/1?_format=hal_json and for XML www.example.com/node/1?_format=xml. This also will work with aliases so you do not need to worry about what is the node id.

To be 100% sure that your web service is working you can use a tool similar to Chrome extension Postman, to get your webservices data and should looks something similar like this.

‘Rest UI Admin Response’

If by any chance you do not see your node data and you see something similar to this:

‘Rest UI Admin Response’

This means either that you did not configure the Rest UI module correctly or there is a bad configuration on the permission page.

Note All this have been handled by the new route system in Drupal 8. For more information about this, I recommend reading this > article Structure of routes.