Best Practices - Rest API
- Anand Nerurkar
- May 15, 2024
- 2 min read
Organize API design around resources https://adventure-works.com/orders // Good https://adventure-works.com/create-order // Avoid
Define API operations in terms of HTTP methods The common HTTP methods used by most RESTful web APIs are:
GET retrieves a representation of the resource at the specified URI. The body of the response message contains the details of the requested resource.
POST creates a new resource at the specified URI. The body of the request message provides the details of the new resource. Note that POST can also be used to trigger operations that don't actually create resources.
PUT either creates or replaces the resource at the specified URI. The body of the request message specifies the resource to be created or updated.
PATCH performs a partial update of a resource. The request body specifies the set of changes to apply to the resource.
DELETE removes the resource at the specified URI.
Use JSON as the best format for sending and receiving messages
Design rest endpoint with nouns , instead of verbs
Wrong --- /createCustomer
/getCustomer/1
correct -- /customers ---POST MAPPING ====Create a Customer
/customers ---GET MAPPING ==== Get all customers
/customers/1 --GET MAPPING ======Get A Customer
/customers --PUT MAPPING ==== Update Customer
/customers -PATCH === PArtial Update for customer
/customers/1 --DELETE
5 . Use status code in error handling
For Example:
6 . USe nesting on endpoints to show relationship
For example: there may be many comments for a post, so we could define endpoints with nesting as below
/posts/{postid}/comments
7. Use Filtering/pagination/sorting when data requested
8. Empty sets in message bodies
Any time the body of a successful response is empty, the status code should be 204 (No Content). For empty sets, such as a response to a filtered request with no items, the status code should still be 204 (No Content), not 200 (OK).
9. Use SSL/TLS for security
10. Use versioning
11. Use documentation with Swagger API
12. Use appropraite header info for authetication for ex: bearer token
Comments