Designing endpoints for the UI

Intermediate · 6 min

Shape API endpoints around the screens that call them: one board endpoint, not five round trips, plain resources for writes, and how to cope as screens change.

Before thisDesigning the schema from featuresShaping queries for screens

ByteByteGo · 6 min

Designing endpoints for the UI

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ByteByteGoReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Design reads around screens and writes around resources: one endpoint can return everything a screen needs, while each change goes to the resource it changes.
  • A chatty UI that needs five requests to paint one screen is slow on a phone, because every request pays a full network round trip.
  • Putting derived values such as per-status counts into the screen endpoint saves the client from fetching every row just to count it.
  • An endpoint that returns 404 for someone else's project, instead of 403, avoids confirming that the project exists.
  • Shaping endpoints to screens has a cost: when a screen changes, the endpoint changes with it, so keep the shape in one place and let other clients use the plain resources.

The screen is the customer

REST tutorials start from nouns: users, projects, tasks. That is a good way to model data and a poor way to decide what the browser should call. The browser does not want a task. It wants the board for Launch, with its tasks, grouped, with counts in the column headers, and it wants them now.

Think of a restaurant. The kitchen stores ingredients (your tables). The menu is what customers order from. Nobody should have to order flour, eggs and butter separately and assemble the cake at the table. The endpoint is the menu item.

The schema you designed earlier and the queries you shaped for screens set this up. This lesson is where those shapes get a URL and a contract.

One round trip for a screen

Here is the Taskboard board screen built the “pure resource” way:

  1. GET /api/projects/1 for the name.
  2. GET /api/projects/1/tasks for the rows.
  3. Count the statuses in the browser.

That is two requests, and it gets worse the moment the screen also wants assignee names or comment counts. Each extra request pays a full network round trip: on a 150 ms mobile connection, three sequential calls cost nearly half a second before any rendering happens.

So Taskboard has one read shaped for the screen:

.get("/api/projects/:id/board", requireUser, (c) => {
  const p = db.prepare("select * from projects where id=?").get(c.req.param("id"));
  if (!p || p.owner_id !== c.get("userId"))
    throw new ApiError(404, "not_found", "Project not found");
  const tasks = db.prepare("select id,title,status from tasks where project_id=? order by id").all(p.id);
  const counts = { todo: 0, doing: 0, done: 0 };
  for (const t of tasks) counts[t.status]++;
  return c.json({ project: { id: p.id, name: p.name }, tasks, counts });
})

I ran this against a seeded project. The response was:

{"project":{"id":1,"name":"Launch"},"tasks":[{"id":1,"title":"Design","status":"todo"},{"id":2,"title":"Build","status":"todo"},{"id":3,"title":"Ship","status":"todo"}],"counts":{"todo":3,"doing":0,"done":0}}

One request, one query’s worth of data, nothing the screen has to stitch together. (In a real app the counts would come from a group by rather than a loop, and tasks would be paginated; the next group of lessons covers that.)

Writes go to resources

Reads are shaped for screens. Writes are not. Creating a task is POST /api/projects/:id/tasks, moving it is PATCH /api/tasks/:id, deleting it is DELETE /api/tasks/:id. Three reasons to keep writes plain:

  • Validation has one home. The createTask schema belongs to the task resource, whichever screen sends it.
  • Other clients exist. A mobile app, a CLI or an integration wants to create a task without knowing what your board page looks like.
  • Caching and retries. A PATCH to one task is easy to reason about, to retry, and to invalidate against. A “save the whole board” endpoint is not.

The rule of thumb: a screen-shaped endpoint is a read-only view over resources, never a second way to write them. If the board needs to show something that changed, the write goes to the resource and the view is re-fetched. REST resource modeling and URI design covers the naming rules for the resource side.

Ownership belongs in the endpoint

Look at the first if in the handler. A user asking for a project that is not theirs gets a 404, not a 403. I confirmed this with a second account: it received {"error":{"code":"not_found","message":"Project not found"}} [404], the same answer as for a project id that was never created.

403 says “this exists and you may not have it”, which tells an attacker which ids are real. Which answer you pick is a product decision, and for private data 404 is the safer one. The longer discussion of who may do what is in authorization in the API and the UI.

When the screen changes

Screen-shaped endpoints have a cost, and it is worth stating plainly. When design adds an avatar to each card, the endpoint changes. When there are three clients with three layouts, you get three endpoints or one bloated one.

Two ways out, and neither is free:

  • Keep the shape in one module. All the board’s SQL and mapping live next to the route, so a screen change is a one-file change, not a hunt.
  • Let the client choose fields. Query-string field selection (?include=assignee) is a small version of what GraphQL does generally. If you find yourself building many of those, read working with GraphQL and decide whether you are reinventing it.

For a team of one or two people with one web client, a handful of screen endpoints plus plain resources is the right amount of machinery.

Versioning is easier than it sounds

Because one team ships the client and the server together, you can change an endpoint and its caller in the same pull request. The moment a client you do not control exists, such as an old mobile build, you need a policy. API versioning strategies is the place for that; for now, add fields rather than renaming them, and old clients keep working.

What the video covers

ByteByteGo’s “Good APIs Vs Bad APIs: 7 Tips for API Design” is under six minutes, published February 2024. Its description credits an engineering blog post and does not list chapters, and I could not read a transcript, so I will not claim which seven tips it gives. It is a general API design video, not a UI-specific one. The screen-first angle in this lesson is mine, not the video’s. ByteMonk’s “9 Must-Know REST API Design Principles” is linked as a longer second view; its description frames it around Java, but the principles are language-neutral.

Where this fits

You now have endpoints with a shape. The next question is how the client knows that shape without someone retyping it by hand. Next: end-to-end type safety.

Check yourself

  1. 01Why does Taskboard have both GET /api/projects/:id/board and plain task resources?

    The board endpoint is a read shaped for one screen so it paints in a single round trip, while the task resources are what writes address, so each change has one obvious place to go.

  2. 02What goes wrong if the board screen builds itself from GET /projects/1, GET /projects/1/tasks and one request per task for details?

    The screen waits on several sequential or parallel round trips, and on a slow connection the latency adds up before anything useful is visible.

  3. 03Why return counts from the server instead of counting tasks in the browser?

    Once pagination exists, the browser only has a page of tasks, so a count taken there would be wrong, and the database can count without sending every row.

  4. 04Why 404 and not 403 when a user asks for a project they do not own?

    A 403 tells the caller the project exists, which leaks information, while a 404 gives the same answer as a project that was never created.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark