Lately, I have been learning how to use Node.js and Express to build APIs. There are no fixed standards to build APIs, but reading online I identified some common themes on how to build a functional and usable API. Some common themes were:
Donβt return plain text
Even if the response body is formatted like a JSON, if the response header is not set as application/json some clients may have issues parsing it.
Use plural rather than singular
For example, use /articles/ rather than /article/
Avoid using verbs in URIs
Use the HTTP verbs (e.g. GET, POST, PUT, PATCH, DELETE) to let the user understand what sort of action the endpoint will perform.
For example, use POST: /users/ rather than POST: /users/newUser/
Always return a meaningful status code with error message in the response body
If the request is not successful, the API should return an error status rather than an ok status like 200. It is also helpful for the user if there is an error message in the response body.
Use trailing slashes consistently
All the endpoints of an API should be consistent in using trailing slashes (e.g. /users/) or not (e.g. /users). Ideally, the client should be automatically redirected to the correct endpoint if they use the other version of the URI. Most frameworks will have such an option, so it is worth looking for it and using it.
Use a framework
As an API gets more complex, it is worth investing some time in learning an API framework, such as Django REST Framework for Python or Restify for Node.js. Using an API-specific framework will make it much easier to keep the API consistent and usable.
Top comments (3)
I Disagree with:
thing/{id}
returns a single thing, whilethings/
returns all things. As most things go, consistency is more important than what you ultimately choose here.|I Agree
I like to think about plural vs singular by what that part of the url means, if it's an entity, a plural makes sense, you're not saying "I want all the posts", it's more like "I want to interact with the entity 'Posts'", with a GET at "/" being all/pagination, "/:id" being a singular fetch, Posting to a entity would be making a create request and what not.
I like this approach because it lowers variance, and imo easier to abstract for the frontend, instead of having to manually pick the singular/plural form, you can have just one word to refer to all the entity CRUD operations
Especially the last sentence of the last bullet.