Relations in an API

A relation is data that's connected, such as a book and its author. A relation can be sent in three ways: link (id only, the client fetches it), embed (always…

The Bookshop list page shows 8 books, each with its author's name. How many requests does it take to show them? It could be 1, or it could be 9. It all depends on how the API sends the authors.

A book has an author, a book has reviews. Data that's connected like this is called a relation. The API has to decide how to send it: is the author put inside the book, or does the client fetch it from another address? It's like ordering food over the phone. First way: the restaurant only reads out menu numbers, and you have to call again for every number to learn its name. Second way: they read out everything at once, ingredients and cooking method included, though you only needed the names. Third way: you say at the start "tell me the names too, please", and you get only what you asked for. In the API, the menu number is author_id, the dish's name is the author's name, and the ingredients and cooking method are data you don't need, such as reviews. The three ways of ordering match the three ways below: link, embed and optional include.

Three ways to send a relation

The data: the 8 books from the previous lessons, 4 authors, and 6 reviews. Each review belongs to one book, and that book's id is written in book_id. Here is how GET /books/1 answers in each way:

Way GET /books/1 answers The author
Link (id only) {"data": {"id": 1, "title": "The Rainbow Troops", "author_id": 1, ...}} the client fetches it from GET /authors/1
Embed (put inside the book) {"data": {..., "author": {"id": 1, "name": "Andrea Hirata"}}} always included
Optional include the same as embed, but only when asked for with ?include=author included when asked

Nested resources: data that belongs to its parent

A review always belongs to one book, so its address is written under the book's address: GET /books/1/reviews means "the reviews that belong to book 1". This is called a nested resource. Another example: the comments that belong to post 3 are at GET /api/posts/3/comments. Here is the route for a book's reviews:

app.get("/books/:id/reviews", (req, res) => {
  const bookId = Number(req.params.id);
  if (!books.some((b) => b.id === bookId)) {
    return res.status(404).json({ error: "Book not found" });
  }
  const data = reviews.filter((r) => r.book_id === bookId);
  res.json({ data, total: data.length });
});

One level of nesting is enough: collection/id/collection. GET /api/posts/3/comments/7/likes/12/users is nested too deep: the client has to know the post, the comment and the like all at once, while like 12 already has its own id. Split it into a separate endpoint, for example GET /api/likes/12/users.

Embed: the author inside the book

With an embed, the server finds the author, then puts it inside the book:

app.get("/books/:id", (req, res) => {
  const book = books.find((b) => b.id === Number(req.params.id));
  if (!book) return res.status(404).json({ error: "Book not found" });
  const author = authors.find((a) => a.id === book.author_id);
  res.json({
    data: {
      id: book.id,
      title: book.title,
      price: book.price,
      author: { id: author.id, name: author.name },
    },
  });
});

Optional include with ?include=

An embed that's always there has a downside too. The list page needs the authors' names, but not the reviews. If the server always embeds the author and the reviews, the body of the 8-book list grows to 1,551 bytes, while the authors alone need only 934 bytes. On a server with a database, every embedded relation is also an extra query. So the reason to include relations optionally is performance: the client only carries the data size and the queries of the relations it asks for. Here is the list endpoint with an optional include:

const INCLUDABLE = ["author", "reviews"];

app.get("/books", (req, res) => {
  const include = req.query.include ? req.query.include.split(",") : [];
  if (include.some((name) => !INCLUDABLE.includes(name))) {
    return res.status(400).json({ error: "include must be one of: author, reviews" });
  }
  const data = books.map((book) => {
    const item = { ...book };
    if (include.includes("author")) item.author = authors.find((a) => a.id === book.author_id);
    if (include.includes("reviews")) item.reviews = reviews.filter((r) => r.book_id === book.id);
    return item;
  });
  res.json({ data });
});

N+1 at the API level

When the API only gives author_id, the list page's code needs a loop like this:

const { data: books } = await (await fetch("/books")).json();
for (const book of books) {
  const { data: author } = await (await fetch(`/authors/${book.author_id}`)).json();
  book.author = author;
}

const { data: books } takes data from the JSON answer and names it books. One request for the list, then one more request for each book: 1 + 8 = 9 requests. It's the same N+1 problem as in the lesson Querying the Database from an API, only now it happens between the client and the API. If one round trip over a phone network takes 100 milliseconds, that loop waits about 900 milliseconds. If the client remembers the authors it already fetched, the count drops to 1 + 4 = 5, since there are only 4 authors. With GET /books?include=author, 1 request is enough.

Way, list page of 8 books Requests Body received
Link, a loop per book 9 926 bytes
Embed authors and reviews 1 1,551 bytes
?include=author 1 934 bytes

On the server side, don't do include=author with a query per book either. Fetch all the authors in one query, with WHERE id IN (...) (the rows whose id is in the list) or a JOIN. The N+1 Problem & Eager Loading lesson of the Database track shows how.

📌 In Laravel: API Resources

In Laravel, the JSON shape is written in a Resource: a class that sets the JSON shape of a model (the data from one table). Resources are covered in the API Resource lesson of the Laravel track. Here is a Resource for a student and their classroom relation:

class StudentResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'classroom' => new ClassroomResource($this->whenLoaded('classroom')),
        ];
    }
}

⚠️ Too deep, too much, too often

TL;DR: A relation is data that's connected, such as a book and its author. A relation can be sent in three ways: link (id only, the client fetches it), embed (always put inside the data), or optional include (?include=author,reviews, embedded when asked for). Data that always belongs to its parent uses a one-level nested resource, an address under its parent's address, like /books/1/reviews or /api/posts/3/comments. /posts/3/comments/7/likes/12/users is nested too deep. With an embed, pick the fields one by one (author: { id, name }). Include is optional for performance: every relation adds bytes and queries, so the client only carries what it asks for. Links with no include push the client into N+1 at the API level (one request for the list, plus one per book): 8 books = 9 requests, with include just 1. In Laravel, $this->classroom reads a student's classroom relation, and $this->whenLoaded('classroom') embeds it only when it was loaded with with('classroom').

⚡ Three ways to send a relation

Meaning: A relation is data that's connected, such as a book and its author. There are three ways to send it. A link sends only author_id, and the client fetches the author itself. An embed always puts the author inside the book. An optional include embeds it only when asked for, such as ?include=author.

⚡ Embed: the author inside the book

Write:

const author = authors.find((a) => a.id === book.author_id);
res.json({
  data: {
    id: book.id,
    title: book.title,
    price: book.price,
    author: { id: author.id, name: author.name },
  },
});

Meaning: authors.find(...) finds this book's author through book.author_id, and the author is then put inside the book. The fields are picked one by one, inside author too. If the authors table has an email, that field doesn't go out.

⚡ N+1 at the API level

Guess first: a list page shows 8 books with their authors' names, but the API only gives author_id. How many requests does it need?

Nine. One for the list, then one more for each book. With GET /books?include=author, 1 request is enough.

Meaning: It's the same N+1 problem (N = the number of books) as in the lesson Querying the Database from an API, only now it happens between the client and the API.

⚡ Optional include for performance

Meaning: If the author and the reviews are always embedded, the body of the 8-book list grows to 1,551 bytes, while the authors alone need only 934 bytes. Every relation adds a query too. With an optional include, the client only carries the data size and the queries of the relations it asks for.

What you will learn