Skip to content

Working With an Individual Recipe

In our examples thus far we have been working with JSON:API collections, which include multiple resources of a specific type. Next we’ll look at methods provided by the client that allow you to work with individual resources.

If you know the id of the recipe you are looking for, you can use the getResource method to retrieve it. For example, if you used getCollection elsewhere in your application to get a list of all recipes, you likely already know the id of any individual recipe you want to retrieve.

Below we’ll use getResource to display the instructions for a recipe with the id ‘6bf4b5b1-08c6-4c16-8a6d-b9af5af4ed04’.

---
import { JsonApiClient } from "@drupal-api-client/json-api-client";
import { Jsona } from "jsona";
const client = new JsonApiClient(
"https://drupal-api-demo.party"
);
const recipe = await client.getResource(
"node--recipe",
"6bf4b5b1-08c6-4c16-8a6d-b9af5af4ed04",
);
---
<h2>{recipe.data.attributes.title}</h2>
<div set:html={recipe.data.attributes.field_recipe_instruction.processed} />

As we saw above, using getResource requires us to know the id of the resource we intend to retrieve. There will likely be cases where your front end application knows the requested path, but doesn’t know the id of the resource in Drupal that it should resolve to. In these cases the getResourceByPath method allows you to retrieve a single resource by providing the path instead of the id.

Let’s adapt our example of rendering an example article to use getResourceByPath.

---
import { JsonApiClient } from "@drupal-api-client/json-api-client";
import { Jsona } from "jsona";
const client = new JsonApiClient(
"https://drupal-api-demo.party"
);
const recipe = await client.getResourceByPath(
"/recipes/deep-mediterranean-quiche"
);
---
<h2>{recipe.data.attributes.title}</h2>
<div set:html={recipe.data.attributes.field_recipe_instruction.processed} />