Create a RESTful web service with Drupal 8

Read the full article on x-team.com.


Disclaimer: Drupal 8 is still in a very early stage. Therefore, some examples or content in this article is subject to change without notice. I will be using the Drupal 8.0-alpha10 package that you can find here.

My girlfriend and I (like mostly everyone really) are always looking for ideas about what to eat. We tried a lot of recipes over the years and couldn’t figure out a good way to file them for future use.

We finally took the time and created a  little website to expose all the recipes we loved; and we did it through a simple web service. It was the perfect time to try the new Drupal 8 web services!

Step 1

Install Drupal 8 using the standard profile. (Please use alpha 10 release)

Step 2

Go to “/admin/modules” and activate the RESTful Web Services and the Serialization module.

Screen-Shot-2014-03-22-at-5.47.56-PM-640x218

 

Step 3

Create you recipe content type with all the fields you want to see displayed on the front-end.

Screen-Shot-2014-03-22-at-6.01.03-PM-640x421

 

Step 4

In “admin/people/permissions” add “Access GET on content ressource” so anonymous user will be able to access the content.

content_permission-640x207

 

Step 5

Now we need to create the view that will serve the web service (this is the interesting part!).

  1. Create a new view with a REST export display
  2. Make sure the format is “Serializer” and in the settings check the “json” option
  3. Add a random sort criteria so the web service would randomize the result sent to the user
  4. Change the path to “/recipe/”
  5. Save the view

Screen-Shot-2014-03-22-at-6.12.45-PM1-640x376

Step 6

Point your web browser to yourdomain.com/recipe/ and enjoy the beautiful json output!

Final thoughts

This a was quick overview of the potential of Drupal 8 web services. Of course, with the power of views, one can even expose any entities to a RESTful json representation without even typing one line of code (this could be even more powerful with the use of the oauth module for authentification).

I can see Drupal 8 becoming a one-stop shop for any company looking to implement a quick and easy web service.