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.
Getting a recipe using getResource
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’.
Deep mediterranean quiche
- Preheat the oven to 400°F/200°C. Starting with the pastry; rub the flour and butter together in a bowl until crumbling like breadcrumbs. Add water, a little at a time, until it forms a dough.
- Roll out the pastry on a floured board and gently spread over your tin. Place in the fridge for 20 minutes before blind baking for a further 10.
- Whilst the pastry is cooling, chop and gently cook the onions, garlic and courgette.
- In a large bowl, add the soya milk, half the parmesan, and the eggs. Gently mix.
- Once the pastry is cooked, spread the onions, garlic and sun dried tomatoes over the base and pour the eggs mix over. Sprinkle the remaining parmesan and careful lay the feta over the top. Bake for 30 minutes or until golden brown.
Getting a recipe using getResourceByPath
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
.
Deep mediterranean quiche
- Preheat the oven to 400°F/200°C. Starting with the pastry; rub the flour and butter together in a bowl until crumbling like breadcrumbs. Add water, a little at a time, until it forms a dough.
- Roll out the pastry on a floured board and gently spread over your tin. Place in the fridge for 20 minutes before blind baking for a further 10.
- Whilst the pastry is cooling, chop and gently cook the onions, garlic and courgette.
- In a large bowl, add the soya milk, half the parmesan, and the eggs. Gently mix.
- Once the pastry is cooked, spread the onions, garlic and sun dried tomatoes over the base and pour the eggs mix over. Sprinkle the remaining parmesan and careful lay the feta over the top. Bake for 30 minutes or until golden brown.