APIs are the backbone of a successful application architecture and REST APIs are the most popular way of creating web services.
Below is a concise list of best practices to use while designing REST APIs.
1. Consistency of HTTP methods
-
GET /api/v1/threads
- to get a list of all threads -
GET /api/v1/threads/14
- get a single thread with id 14 -
POST /api/v1/threads
- add a new thread to collection -
PUT /api/v1/threads/14
- update thread with id 14 -
DELETE /api/v1/threads/14
- update thread with id 14
2. Versioning
- Version is part of the endpoint
- This gives the possibility to support multiple live versions of the same API. E.g. Twitter has API versions 1.1 and 2.0 - both are live and accessible.
- Enables easy switching and rollback for consumers of the API
3. Use standard HTTP error codes
- HTTP response codes were created to describe the semantics of an API response.
- Return standard error codes and let the consumer handle the errors in their own way. Always include a message in your errors for troubleshooting purposes.
4. Endpoint conventions
Plural nouns for collections and no verbs
E.g. "threads" is used instead of using verbs like /getThread, /updateThread-
Resource nesting is visible in the endpoint
E.g.GET /api/v1/threads/14/tweets
GET /api/v1/threads/14/tweets/2
5. Security
- Use TLS/SSL
- Use authentication and authorization to avoid malicious requests
- Set up rate limiting and caching to prevent against DoS attacks
6. Performance
Use caching(in-memory or CDN) to provide fast results for repeated GET requests
A good API has pagination and filtering capabilities to reduce the amount of data being transferred. Data transfer objects should not include unnecessary fields.
7. Documentation
The least requirements of a method documentation - description, request parameters, response, error scenarios.
Definitely include request/response samples to provide the full picture.
Also check - https://swagger.io/specification/
My final suggestion is to make API designing process the starting point of your backend architecture and build other architectural components around it.
Thanks for reading.
I hope this was useful in providing a checklist of points to take care of while designing APIs.
If you want to connect with me, you can find me on Twitter
Top comments (6)
This looks very interesting.
I follow all these rules but not the Plural nouns for collections. After all, tbh it makes sense
Thanks Kola 💜
Good article
Thanks 😊
Best way of explanation.
Thank you 😊