JSON API: A Summary

Chris Wright
January 24, 2017
Illuminated dome ceiling

For the past several weeks I have been working on a project using Drupal 8 and it's built in REST API. A coworker of mine suggested that we switch to using the JSON API as well/instead. I was reluctant at first until I saw how awesome JSON API is.

JSON API is the droids you have been looking for. It is the answer to most of your Drupal 8 API issues. Let me share with you just why JSON API will change your life. JSON API is a standard that we should all begin to use and follow. It provides an easy to learn format to your JSON responses using REST API. You can find the docs on their site and you can also download the Drupal module.

JSON API works out of the box. Yes, I said it. It works out of the box, no strings attached. You turn it on and you can hit its default endpoints and view content returned to you in JSON formatted very nicely. Drupal 8’s default REST API gives you some endpoints to hit but JSON API provides a much cleaner output as well as gives you access to more content, filters and sort options than is provided by default. If you are trying to view any type of content, the method is simple.

Your site's URL/jsonapi/{bundle}/{entity} with a Content-Type of application/api_json as a header in your request and a format of api_json or ?_format=json. So if you wanted to return all basic pages, you would request URL/jsonapi/node/basic_page?_format=api_json. That will return every basic page. JSON API also has many parameters you can pass in. You can filter/sort your request based on certain fields in the requested content. You can set it to only show certain fields instead of returning all of the fields on the content.

You can include entity-relationships which is very handy. Meaning, that if you have an entity-reference field in your content, it will return to you the target_id of the referenced content. This is undesirable because you cannot simply display that content unless you do an entity::load with the target_id and that gets very complicated and convoluted very fast. This is why JSON API lets you “include” relationships in your request and it will actually return that referenced content to your as well as the default content you are requesting.

However, if you need to do some custom endpoints that do logic or aggregation, you may need to create those yourself as JSON API is mainly built for retrieving content. It is powerful though, and is way better than Drupal 8’s default response.

These are some reasons why JSON API is awesome. Stay tuned for JSON API: Relationships.