REST API Design Principles: How to Build Clean Endpoints?
The most widespread form of communication between modern web and mobile applications (such as an iOS app) and servers is the REST (Representational State Transfer) architecture. REST APIs define the standards and endpoints through which we can exchange data.
Strictly adhering to a few fundamental rules is essential for designing a clean and scalable REST API:
1. Resource-based URL Structure
URLs should always denote nouns (resources), not verbs (actions). The use of plural forms is recommended.
| Bad Approach (Verb) | Good Approach (Noun + HTTP Method) |
|---|---|
| POST /getUsers | GET /users |
| POST /createNewUser | POST /users |
| GET /deleteUser?id=5 | DELETE /users/5 |
2. Semantics of HTTP Methods
- GET: Retrieving resources (safe, cannot modify data).
- POST: Creating a new resource.
- PUT: Full update of an existing resource.
- DELETE: Deleting a resource.
3. Use of Appropriate HTTP Status Codes
The server must always send a code corresponding to reality in its response. For example, 201 Created upon a successful creation, 400 Bad Request for an invalid client request, and the classic 404 Not Found code when a resource is not found.