What is REST? A Quick Refresher
REST (REpresentational State Transfer) is an architectural style for designing networked applications. It's not a strict protocol, but a set of constraints that lead to scalable and maintainable APIs. The core idea is to treat everything as a resource that can be manipulated using standard HTTP methods.
Best Practices for Clean REST APIs
- Use Nouns for URLs, Not Verbs Your API should expose resources. The URL identifies the resource; the HTTP verb identifies the action.
- Bad 👎: /getUsers, /createUser
- Good 👍: GET /users, POST /users
- Use Plural Nouns for Collections Using plural nouns for resource collections is a standard convention that keeps your API consistent.
- Bad 👎: /user/123
- Good 👍: /users/123
- Use HTTP Verbs Correctly Each HTTP verb has a specific, well-defined meaning.
- GET: Retrieve a resource or a collection of resources. (Safe, Idempotent)
- POST: Create a new resource. (Not Idempotent)
- PUT: Update an existing resource completely (replaces the entire resource). (Idempotent)
- PATCH: Partially update an existing resource. (Not necessarily Idempotent)
- DELETE: Remove a resource. (Idempotent)
- Idempotent means running the same request multiple times has the same effect as running it once.
- Provide Meaningful HTTP Status Codes Use standard status codes to indicate the outcome of a request. This allows clients to handle responses programmatically.
- 2xx (Success): 200 OK, 201 Created, 204 No Content
- 3xx (Redirection): 301 Moved Permanently
- 4xx (Client Error): 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
- 5xx (Server Error): 500 Internal Server Error
- Support Filtering, Sorting, and Pagination For collections, never return all the data at once. Use query parameters to allow clients to refine the results.
- Filtering: GET /posts?status=published
- Sorting: GET /posts?sort=-created_at (the - indicates descending)
- Pagination: GET /posts?page=2&limit=20
Why and How to Version Your API
As your application evolves, you will inevitably need to make breaking changes to your API (e.g., renaming a field, changing the data structure). If you do this without versioning, you will break existing client applications. API versioning is the practice of managing these changes.
Strategy 1: URI Versioning (Most Common)
This is the most straightforward approach. You include the version number directly in the URL.
- https://api.example.com/v1/users
- https://api.example.com/v2/users
Pros: Simple, explicit, and easy to see which version is being used just by looking at the URL. Cons: The URL is technically pointing to the same resource, which some purists argue violates REST principles.
Strategy 2: Header Versioning
You use a custom HTTP request header to specify the API version.
- GET /users
- Accept-Version: v1
Pros: Keeps the URI clean. Considered a more "pure" REST approach. Cons: Less visible to developers. You can't see the version in the browser's address bar.