JSONAPI: Relationships and Includes

Scroll Down

Written by Chris Wright

July 25, 2017

JSONAPI: Relationships and Includes

In my last blog, I briefly showed some of the things JSONAPI can do.

Say you want the image to be returned with your blog. By default, field_image is a file reference, which means it will actually only return the target_id of the referenced file. This is the same for comments, user-reference, node-type, revisions and entity-reference fields. Logically, this would mean you would need to either do a GET on the node and then again on each reference. Either that, or you would need to programmatically load each entity or file with its’ target_id to be returned in the output. This isn’t the best practice as you would need to make several calls just to gain access to an image or some other form of reference content.

This is where JSONAPI comes in. In the return object of your entity, there is a space called “relationships”. This will include links for each reference-field. There is a “self” link that describes or gives you information about the referenced field-type and a “related” link that when called will return that referenced object.

However, if you want to limit the amount of calls you’re making, you can use includes. Includes are pure magic. They will basically include whatever referenced objects you specify in the original return object. The syntax is just ?include={referenced_field}. If you wanted to include the comments on your blog page in the call, you would simply add ?include=comments. This will return the comments object referenced at the bottom of your return object. The best part is you can include referenced content inside of referenced content. In order to include content referenced, you would use a dot-separated list.

So you could include the comments on a blog, but also include the comments’ authors’ information.

?includes=comments.author

If you wanted to go deeper, you could even reference the comments’ author's’ image.

?includes=comments.author.field_image

You can include as many referenced fields as you want using a comma separated list. If you need to include the blogs’ image, comments and an entity-reference field, you would add them all in the same line, just separating each separate “call” with a comma. This makes including images and other content a breeze with the JSONAPI.