Setting up routes and methods for REST APIsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

In our ongoing journey of Drupal module development, an essential component we've touched upon is the creation of RESTful APIs. In this installment, we’ll focus on setting up routes and methods for these APIs. Understanding this process is key to handling different HTTP behaviors and ensuring your REST endpoints can efficiently process and respond to client requests.

Understanding Routes and HTTP Methods in REST APIs

In Drupal, routes play a critical role in mapping URLs to specific callback logic. They determine how requests are processed and interacted with, while HTTP methods define the operations (such as GET, POST, PUT, DELETE) available for API endpoints.

For example, a GET method might retrieve data, whereas a POST method could submit data for server-side processing. Being able to configure these elements provides you with the flexibility required in modern API development.

Creating Routes for Your REST API

Start by ensuring your custom module is set up, as we've done in previous lessons. We'll extend this to include a custom route:

Step 1: Define Routes in a YAML File

Routes in Drupal are defined in YAML files. For our module, create a file named my_rest_module.routing.yml in your module's root directory. Inside this file, define your custom API routes:

      
          my_rest_module.get_custom_resource:
            path: '/api/v1/custom-resource/{id}'
            defaults:
              _controller: '\Drupal\my_rest_module\Controller\CustomResourceController::get'
              _title: 'Retrieve Custom Resource'
            requirements:
              _permission: 'access content'
              id: \d+
            methods: ['GET']

          my_rest_module.post_custom_resource:
            path: '/api/v1/custom-resource'
            defaults:
              _controller: '\Drupal\my_rest_module\Controller\CustomResourceController::post'
              _title: 'Create Custom Resource'
            requirements:
              _permission: 'access content'
            methods: ['POST']
      
    

Here, we define two routes: one for GET requests to fetch data from a resource, and another for POST requests to create new data. Each route specifies a path, controller, and HTTP method, as well as requirements such as permissions and parameter validation.

Implementing the Controller

Next, create a controller that will handle requests routed to these paths. In src/Controller directory, create CustomResourceController.php:

      
          <?php
          namespace Drupal\my_rest_module\Controller;

          use Drupal\Core\Controller\ControllerBase;
          use Symfony\Component\HttpFoundation\JsonResponse;
          use Symfony\Component\HttpFoundation\Request;

          class CustomResourceController extends ControllerBase {

            /**
             * Returns custom resource data.
             */
            public function get($id) {
              // Mock retrieval of resource data.
              $data = [
                'id' => $id,
                'name' => 'Sample Resource',
                'description' => 'This is a mock resource description.'
              ];
              return new JsonResponse($data);
            }

            /**
             * Handles resource creation.
             */
            public function post(Request $request) {
              // Example handling of POST data.
              $data = json_decode($request->getContent(), TRUE);
              // Ideally, implement validation and data storage logic here.
              return new JsonResponse([
                'message' => 'Resource created successfully!',
                'submitted_data' => $data,
              ]);
            }
          }
      
    

This controller defines two methods to process incoming requests mapped via routing configuration. The GET method retrieves mock data associated with an ID, while the POST method processes submitted data, typically storing it in a database.

Testing Your API Endpoints

With your routes and methods defined, enable your module and test the endpoints using tools like Postman to send HTTP requests. Verify that the GET and POST routes work as expected and properly handle data as configured.

      
          drush en my_rest_module
      
    

Test the GET request by accessing http://yourdrupalsite.com/api/v1/custom-resource/1 to retrieve the resource with ID 1. Test the POST request by sending JSON data to http://yourdrupalsite.com/api/v1/custom-resource.

Conclusion

You have now learned how to set up custom routes and handle various HTTP methods in Drupal, enabling you to build comprehensive and flexible REST APIs. This capability expands your modules' functionality and improves data interactions across platforms.

What’s Next?

The next crucial step in securing your REST APIs is adding authentication. In our next session, we will explore how to implement authentication using OAuth and JWT, ensuring secure communication and data protection across your API services.