Create Rest Resource for GET Method in Drupal 8

Create Rest Resource for GET Method in Drupal 8

In one of the earlier blog post we had explored, How to create Custom Rest Resources for POST methods in Drupal 8. Let's see how can we create Rest Resource using GET method in Drupal 8. 

RESTful services were introduced in Drupal 8 into the core, this was inspired by Drupal 7. With Drupal 8 REST, you can enable other websites or applications to view, edit or update information. REST, among other Drupal 8 web services like XML and JSON is a method to provide customizable data in the form of API. 

Normally we can use view but here we will be learning how to create drupal 8 REST using custom code.

So let’s create an example module ‘example_rest’

Module Setup :

Now we will be defining the rest resource. In this we will be fetching all the existing node title in the existing drupal.

Let’s create rest resource with GET method.


Here in get method we will be defining the logic what we want as output. 

As example we are loading all node present in the drupal installation and return node title as key value pair. Node id will be key and title will be respective value.

Let’s  enable the module and Drupal rest api.

This module will be dependent on Rest and Drupal Rest UI module so we need to enable these two module as well. Rest is included in drupal core but drupal 8 Rest UI is a contributed module so we need to download and enable it.

Once we enable all required module we need to enable our rest api.
 1.Goto admin/config/services/rest
 2.Search for rest api (in our case its “Example get rest resource”) and enable it.
 3.Once you click on enable  it will open the setting page of the respective api we need to select Get and Supported formats as xml, Authentication providers as cookie.
 4.Click on “save config”
 5.Now goto /example-rest?_format=xml

Result :

Test Article
test article
rest test
Rest Test
Test Drupal 8