Designing REST APIs
Overview
An API is a user interface for developers. A well-designed one is predictable: once someone has used two endpoints, they can guess how the rest work. A badly designed one forces them to read documentation for every call, and leads to bugs on both sides.
REST (Representational State Transfer) is the most common style for HTTP APIs. Its central idea: your API exposes resources — things such as courses, users and orders — at URLs, and clients use standard HTTP methods to act on them.
Resources and URLs
Use nouns, not verbs, in URLs, and let the method be the verb:
| ✗ Action-style | ✓ Resource-style |
|---|---|
POST /createCourse |
POST /courses |
GET /getCourse?id=42 |
GET /courses/42 |
POST /updateCourse/42 |
PATCH /courses/42 |
POST /deleteCourse/42 |
DELETE /courses/42 |
Conventions that keep URLs predictable:
- Plural nouns for collections:
/courses,/users. - IDs for single items:
/courses/42. - Nesting for clear ownership, at most one or two levels:
/courses/42/lessons. - lowercase-with-hyphens for multi-word names:
/learning-paths. /mefor the current user:GET /users/me.
Actions that don’t fit
Some operations aren’t simple create/read/update/delete — publishing a course, cancelling an order, resending an email. Two common approaches:
POST /courses/42/publish # an action sub-resource
PATCH /courses/42 { "status": "published" } # model it as a state changeBoth are fine; pick one style and use it consistently.
Methods and status codes
| Operation | Request | Success response |
|---|---|---|
| List | GET /courses |
200 + array (with pagination info) |
| Read | GET /courses/42 |
200 + object, or 404 |
| Create | POST /courses + body |
201 + created object + Location: /courses/42 |
| Update some fields | PATCH /courses/42 + partial body |
200 + updated object |
| Replace | PUT /courses/42 + full body |
200 + object |
| Delete | DELETE /courses/42 |
204 (no body) |
And the errors you’ll use most:
| Status | When |
|---|---|
400 Bad Request |
malformed request (invalid JSON, wrong types) |
401 Unauthorized |
not logged in / bad token |
403 Forbidden |
logged in but not allowed |
404 Not Found |
no such resource (also used to hide resources the user may not see) |
409 Conflict |
conflicts with current state (duplicate email, already enrolled) |
422 Unprocessable Content |
well-formed but fails validation rules (some APIs use 400 for this) |
429 Too Many Requests |
rate limit exceeded |
500 Internal Server Error |
a bug or outage on your side |
Request and response bodies
- Use JSON with
Content-Type: application/json. - Pick one naming style for fields —
camelCaseis natural for JavaScript clients — and stick to it. - Send dates as ISO 8601 strings in UTC:
"2026-12-03T10:30:00Z". - Send money as integers in the smallest unit (
"pricePaise": 49900) or as strings, never as floating-point numbers. - Return the resource after creating or updating it, so the client gets server-generated fields (
id,createdAt) without another request. - Don’t expose internal fields: password hashes, internal flags, other users’ emails.
Lists: pagination, filtering, sorting
Never return an unbounded list. A table with a million rows will eventually crash your server or the client.
GET /courses?level=beginner&search=node&sort=-createdAt&limit=20&cursor=eyJpZCI6NDJ9- Filtering with simple field names:
?level=beginner&status=published. - Searching:
?search=node. - Sorting:
?sort=title(ascending) or?sort=-createdAt(descending). - Pagination, with a default and a maximum page size.
Two pagination styles:
| Style | Request | Good for |
|---|---|---|
| Offset | ?page=3&limit=20 |
simple admin tables where users jump to page 7 |
| Cursor | ?cursor=…&limit=20 |
feeds and large or fast-changing data — fast and never skips or repeats items |
A response envelope makes paging easy for clients:
{
"data": [{ "id": 41, "title": "Node.js" }, { "id": 40, "title": "SQL" }],
"page": { "limit": 20, "nextCursor": "eyJpZCI6NDB9", "hasMore": true }
}Errors
Use one error format everywhere (see Error handling in Express):
{
"error": {
"message": "Validation failed",
"details": [{ "path": "title", "message": "Required" }]
}
}Messages should help the developer fix the problem, without revealing internals.
Versioning and change
Once clients depend on your API, changing it can break them. Put a version in the path — /api/v1/courses — and follow these rules:
- Adding a new endpoint or an optional field is safe.
- Removing or renaming a field, changing a type, or making an optional field required is a breaking change. Do it in a new version (
/api/v2), and give clients time to move.
Idempotency for POST
Networks fail. If a mobile app sends “create order” and the connection drops before the response arrives, it doesn’t know whether the order was created. Retrying could create two orders.
Many APIs (Stripe is the famous example) accept an Idempotency-Key header: a unique value the client generates for each logical operation. If the server sees the same key twice, it returns the first result instead of acting again. It’s worth adding for payments and anything else that mustn’t happen twice.
Documenting your API
An API without documentation barely exists. The OpenAPI specification describes endpoints, parameters, bodies and responses in a YAML or JSON file, from which tools generate interactive docs (Swagger UI, Redoc), client libraries and tests. Many frameworks and validation libraries can generate OpenAPI from your code.
Design first, code second. Sketch the endpoints, bodies and errors (as in this topic’s exercise) before writing handlers. Changing a design on paper is free; changing it after clients depend on it is expensive.
Design an API on paper
Design the endpoints for a course-enrolment feature: listing a user's enrolments, enrolling in a course, marking a lesson complete, and leaving a course. For each, write the method, path, request body (if any), success status and one likely error status.
# Method Path Body Success Error
# ...# Method Path Body Success Error
# GET /users/me/enrolments?status=active — 200 401
# POST /enrolments { courseId } 201 409 (already enrolled)
# PUT /enrolments/:id/lessons/:lessonId/progress { completed: true } 200 404 (lesson not in course)
# DELETE /enrolments/:id — 204 404Summary
- Model your API as resources (nouns) in URLs, acted on by HTTP methods (verbs).
- Use plural nouns and nesting for clear relationships:
/courses/42/lessons. - Return precise status codes and one consistent error format.
- Paginate, filter and sort lists through the query string, and always cap the page size.
- Version your API and never break existing clients without warning.