REST API Design

2021-08-20

In the projects that I have been working on, the frontend communicates with the backend through APIs. The most common pattern that we use is REST API. REST stands for Representational State Transfer, and it is a set of guidelines on how the client and server should communicate.

HTTP Methods

REST API uses HTTP methods to define what action we want to perform. The most common ones are:

GET is used to retrieve data. For example, if we want to get a list of users, we send a GET request to /api/users. If we want to get a specific user, we send a GET request to /api/users/1 where 1 is the user id.

POST is used to create new data. If we want to create a new user, we send a POST request to /api/users with the user data in the request body.

PUT is used to update existing data. If we want to update user with id 1, we send a PUT request to /api/users/1 with the updated data in the request body.

DELETE is used to remove data. If we want to delete user with id 1, we send a DELETE request to /api/users/1.

Status Codes

When the server responds, it sends back a status code to indicate what happened. Some common ones are:

200 means the request was successful. 201 means a new resource was created successfully. 400 means the request was invalid, usually because the data sent by the client is wrong or missing. 401 means the client is not authenticated. 404 means the resource was not found. 500 means something went wrong on the server side.

It is important to return the correct status code so the client knows how to handle the response properly.

Naming Conventions

When designing API endpoints, there are some conventions that are good to follow. Use nouns instead of verbs for the endpoint path. For example, use /api/users instead of /api/getUsers. The HTTP method already tells us the action, so we do not need to repeat it in the path.

Use plural nouns for collections, so /api/users instead of /api/user. And for nested resources, we can chain them like /api/users/1/orders to get all orders for user with id 1.

Query Parameters

For filtering, sorting, or pagination, we can use query parameters. For example, /api/users?role=admin to filter users by role, /api/users?sort=name to sort by name, or /api/users?page=2&limit=10 to get the second page with 10 items per page.

Versioning

As the API grows, there might be cases where we need to change the structure of the response or the behaviour of an endpoint. To avoid breaking existing clients that are still using the old version, we can version our API. A common approach is to include the version in the URL like /api/v1/users and /api/v2/users.

This way, clients using v1 will not be affected when we make changes in v2.