What are the best practices for API design and RESTful architecture?
RESTful API design creates intuitive, consistent, and maintainable interfaces. URL design: use nouns for resources (GET /users, not GET /getUsers), use plural nouns (GET /users, not GET /user), nest for relationships (GET /users/123/posts), and keep URLs flat (avoid deeply nested resources beyond 2 levels). HTTP methods: GET (read, idempotent, cacheable), POST (create), PUT (full update, idempotent), PATCH (partial update), and DELETE (remove, idempotent). Response design: use consistent JSON structure across all endpoints, include meaningful error responses with error code, message, and details, use HTTP status codes correctly (200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 500 Internal Server Error). Pagination: use cursor-based pagination for large datasets (more efficient than offset for PostgreSQL, avoids missing/duplicate items when data changes), return next cursor in response, implement page size limits. Filtering and sorting: use query parameters for filtering (GET /users?status=active&role=admin), support sorting (GET /users?sort=-createdat for descending), and implement field selection (GET /users?fields=id,name,email). Rate limiting: implement per-client rate limits, return limit info in headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset), and return 429 Too Many Requests when exceeded. Documentation: use OpenAPI (Swagger) specification, maintain documentation alongside code, provide interactive API explorer (Swagger UI), and include request/response examples for every endpoint. Idempotency: implement Idempotency-Key header for non-idempotent operations (POST requests), enabling safe retries without duplicate creation.