Using JSON:API Parameters
Previously, we saw that our recipe did not include all of the data for our image field, only an ID for the referenced entity.
JSON:API accepts a number of query string parameters to modify the response, for things like filtering, sorting, pagination, including related data, and restricting the fields that are returned. This makes it possible for us to include the desired image data in the response.
Let’s look at how we can add the necessary parameters to requests made by the JSON:API Client.
The queryString Option
Revisiting our call to getCollection
, we can add an options object as the second argument to the method. This object can include a queryString
property, which will be added to the resulting fetch request.
To include the field_media_image
field, we could use the following query string: include=field_media_image
If we examine the resulting recipes object, we’ll now see an included
property which contains the data referenced by the field_media_image
field. However, the image data is still incomplete because this media entity references file entities and we need to include that data as well. For our grid, we specifically want the thumbnail image file.
Thankfully, the include parameter allows us to follow these relationship paths with a value like: include=field_media_image.thumbnail
Looking at the data returned, you’ll now see that the referenced thumbnail files are also part of the included
array.
Generating query strings with drupal-jsonapi-params
The drupal-jsonapi-params package provides a convenient way to generate query strings for more complicated JSON:API
requests. The example below demonstrates how to use this package to generate the include
query string we used earlier, and also adds a filter for titles containing ‘chocolate’ to the request.
Adding images to recipe cards
Now that we have retrieved all of the data we need, we can update our recipe grid to include images.
Umami Recipes
Deep mediterranean quiche
Difficulty: medium
View RecipeVegan chocolate and nut brownies
Difficulty: medium
View RecipeSuper easy vegetarian pasta bake
Difficulty: easy
View RecipeWatercress soup
Difficulty: easy
View RecipeVictoria sponge cake
Difficulty: easy
View RecipeGluten free pizza
Difficulty: medium
View RecipeThai green curry
Difficulty: medium
View RecipeCrema catalana
Difficulty: medium
View RecipeFiery chili sauce
Difficulty: easy
View RecipeBorscht with pork ribs
Difficulty: medium
View RecipeYou may have noticed that traversing entity relationships to determine the image path in the above example required a number of steps.
The JSON:API Client can help with this as well. Next, we’ll adapt this example to deserialize the response in order to simplify the process of working with JSON:API relationships.