Let's learn, share & inspire each other. Sign up now 🤘🏼
RESTful API Designing Guidelines — The Best Practices
Facebook, Google, Github, Netflix, and few other tech giants have given a chance to developers and products to consume their data through APIs and became a platform for them.
Even if you are not writing APIs for other developers and products, it is always very healthy for your application to have beautifully crafted APIs.
There is a long debate going on the internet, about the best ways to design the APIs, and is one of the most nuanced. There are no official guidelines defined for the same.
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.
The API is like an artist performing on stage, and its users are the audience
1) Terminologies
The following are the most important terms related to REST APIs
Let’s write few APIs for Companies which has some Employees, to understand more.
/getAllEmployees
is an API that 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?
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
.
Then what is the correct way?
/companies
endpoint is a good example, which contains no action. But the question is how do we tell the server about the actions to be performed on companies
resource viz. whether to add, delete or update?
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.
GET
path /companies
should get the list of all companiesGET
path /companies/34
should get the detail of company 34DELETE
path /companies/34
should delete company 34In 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 3GET /companies/3/employees/45
should get the details of employee 45, which belongs to company 3DELETE /companies/3/employees/45
should delete employee 45, which belongs to company 3POST /companies
should create a new company and return the details of the new company createdConclusion: The paths should contain the plural form of resources and the HTTP method should define the kind of action to be performed on the resource.
HTTP has defined few sets of methods which indicates the type of action to be performed on the resources.
The URL is a sentence, where resources are nouns and HTTP methods are verbs.
The important HTTP methods are as follows:
GET
method requests data from the resource and should not produce any side effect./companies/3/employees
returns list of all employees from company 3.POST
method requests the server to create a resource in the database, mostly when a web form is submitted./companies/3/employees
creates a new Employee of company 3.POST
is non-idempotent which means multiple requests will have different effects.PUT
method requests the server to update resource or create the resource, if it doesn’t exist./companies/3/employees/john
will request the server to update, or create if doesn’t exist, the john resource in employees collection under company 3.PUT
is idempotent which means multiple requests will have the same effects.DELETE
method requests that the resources, or its instance, should be removed from the database./companies/3/employees/john/
will request the server to delete john resource from the employees collection under the company.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 a bunch of standardized codes which has various explanations in various scenarios. The server should always return the right status code.
The following are the important categorization of HTTP codes:
These status codes represent that the requested action was received and successfully processed by the server.
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 be of 2xx Success Category
but around 4xx Client Error category
.These status codes represent that the client has raised a faulty request.
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.
All of 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 of how to implement these actions.
GET /companies
endpoint should accept multiple sort params in the query.GET /companies?sort=rank_asc
would sort the companies by its rank in ascending order.GET /companies?category=banking&location=india
would filter the companies list data with the company category of Banking and where the location is India.GET /companies?search=Digital Mckinsey
GET /companies?page=23
means get the list of companies on 23rd page.If adding many query params in GET methods makes the URI too long, the server may respond with 414 URI Too long
HTTP status, in those cases params can also be passed in the request body of the POST
method.
When your APIs are being consumed by the world, upgrading the APIs with some breaking change would also lead to breaking the existing products or services using your APIs.
http://api.yourservice.com/v1/companies/34/employees
is a good example, which has the version number of the API in the path. If there is any major breaking update, we can name the new set of APIs as v2
or v1.x.x
Anjali 16 Sep, 2022
what is your opinion on the proper HTTP response code returned by a successful login/automated redirection to, say, a home page or admin dashboard?
Krishnan 16 Sep, 2022
I always get confused with point 6. So let´s say I am working with Laravel and its resoucerful controllers. The index method returns all resources from that particular controller. I don’t know how to implement point 6, about sorting and filtering. And most of times that situation is handled to a datatables plugin, so how to perform that in actual code? I
Rahul 16 Sep, 2022
Let’s say we have a case where we have different kinds of users like boss, manager, hr etc. and they all need to get some informations about an employee. But we also want bosses to get some extra information like salary of an employee where the other kinds of users cannot get that knowledge. In a short way, different kinds of users will get mostly same information but depending on their kind, they might get a few extra field in response. In such a case I have 2 solutions in my mind. The first one is they have a common route like /companies/3/employees/4 and I will handle the response inside of the related function, according to owner of request.In the second case, I might use different routes like /admin/companies/3/employees/4 thereby handling them in different functions. What is the best way to handle such a case?
Khushboo 16 Sep, 2022
6) You would also need to use POST instead of GET due to security reasons as GET requested URLs stay in browser history, cached and logged in server logs which may not be acceptable at times. Overall a great post!