Formatting REST output as JSONfor Drupal 8 , 9 , 10 , and 11

Last updated :  

As you progress in developing modules in Drupal, formatting REST API output as JSON becomes critical for interoperability. JSON (JavaScript Object Notation) is the data exchange format favored for its simplicity and efficiency in web applications. This lesson will guide you through configuring your Drupal REST endpoints to deliver structured JSON responses efficiently.

Why Use JSON for REST APIs?

JSON has become the de facto standard format for REST APIs due to its human-readable structure and ease of use in various programming environments. Its lightweight nature makes it perfect for data interchange between servers and clients, significantly reducing payload sizes compared to alternatives like XML.

Preparing Your Module Environment

Ensure you have a custom module created, as established in previous lessons. Verify that essential dependencies like the REST and Serialization modules are enabled:

      
          drush en rest serialization -y
      
    

These modules enable Drupal to handle RESTful requests and output serialized data formats, including JSON, as per your configuration.

Configuring REST to Output JSON

Let's modify your existing custom REST resource plugin to ensure it outputs JSON. Assuming you have a basic REST resource set up, as discussed in earlier lessons, let's refine your resource class:

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

          <?php

          namespace Drupal\my_rest_module\Plugin\rest\resource;

          use Drupal\rest\RestResourceBase;
          use Drupal\rest\ResourceResponse;
          use Symfony\Component\DependencyInjection\ContainerInterface;
          use Drupal\Core\Entity\EntityStorageInterface;

          /**
           * 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 {

            /**
             * Responds to GET requests.
             *
             * @return \Drupal\rest\ResourceResponse
             *   The HTTP response object.
             */
            public function get() {
              $data = [
                'id' => 1,
                'name' => 'Sample Item',
                'status' => 'active',
                'description' => 'A sample item for demonstration purposes.'
              ];
              return new ResourceResponse($data);
            }
          }
      
    

Observe how the @RestResource annotation includes serialization_class set to handle JSON. This ensures the output from this resource is serialized into JSON format.

Handling Complex Data Structures

Your REST resources might need to return more complex structures, such as lists or deeply nested data. Modify your data arrangement in PHP arrays or objects, as shown below:

      
          $data = [
            [
              'id' => 1,
              'name' => 'First Item',
              'status' => 'active',
            ],
            [
              'id' => 2,
              'name' => 'Second Item',
              'status' => 'inactive',
            ]
          ];
      
    

These arrays are automatically serialized into JSON arrays preserving the internal data structure through Drupal's serialization mechanisms.

Testing Your JSON Output

To validate your REST setup, test the output of your API using tools like Postman or cURL. These tools help you verify JSON response structure by hitting your endpoints and analyzing the returned data.

      
          // Example using cURL
          curl -X GET http://yourdrupalsite.com/api/v1/custom-resource
      
    

Check if the output is properly formatted JSON and that all expected data is present and correct.

Improving JSON Output with Response Metadata

Enhance your JSON responses by adding metadata such as response codes and cache instructions. Leveraging HTTP headers provides additional context to the API consumer:

      
          $response = new ResourceResponse($data);
          $response->addCacheableDependency($data);
          return $response->setStatusCode(200);
      
    

This approach not only gives a structured JSON response but also strategically controls caching and status messaging.

Conclusion

Mastering JSON response formatting in Drupal allows you to build versatile and standards-compliant APIs, facilitating seamless data-sharing with varied clients. With straightforward serialization configuration, you can easily adapt your custom modules to meet robust RESTful data interchange requirements.

What’s Next?

Formatting restful output enhances the client-server data synergy. Up next, we delve into Adding Filters to REST Resources to refine data queries and client-side management, optimizing how clients interact with your RESTful service.