The Other Side of the Request

Why build one after consuming several. Everything that annoyed you as a client is a decision someone made as a server. Inconsistent shapes, a count that lies, no way to page, errors that arrive as HTML. You now know what those cost, which is the right moment to design your own.

The decisions, in order.

Wrap your results in an object rather than returning a bare array, so there is room for a count and paging later. A bare array is a promise you cannot change.

Use status codes properly: 200 for success, 404 for absent, 400 for a bad request.

Return errors as JSON with the same shape every time.

Name your fields explicitly rather than serializing whole records, which is how private fields leak.

Document the five things you wished your sources had documented.

◈ Graded Challenge

Write respond(records, page, per_page) shaping an API response the way you would want to receive one. Return an object with four keys: count, the total number of records; page, the page requested; total_pages, the number of pages needed to hold every record, which is 1 when there are no records; and results, only that page's records. Pages start at 1. A page beyond the end returns an empty results list rather than an error.

Name it exactly: respond(records, page, per_page)

3 visible + 4 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Documenting It →
← Back