How to create custom Rest Api
In this tutorial, we will learn how to create a custom RESTful Web Service in Drupal 9.
Before creating Rest Api, we need to know what REST API is. An application programming interface (API or web API) allows interaction with RESTful web services. Where REST is known as Representational State Transfer.
First, We will need to install these core modules HTTP Basic Authentication, REST Web Services, and serialization module.
Then install Contributed module called REST UI, which you can download from
the composer requiring ‘drupal/restui:^1.21’
Let’s create a custom module named “Rest Example” in /modules/custom
After that create ExampleRest.php
in directory /modules/custom/rest_example/src/Plugin/rest/resource/ExampleRest.php.
This is our custom resource file which will have get method that will get all nodes of content type Football Teams.
/** * Provides a Rest Resource Example * * @RestResource( * id = "rest_example", * label = @Translation("Rest Example Resource"), * uri_paths = { * "canonical" = "/rest_example" * } * ) */
Let’s understand annotation.
- @RestResource is a function, through which know, it’s a kind of Rest Resource
- id define the id of Rest Resource API
- label displaying to the user through which author can know about this api
- uri_paths : canonical attributes set the path of API.
In our case, we will use “sitename/rest_example” to hit our API. After this, we need to install our module.
Then go to /admin/config/services/rest and enable our custom resource Rest Example Resource
After that, select the following options
Further, allow anonymous permission to our rest resource.
Now we will hit our get resource.