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/Controllerdirectory in the module’s directory. We will put our controller class in this directory, which gives our controller class theControllernamespace:mkdir -p src/Controller
- Create a file named
SiteInfoController.phpin theControllerdirectory. This will hold ourSiteInfoControllercontroller class. - Our
SiteInfoControllerclass will extend theControllerBasebase class provided by Drupal core:<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony...