How to send the JSON data from a Drupal 8 site?

Send the JSON data with Controller

However, redefining an array through normalizers can be too inconvenient if you need to get the absolutely custom JSON array from a specific path. In addition, an override of the normalizer will affect the JSON structure of all the nodes of this content type, that’s why you can use a simpler method: you can always send the JSON data using the controller having adjusted this data to a certain path. And this method can really help to solve a more specific problem, for example, in my case, it was necessary to place all the nodes in the common array, which is very difficult or even impossible to achieve through a view. You can learn how to create a custom module with a controller in this article.

First, create a routing file and assign a path which will use the GET method to get JSON.

The controller file will look like in the code sample below. Using the custom method in the controller and JSONResponse, we can send the JSON array exactly as we want it to.

Here we do not use hardcoded Symfony and the Rest module methods in order to change the JSON array but create our own.

Facebook Comments

More Stuff

Torque Toons: Super Gutenberg Cloud In case you missed it, developers recently announced Gutenberg Cloud, a new way for WordPress and Drupal users to create their custom Gutenberg conten...
Maintaining Application Compatibility With version 11.28 of cPanel & WHM making it’s way into the production update tiers, now is a great time to discuss your application testing strat...
Upcoming Improvements to LivePHP This past week, we have been working to improve livePHP. For those of you not familiar with livePHP, it is a PHP class that allows access to the cPane...
Spread the love

Posted by News Monkey