12 Rules to build REST API
1. Use consistent resource naming
Plural nouns, kebab-case, no verbs.
Your URLs are nouns. HTTP methods are the verbs.
`/api/users`, `/api/order-items`, never `/api/getUsers`.
2. Version from day one
Put `/v1/` in your base path before you ship.
Retrofitting versioning onto a live API is painful. Starting with it is free.
3. Use proper HTTP status codes
Not everything is 200. Not every error is 500.
4. Implement pagination from the start
Every list endpoint should support `?page=1&limit=20` or cursor-based pagination from day one.
Add filtering and sorting through query params (`?status=active&sort=name`).
Keeps your API flexible without new endpoints.
5. Use DTOs. Don't leak your DB schema
Your database model is not your API response.
Shape what goes out. Strip internal IDs, timestamps you don't want exposed, and sensitive fields.
6. Add rate limiting
One abusive client shouldn't take down your API.
`express-rate-limit` takes five lines.
For production, back it with Redis so it works across instances.
7. Design for idempotency
Network failures happen. Idempotency means retries are safe.
8. Standardize error responses
Every error from your API should have the same shape:
Use a global error handler to enforce this. Clients should never have to guess what an error looks like.
9. Use proper authentication patterns
Always send tokens in the `Authorization: Bearer <token>` header, never in query params.
Separate authentication (who are you?) from authorization (what can you do?).
Different middleware for each.
10. Document your API
An undocumented API is a private API.
Use OpenAPI/Swagger, which lets you auto-generate client SDKs, validate requests, and run contract tests.
11. Add health check endpoints
Every API needs `/health`.
It's how load balancers and Kubernetes know your service is alive.
12. Add observability from day one
Structured JSON logs (not console.log) with request ID, user ID, and duration on every request. Correlation IDs that flow across service boundaries. Metrics on response times, error rates, and throughput per endpoint.
Comments
Post a Comment