Full Stack Developer, Tech Geek, Audiophile, Cinephile, and Lifelong Learner!

REST API Design Good Practices

R

REST API Design Best Practices | Mushfiqur’s Blog

REST API Design Best Practices | Mushfiqur’s Blog

In order to survive, a project needs to sacrifice the quality for money and time. But in order to continue surviving, a software project needs to sacrifice money and time for the quality. In this post, we are going to see some good practices for developing REST API.

REST API Design Best Practices

In order to survive, a project needs to sacrifice the quality for money and time. But in order to continue surviving, a software project needs to sacrifice money and time for the quality. In this post, we are going to see some good practices for developing REST API.

Let’s not sacrifice the quality for money and time.

We almost everyone already know the content of this document but we just do not follow them always. Let’s start following some good practices which would eventually lead us to become good developers as well as it would benefit the product itself.

The API is an interface, through which many developers interact with the data. A good designed API is always very easy to use and makes the developer’s life very smooth. API is the GUI for developers, if it is confusing or not verbose, then the developer will start finding the alternatives or stop using it. Developers’ experience is the most important metric to measure the quality of the APIs.

terminologies

When you would go through this post, you are going to see few terms here and there. These terms are the most important terms related to REST APIs. Let’s get familiar with these terms.

Resource

Resource is an object or representation of something, which has some associated data with it and there can be a set of methods to operate on it. e.g. Animals, schools and employees are resources and delete, add, update are the operations to be performed on these resources.

Collections

Collections are set of resources, e.g. Companies is the collection of Company resource.

URL

URL(Uniform Resource Locator) is a path through which a resource can be located, and some actions can be performed on it.

API Endpoints

Let’s write a few APIs for Companies which has some Employees, to understand more. /getAllEmployees is an API which will respond with the list of employees. Few more APIs around a Company will look like as follows:

  • /addNewEmployee
  • /updateEmployee
  • /deleteEmployee
  • /deleteAllEmployees
  • /promoteEmployee
  • /promoteAllEmployees

And there will be tons of other API endpoints like these for different operations. All of those will contain many redundant actions. Hence, all these API endpoints would be burdensome to maintain, when API count increases.

What Is Wrong Here

The URL should only contain resources(nouns) not actions or verbs. The API path /addNewEmployee contains the action addNew along with the resource name Employee.

This is where the HTTP methods (GET, POST, DELETE, PUT), also called as verbs, play the role. The resource should always be plural in the API endpoint and if we want to access one instance of the resource, we can always pass the id in the URL.

  • method GET path /companies should get the list of all companies
  • method GET path /companies/34 should get the detail of company 34
  • method DELETE path /companies/34 should delete company 34

In few other use cases, if we have resources under a resource, e.g. Employees of a Company, then few of the sample API endpoints would be:

  • GET /companies/3/employees should get the list of all employees from company 3
  • GET /companies/3/employees/45 should get the details of employee 45, which belongs to company 3
  • DELETE /companies/3/employees/45 should delete employee 45, which belongs to company 3
  • POST /companies should create a new company and return the details of the new company created

HTTP Methods(VERBS)

HTTP has a set of rules to transfer data between server and client. We can call them HTTP request methods or HTTP verbs. There are eleven HTTP request methods. These methods indicate the type of action to be performed on resources. We are going to see some example of them.

  • GET method requests data from the resource and should not produce any side effect e.g. /companies/3/employees returns a list of all employees from company 3.
  • The POST method requests the server to create a resource in the database, mostly when a webform is submitted. e.g. /companies/3/employees creates a new Employee of company 3. The POST is a non-idempotent which means multiple requests will have different effects.
  • The PUT method requests the server to update a resource or create the resource if it doesn’t exist. e.g. /companies/3/employees/mushfiq will request the server to update, or create if doesn’t exist, the mushfiq resource in employees collection under company 3. The PUT is idempotent which means multiple requests will have the same effects.
  • The DELETE method requests that the resources, or its instance, should be removed from the database. e.g. /companies/3/employees/mushfiq will request the server to delete mushfiq resource from the employees’ collection under the company 3.

Idempotent A HTTP method is idempotent when we can safely execute the request over and over again and all requests lead to the same state.

HTTP Response Status Codes

When the client raises a request to the server through an API, the client should know the feedback, whether it failed, passed or the request was wrong. HTTP status codes are bunch of standardized codes which has various explanations in various scenarios. The server should always return the right status code.

Let’s discuss few important HTTP status code and try to categorize them to understand easily.

2XX [Success Category]

These status codes represent that the requested action was received and successfully processed by the server.

  • 200 Ok The standard HTTP response representing success for GET, PUT or POST
  • 201 Created This status code should be returned whenever the new instance is created. E.g. on creating a new instance, using the POST method, should always return 201 status code.
  • 204 No Content represents the request is successfully processed but has not returned any content. DELETE can be a good example of this. The API DELETE /companies/43/employees/2 will delete the employee 2 and in return, we do not need any data in the response body of the API, as we explicitly asked the system to delete. If there is any error, like if employee 2 does not exist in the database, then the response code would be not being of 2xx Success Category but around 4xx Client Error category.
3XX [Redirection Category]
  • 304 Not Modified indicates that the client has the response already in its cache. And hence there is no need to transfer the same data again.
4XX [Client Error Category]

These status codes represent that the client has raised a faulty request.

  • 400 Bad Request indicates that the request by the client was not processed, as the server could not understand what the client is asking for
  • 401 Unauthorized indicates that the client is not allowed to access resources and should re-request with the required credentials
  • 403 Forbidden indicates that the request is valid, and the client is authenticated, but the client is not allowed to access the page or resource for any reason. E.g. sometimes the authorized client is not allowed to access the directory on the server
  • 404 Not Found indicates that the requested resource is not available now
  • 410 Gone indicates that the requested resource is no longer available which has been intentionally moved
4XX [Server Error Category]
  • 500 Internal Server Error indicates that the request is valid, but the server is totally confused, and the server is asked to serve some unexpected condition
  • 503 Service Unavailable indicates that the server is down or unavailable to receive and process the request. Mostly if the server is undergoing maintenance

Field Name Casing Convention

You can follow any casing convention, but make sure it is consistent across the application. If the request body or response type is JSON then please follow camelCase to maintain the consistency.

Searching, Sorting, Filtering and Pagination

All these actions are simply the query on one dataset. There will be no new set of APIs to handle these actions. We need to append the query params with the GET method API. Let’s understand with few examples how to implement these actions.

  • Sorting In case, the client wants to get the sorted list of companies, the GET /companies endpoint should accept multiple sort params in the query. E.g. GET /companies?sort=rank_asc would sort the companies by its rank in ascending order.
  • Filtering For filtering the dataset, we can pass various options through query params. E.g. GET /companies?category=banking&location=bd would filter the companies list data with the company category of Banking and where the location is BD.
  • Searching When searching the company name in companies list the API endpoint should be GET /companies?search=Google

If adding many query params in GET method makes the URI too long, the server may respond with 414 URI Too long HTTP status, in these cases, params can also be passed in the request body of the POST method.

Versioning

While APIs are being consumed by the other clients, changing anything in the API would break the client apps. So, it’s a very good practice to add version system into the APIs.

For example:

https://api.servicename.com/v2/
https://api. servicename.com/v1/

This document has a lot of areas to improve.

Share on:

Add Comment

  |     |  
Full Stack Developer, Tech Geek, Audiophile, Cinephile, and Lifelong Learner!