Many APIs use nested resource URL paths to express relationships. An example of a nested resource URL path is /contacts/1/pets, where the collection of pet resources returned from this endpoint belongs to the contact resource with an id of 1. These endpoints are often referred to as relationship links, and Ember Data knows how to use them to load relationships. Let’s look at the default behavior of how Ember Data uses relationship links in response payloads. Then, we will look at how to tell Ember Data about relationship links if they aren’t present in an API.
The code for this chapter can be found in the chapter-7 folder of the source code for this book.
How Relationship Links Work
Ember Data supports relationship links out of the box for both the RESTAdapter and the JSONAPIAdapter. In this section, we will specifically look at relationship links with the RESTAdapter and RESTSerializer, but the same ideas apply when using JSON:API.
If we access contact.pets or contact.company, Ember Data will trigger a fetch using the URLs defined in links. As noted in the API documentation:
The format of your links value will influence the final request URL via the urlPrefix method: Links beginning with //, http://, https://, will be used as is, with no further manipulation. Links beginning with a single / will have the current adapter’s host value prepended to it. Links with no beginning / will have a parentURL prepended to it, via the current adapter’s buildURL.
Lots of APIs offer endpoints that follow a nested resource URL path convention, but don’t return them in the links property in a resource. Let’s find out how we can tell Ember Data about these endpoints.
When APIs Don’t Return Relationship Links
In the previous chapters, we learned about the different normalization methods in serializers that allow us to intercept a payload before Ember Data uses it. To handle the missing links property, we can override one of the many normalization methods.
And that’s really it! Pretty simple huh?
As mentioned earlier, JSON:API uses links too, but the response format is a little different. If you do find yourself needing to manually add links when using JSON:API, the process is similar to the example in this chapter. Visit the JSON:API specification on links1 for more details.
Summary
Now that we know how to work with relationship links, let’s move on and learn about the different ways we can work with nested data.