We’ve already seen the fundamentals of JSON:API and how to filter, but now we’re still missing a very important functionality: how to get the values of referenced fields with the same query.
With a traditional REST API, if we have an endpoint that returns a list of recipes and the recipes have categories, it’s common for the recipe endpoint to only contain the category ID. The same would happen with the user – we’d only have the user ID and not the fields we’re actually interested in (name, surname, etc.). Once we have the ID, we’d use the corresponding endpoint to get the necessary information.
This would mean one general request for recipes, then n requests for users and m requests for categories, where n would be the number of users to query and m the number of categories (unless the endpoint supported querying multiple items at once). This results in many queries, and the solution would be to create a custom endpoint that returns all this data directly.
With JSON:API this isn’t necessary, as we can simply include the references in the same query by adding parameters to the URL. The parameter we need to use is:
include=field_to_include
For example, in our recipe JSON we can see several referenced fields: field_recipe_category, field_image, and as you can see in the JSON, there’s a “relationships” field within each item that only contains the type and ID in the data. With just that information, it’s not enough for us.
With the code we saw earlier, in our case we need to put:
include=field_recipe_category,field_image
So it would look like this:
https://drupaldemo.omitsis.com/es/jsonapi/node/recipe?include=field_recipe_category,field_image
If you click on the link, you’ll see that at the end of the document there’s a new JSON item called “included” – that’s where all the included related entities will be, with all their fields.
We could also get the reference of a reference. For example, if we had a comments field and wanted to also have the information of the comment authors, we would simply need to add this:
include=field_comments.uid
As you can see, it’s very powerful, but you also need to be careful – if you include too many relationships, the necessary queries might become too heavy and take a long time. Always experiment and maintain a balance.