Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Designing Resources and Endpoints

Relationships, Sub-resources and Actions

Model relationships in a REST API: nested versus flat URLs, sub-resources, embedding with include, actions that do not fit CRUD, bulk operations and async jobs.

Real data is connected: an author has books, an order has items, a post has comments. Plain CRUD on separate collections handles simple cases, but sooner or later you need to decide how to expose relationships, and how to handle operations that are not create/read/update/delete, such as "cancel this order" or "publish this article".

This lesson gives you rules of thumb for both problems, and shows a nested API and a background-job pattern in running code.

Nested or flat?

Take books and authors. You can expose the relationship in two ways:

HTTP
GET /authors/7/books        # nested: books of author 7
GET /books?authorId=7       # flat: books filtered by author

Neither is wrong. A good approach uses both:

  • Nested URLs for ownership and creation. If a child cannot exist without its parent (order items, comments on a post), nest it: POST /orders/9/items creates an item in order 9, and GET /orders/9/items lists them.
  • Flat collections for global access and filtering. If clients also need "all books regardless of author", give them /books with a filter.
flowchart TD
    A["/authors/7"] --> B["/authors/7/books"]
    B --> C["/books/42"]
    A -. "authorId filter" .-> D["/books?authorId=7"]

Nest to express containment; give important items their own top-level URL as well.

Keep nesting shallow

Deep nesting makes URLs long and brittle: /companies/3/departments/8/teams/2/members/15 forces clients to know four ids to reach one member. Aim for at most two levels. Once an item has a globally unique id, address it directly: /members/15.

Many-to-many relationships

Books and tags are many-to-many. Common patterns:

  • A sub-collection under one side: GET /books/42/tags.
  • Adding and removing links by id: PUT /books/42/tags/fiction (idempotent: adding twice changes nothing) and DELETE /books/42/tags/fiction.
  • Or treat the relationship as its own resource when it has data of its own: an enrollment linking a student and a course, with a grade and a date, becomes /enrollments.

Showing relations in a response

Three ways to represent a related resource inside a JSON response:

  1. By id: "authorId": "7". Smallest, clients fetch the author separately.
  2. By link: "links": { "author": "/authors/7" }. Self-describing.
  3. Embedded: the full author object inside the book. Saves a round trip but increases size.

Let the client choose with an include (or expand) parameter: GET /books/42?include=author embeds the author, and plain GET /books/42 returns only the id. This gives you the flexibility of GraphQL-style fetching in a small, cacheable form. The query-string rules are the same as in filtering and sorting: allow-list the names you support.

A nested API

Node.js Authors and their books

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Actions that are not CRUD

Sometimes the operation is a verb: cancel an order, publish an article, send a password reset email, merge two accounts. Four strategies, from most to least RESTful:

  1. Change a field with PATCH. If the action is really a state change, express it as one: PATCH /orders/9 with {"status": "cancelled"}. The server validates that the transition is allowed (a shipped order cannot be cancelled; answer 409).
  2. Model the action as a sub-resource. POST /orders/9/cancellation creates a cancellation, PUT /articles/5/publication publishes. The noun makes it easy to add data (a cancellation reason) and a history (GET /orders/9/cancellation).
  3. Use a verb sub-path with POST. POST /orders/9/cancel is pragmatic and common. Keep it to genuine actions and always use POST so it is never called by prefetching.
  4. Make the operation a resource of its own. POST /exports creates an export job, POST /payments creates a payment. This is the right fit when the action takes time or leaves a record.

Choose one style per API and be consistent. Whichever you pick, the result of an action should return the new state of the affected resource so clients do not need a second request.

Bulk operations

Sending 500 POST /items requests is slow. Options: a batch endpoint (POST /items/batch with an array), or one POST /items that accepts an array. Two design questions arise: should the batch be atomic (all or nothing) or partial (some may fail), and how do you report per-item results? A 207 Multi-Status style body with one status per item is a common answer for partial batches. Cap the batch size.

Long-running operations

If work takes more than a second or two (video encoding, report generation), do not hold the connection open. Accept the job and let the client poll:

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: POST /exports
    S-->>C: 202 Accepted + Location /exports/5
    C->>S: GET /exports/5
    S-->>C: 200 status=running
    C->>S: GET /exports/5
    S-->>C: 200 status=done + result link

202 means "accepted, not finished". The Location header is the status resource.

Node.js Async job with 202 and polling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL best expresses "books written by author 7"?

    A nested sub-collection under a real parent expresses containment clearly.
  2. 2. Why avoid URLs nested four or five levels deep?

    Prefer at most two levels and address items with a global id once it exists.
  3. 3. What does the include=author parameter do?

    include (or expand) lets clients opt in to embedded related resources.
  4. 4. A client starts an export that takes a minute. What should the server return?

    202 says the work was accepted but is not finished, and the status URL lets the client poll.
  5. 5. Which choice is the most pragmatic way to expose a "cancel order" action?

    Use POST (never GET) for actions, or model it as a state change with PATCH.

Summary

  • Nest to express containment (/orders/9/items), keep nesting to two levels, and give important items a top-level URL.
  • Show relations by id, by link or embedded, and let clients choose with include.
  • Express actions as a PATCH of a state field, as a sub-resource, as a POST verb path, or as a resource of their own.
  • Return 202 plus a status URL for long-running work, and cap and define semantics for bulk operations.

Next: Building an HTTP Server from Scratch