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. Normally we can use view but here we will be learning how to do the same 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 rest api.
This module will be dependent on Rest and Rest UI module so we need to enable these two module as well. Rest is included in drupal core but 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.
- Goto admin/config/services/rest
- Search for rest api (in our case its “Example get rest resource”) and enable it.
- 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.
- Click on “save config”
- Now goto /example-rest?_format=xml
<item key="1">Test Article </item>
<item key="2">test article</item>
<item key="3">rest test</item>
<item key="4">Rest Test</item>
<item key="5">Test Drupal 8</item>