Defining a custom REST resource pluginfor Drupal 8 , 9 , 10 , and 11

Last updated :  

As you establish your skills in Drupal module development, creating RESTful services becomes essential. Today, we’re honing in on defining a custom REST resource plugin—a fundamental step in providing flexible and robust APIs within Drupal.

What is a REST Resource Plugin?

A REST resource plugin in Drupal serves as a connector to expose data or functionality via RESTful web services. Plugins are integral to the extensible nature of Drupal, allowing developers to add new operations and customize data exchange through HTTP methods like GET, POST, PUT, and DELETE.

Setting Up Your Environment

Before creating your plugin, ensure your development environment is ready. This includes a running Drupal site with module dependencies such as the REST and Serialization modules enabled:

      
          drush en rest serialization -y
      
    

Also, make sure you have a custom module, which we previously set up in this series. Navigate to your module’s folder. Let's say your module is named my_rest_module:

      
          cd sites/all/modules/custom/my_rest_module
      
    

Creating the REST Resource Folder Structure

Within your module, create the necessary directory path for your PHP class file:

      
          mkdir -p src/Plugin/rest/resource
      
    

This path follows Drupal’s PSR-4 standard for class autoloading, ensuring your plugin is discoverable by the system.

Creating the REST Resource Plugin

Create a new PHP class within src/Plugin/rest/resource called MyCustomResource.php. This file will define your custom resource:

      
          // File src/Plugin/rest/resource/MyCustomResource.php

          <?php
          namespace Drupal\my_rest_module\Plugin\rest\resource;

          use Drupal\rest\RestResourceBase;
          use Symfony\Component\DependencyInjection\ContainerInterface;
          use Symfony\Component\HttpFoundation\Request;
          use Drupal\rest\ResourceResponse;

          /**
           * Provides a My Custom Resource
           *
           * @RestResource(
           *   id = "my_custom_resource",
           *   label = @Translation("My Custom Resource"),
           *   serialization_class = "Drupal\Component\Serialization\Json",
           *   uri_paths = {
           *     "canonical" = "/api/v1/custom-resource"
           *   }
           * )
           */
          class MyCustomResource extends RestResourceBase {

            /**
             * Constructs a new MyCustomResource object.
             */
            public function __construct(array $configuration, $plugin_id, $plugin_definition) {
              parent::__construct($configuration, $plugin_id, $plugin_definition);
            }

            /**
             * Responds to GET requests.
             *
             * @param \Symfony\Component\HttpFoundation\Request $request
             *   The request object.
             *
             * @return \Drupal\rest\ResourceResponse
             *   The HTTP response object.
             */
            public function get(Request $request) {
              $data = [
                'message' => 'Hello, welcome to our custom REST API!',
                'status' => 'success'
              ];
              return new ResourceResponse($data);
            }
          }
      
    

Here, you define your REST resource using @RestResource annotation, specifying ID, label, and URI paths. The get() method processes GET requests, returning a simplified JSON response.

Testing Your REST Resource Plugin

Enable your module and test the REST endpoint:

      
          drush en my_rest_module -y
      
    

Access your endpoint via a web client, sending a GET request to /api/v1/custom-resource to see the JSON response in action.

Conclusion

You’ve successfully defined a simple custom REST resource plugin within Drupal. This setup forms the backbone of your REST API, enabling HTTP request handling to expose data or functionality. Extend this example by handling other HTTP methods like POST and DELETE, or by connecting more complex data structures.

What's Next?

In our next lesson, we will explore the process of Setting Up Routes and Methods for REST APIs. This will deepen your understanding of how to handle different types of API interactions, further enhancing the functionality and reach of your Drupal API.