RESTFul API Design - rnakidi/dsa GitHub Wiki
๐๐๐๐๐๐ฎ๐ฅ ๐๐๐ ๐๐๐ฌ๐ข๐ ๐ง: ๐๐๐ฒ ๐๐ฌ๐ฉ๐๐๐ญ๐ฌ ๐๐ง๐ ๐๐ฆ๐ฉ๐ฅ๐๐ฆ๐๐ง๐ญ๐๐ญ๐ข๐จ๐ง ๐๐ญ๐ซ๐๐ญ๐๐ ๐ข๐๐ฌ
- ๐๐จ๐ฆ๐๐ข๐ง ๐๐จ๐๐๐ฅ-๐๐ซ๐ข๐ฏ๐๐ง ๐๐๐ฌ๐ข๐ ๐ง
Design APIs based on the domain model, reflecting real-world entities and their relationships. Example: If the domain includes "users" and "orders," design resources like /users/{id} and /orders/{id} to align with the domain.
- ๐๐ฎ๐๐ซ๐ฒ ๐๐๐ง๐ ๐ฎ๐๐ ๐ ๐๐ฎ๐ฉ๐ฉ๐จ๐ซ๐ญ
Allow advanced data retrieval by supporting filtering, sorting, and querying. Use query parameters for flexible searches: Example: /products?category=electronics&sort=price_asc For complex queries, integrate standards like GraphQL or custom query languages.
- ๐๐ฆ๐ฉ๐ฅ๐๐ฆ๐๐ง๐ญ ๐๐๐๐ฆ๐ฉ๐จ๐ญ๐๐ง๐๐ ๐๐ซ๐จ๐ฉ๐๐ซ๐ญ๐ฒ
Ensure safe and predictable operations for retries, particularly for PUT, DELETE, and GET. PUT: Updating the same resource multiple times yields the same result. DELETE: Deleting a resource repeatedly doesnโt cause errors if the resource is already deleted.
- ๐๐ฌ๐ ๐๐๐ฆ๐๐ง๐ญ๐ข๐ ๐๐๐ญ๐ก๐ฌ
Structure endpoints logically, reflecting resources and their relationships. Favor meaningful nouns over verbs for endpoints: Good: /users/123/orders Avoid: /getUserOrders
- ๐๐ก๐จ๐จ๐ฌ๐ ๐๐๐๐ ๐๐๐ญ๐ก๐จ๐๐ฌ
Assign appropriate HTTP methods based on operation: GET: Retrieve data. POST: Create new resources. PUT: Update resources or create them if they donโt exist (upsert). DELETE: Remove resources. PATCH: Partially update a resource.
- ๐๐ก๐จ๐จ๐ฌ๐ ๐๐๐๐ ๐๐ญ๐๐ญ๐ฎ๐ฌ ๐๐จ๐๐๐ฌ
Use standard HTTP status codes for clear client-server communication: 200 OK: Request successful. 201 Created: Resource successfully created. 400 Bad Request: Client-side error. 401 Unauthorized: Authentication required. 404 Not Found: Resource doesnโt exist. 500 Internal Server Error: Unexpected server-side issue.
- ๐๐๐ซ๐ฌ๐ข๐จ๐ง๐ข๐ง๐
Maintain backward compatibility and introduce changes via versioning. Common approaches:
URI Versioning: /v1/users
Header Versioning: Accept: application/vnd.api+json;version=1.0
- ๐๐๐ญ๐๐ก ๐๐ซ๐จ๐๐๐ฌ๐ฌ๐ข๐ง๐
Allow multiple operations in a single request for efficiency. Use batch endpoints to handle multiple entities: Example: { "requests": [ { "method": "POST", "path": "/users", "body": {"name": "John"} }, { "method": "DELETE", "path": "/orders/123" } ] }
Respond with detailed results for each operation.
๐๐๐ฌ๐ญ ๐๐ซ๐๐๐ญ๐ข๐๐๐ฌ
Design APIs with the clientโs use case in mind, simplifying interactions while maintaining scalability.
Use tools like Swagger or OpenAPI for documenting and testing the API. Regularly monitor and refine APIs based on usage patterns and feedback.
By applying these principles and strategies, RESTful APIs can achieve greater efficiency, reliability, and maintainability.