This document aims to define some structural guidelines to be used when designing REST API design.
- Use hyphens instead underscores to improve URI readability
- Prefer lowercase letters, following the rule above, avoid to use
camelCase
in URI sections - Avoid to include file extension in URIs, this should be communicated to the client via HTTP headers. i.e.
content-type
header. - Use always plurals for resource collections, example
http://api.company-xyz.com/clients
insteadhttp://api.company-xyz.com/client
- Avoid to use verbs in our endpoints (RPC style), the verb is implicit by the HTTP method we are using (GET - POST - PUT - PATCH - DELETE). For example, avoid
HTTP GET - http://api.company-xyz.com/getAgent/:agentId
instead use something likeHTTP GET - http://api.company-xyz.com/agents/:agentId
. - Prefer query string for search, filters and pagination:
/houses?city=San%20Francisco&page=2&size=30&order=desc
- Define a hierarchy for resources relations, for example nesting resources:
/agents/:agentId/houses?limit=5&order=desc
- Use version for endpoints, this is important when the API serves data for a mobile app, because if you don't have a mechanism to make the users update the app in a mandatory way, we can have multiple app versions installed (one client is in 1.0.0 the other one is in 2.0.1). So, for example if we change the contract for the
/houses
endpoint from v1.0.0 to v2.0.1 we will break all v1.0.0 clients. - Use a standard response for all endpoints, one example is JSEND, it's a really simple way to structure responses.
- Prefer
camelCase
oversnake_case
for field names in JSON responses. - Use HTTP status consistently, (in bold most used codes)
- 200 Success - General success (should return a body response)
- 202 Accepted: Commonly used in asynchronous operations, used to indicate that the operation was accepted but it is not completed yet
- 204 No Content - should be used when the response body is intentionally empty
- 400 Bad Request – This means that client-side input fails validation.
- 401 Unauthorized – This means the user isn’t not authorized to access a resource. It usually returns when the user isn’t authenticated.
- 403 Forbidden – This means the user is authenticated, but it’s not allowed to access a resource.
- 404 Not Found – This indicates that a resource is not found.
- 500 Internal server error – This is a generic server unhandled error. It probably shouldn’t be thrown explicitly.
- 502 Bad Gateway – This indicates an invalid response from an upstream server.
- 503 Service Unavailable – This indicates that something unexpected happened on server side (It can be anything like server overload, some parts of the system failed, etc.).
- Last but not least handle errors gracefully and avoid to leak detailed technical information to the client.
References