HackerNoon.com
Published in

HackerNoon.com

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

By ADCI Solutions

Several ways to create and send data in the JSON format in Drupal 8

Good news! You do not need to write code or download additional modules to configure the sending of a JSON data using REST and to customize a JSON array. Everything you need is already in the core of Drupal 8. First of all, you need to install the Views and Rest modules and determine an exported content type. If you have never worked and are not familiar with the Rest module, I recommend that you familiarize yourself with this guide before reading the rest of the article.

Send the JSON data with REST and Views

Step 1

Create a new view
Choosing the style of content in view
Choose how this view should be styled
Style options — json
How the view should look like in the end
JSON result in the chrome plugin

Send the JSON data programmatically with Normalizer

With Views, you can customize a JSON array and specify only the certain fields that will be returned. But what if your application needs to receive the JSON array in a specific form that you can not configure in Views? You can take advantage of Normalizer. In the custom module, we create the file “services” and necessarily set the priority higher or equal to 2, so that a custom normalizer is executed with the highest priority. Otherwise, nothing will work.

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.

Conclusion

I showed you several ways how you can work with REST and JSON in Drupal 8, each of them was useful to me to some extent and I hope that they will reduce the time to find a solution to a particular problem.

--

--

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
ADCI Solutions

We help businesses thrive online and get to the market faster than their competitors. https://www.adcisolutions.com/