Creating a JSON response
Routes can also return JavaScript Object Notation (JSON) responses. A JSON response is often used for building API routes since it is an interchange format that is supported by all programming languages. This allows exposing data to be consumed by a third-party consumer.
In this recipe, we will create a route that returns a JSON response containing information about the Drupal site.
How to do it…
- First, we need to create the
src/Controller
directory in the module’s directory. We will put our controller class in this directory, which gives our controller class theController
namespace:mkdir -p src/Controller
- Create a file named
SiteInfoController.php
in theController
directory. This will hold ourSiteInfoController
controller class. - Our
SiteInfoController
class will extend theControllerBase
base class provided by Drupal core:<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony...