REST APIs play an important role in client-server applications, microservices architecture, and third-party integrations.
Designing your REST API following best practices will improve:
Let's dive into the core best practices for designing an API specification.
Example:
https://{base-url}/api/products?type={product-type}&limit={limit}&offset={offset}
✅ Use nouns for resource names (e.g., /users
, /orders
)
✅ Stick to plural nouns (e.g., /products
instead of /product
)
✅ Use lowercase and separate words with hyphens (-) or underscores (_)
✅ Keep URLs simple & predictable
✅ Use path parameters for sub-resources:
/users/123/orders
✅ Use query parameters for filtering, sorting, and pagination:
GET /users?role=admin # Filtering
GET /products?sort=price # Sorting
GET /items?page=2&limit=20 # Pagination
🔹 GET → Retrieve data (e.g., GET /users/123
)
🔹 POST → Create a new resource (e.g., POST /users
)
🔹 PUT → Update an entire resource (e.g., PUT /users/123
)
🔹 PATCH → Partially update a resource (e.g., PATCH /users/123
)
🔹 DELETE → Remove a resource (e.g., DELETE /users/123
)
For successful responses, an HTTP status code alone is often sufficient.
📌 200 OK → Request successful (GET, PUT, PATCH)
📌 201 Created → Resource created successfully (POST)
📌 204 No Content → Successful request but no response body (DELETE)
📌 400 Bad Request → Invalid request data
📌 401 Unauthorized → Authentication required
📌 403 Forbidden → No permission
📌 404 Not Found → Resource does not exist
📌 500 Internal Server Error → Unexpected server error
For business rule validation errors, return 400 Bad Request
with a clear response body:
{
"code": "BUSINESS_REJECTED",
"message": "A book cannot be updated while it is under review."
}
✅ Use JSON as the standard format
✅ Maintain consistent field naming (snake_case
or camelCase
)
✅ Provide meaningful error messages
✅ Return only necessary data
If using OpenAPI Specification, define:
schema
section🔐 Use OAuth 2.0 / JWT for authentication
🔐 Do not expose API keys in URLs
🔐 Validate & sanitize inputs to prevent attacks
🔐 Use HTTPS for secure communication
Only consider versioning when necessary.
🛠️ Include versioning in the URL:
/v1/users
🛠️ Alternatively, use headers:
Accept: application/vnd.api.v1+json
📚 Provide clear API documentation (OpenAPI v3 specification)
📚 Include examples & error responses
Using editor.swagger.io for creating the API specification.
Store your API spec (.yaml
or .json
format) in a Git repository to maintain a history of changes.
Following OpenAPI specs (.yaml
or .json
format) allows:
By following these best practices, you'll create scalable, maintainable, and secure REST APIs! 🚀