REST APIs
Resources and methods, correct status codes, consistent errors, offset vs cursor pagination.
Updated
What a REST API is
An API is the interface through which one program asks another for data. REST is the most common style for web APIs: data is made of resources (users, posts, orders), each with a URL, and the action is given by the HTTP method.
As a frontend developer, you consume APIs every day. Understanding the conventions helps you read them, use them correctly and write Route Handlers that look professional.
The conventions — resource + method
| Method | URL | Action | Status on success |
|---|---|---|---|
GET |
/posts |
a list | 200 |
GET |
/posts/42 |
one item | 200 (404 if it's missing) |
POST |
/posts |
creates | 201 + the created item |
PATCH |
/posts/42 |
updates partially | 200 |
PUT |
/posts/42 |
replaces completely | 200 |
DELETE |
/posts/42 |
deletes | 204 with no body |
Naming rules:
- plural nouns, not verbs:
/posts, not/getPostsor/createPost; - relationships through nesting:
/posts/42/comments; - filters, sorting, pagination in the query string:
/posts?author=7&sort=-createdAt&page=2.
Responses and errors
// 200 — a paginated list
{ "data": [{ "id": 1, "title": "Hello" }], "page": 2, "totalPages": 9 }
// 422 — validation failed
{ "error": "validation", "fieldErrors": { "email": ["Invalid email"] } }| Situation | Status |
|---|---|
| invalid data | 400 / 422 |
| not authenticated | 401 |
| authenticated, not allowed | 403 |
| doesn't exist | 404 |
| a conflict (the email is already used) | 409 |
| too many requests | 429 |
| an internal error | 500 — no internal details in the response |
A consistent error format across the whole API makes the frontend much simpler.
Pagination — kinds and when
| Kind | How | Pros | Cons |
|---|---|---|---|
| offset | ?page=3&perPage=20 → OFFSET 40 LIMIT 20 |
simple, jump straight to page 7 | slow on big tables; duplicated / skipped items if data is added in between |
| cursor | ?after=<last-id>&limit=20 |
fast, stable when new data arrives | you can't jump to "page 7" |
Numbered pages (admin panels, search) → offset. An infinite feed (social, notifications) → cursor.
REST vs the alternatives
| REST | GraphQL | tRPC / Server Actions | |
|---|---|---|---|
| Shape | many URLs, HTTP methods | a single endpoint, the client asks for exactly the fields | you call server functions directly from TS |
| HTTP caching | natural | complicated | — |
| Client-server types | through OpenAPI / by hand | from the schema | automatic |
| When | a public API, diverse consumers | many clients with different needs | frontend + backend in the same TS project |
Summary
- Plural resources + the HTTP method decides the action; correct status codes (201, 204, 404, 422).
- Filters and pagination in the query string; a consistent error format.
- Offset for numbered pages, cursor for infinite feeds.