Best practice for building a RESTful API

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.