Custom Rest Resources for POST methods in Drupal 8

How to create Custom Rest Resources for POST methods in Drupal 8

One of the biggest changes in Drupal 8 is the integration of Rest services in the core. With use of Views it become very easy to create RESTful Services.

But there are certain situations when you need to create your own custom REST Resources. There are documentations available for creating a GET request using Views and using custom module. However there isn’t much documentation available for creating Rest Resources for POST methods.

In this article I will be sharing, how to create a REST Resource for POST methods. This Rest API will create an article in Drupal 8 site from an external application.

Note: I will be using Drupal Console for generating the module and code boilerplates.

Create the module
drupal generate:module



Create the Rest Resource Plugin
drupal generate:plugin:rest:resource



The above command will create a Plugin for rest resource in your module. The url /api/custom is the url for your resource which can be accessed like localhost:8000/api/custom?_format=json

Enable the resource from RestUI

rest UI

This was the easiest part.  Now we need to modify the Plugin created by Drupal Console to get the Resource working for POST methods.

In the above file change the Annotation lines

*  uri_paths = { 
*    "canonical" = "//api/custom" 
*  }


*   uri_paths = {
*     "canonical" = "//api/custom”,
*     "" = "//api/custom"
*   }

Otherwise your API will be be expecting the request to use the /entity/{entity_type} endpoint, which will conflict with the endpoint provided by core.

Next we need a serializer class for normalising the data being passed.
Add serialization_class = "Drupal\node\Entity\Node", in the Annotation for the Resource.
This will ensure that the data being passed is of entity type Node.

To run the resource use a Rest Client for example Advanced Rest Client.

advanced Rest Client

Now to create the node from the Rest Client change the create() function in your Resource class.

All done! This, is how we can create a node using Rest Resource for POST methods in Drupal 8. Here is the complete code for the Resource Plugin file: