Best Coding Practices For Rest API Design

JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a payment gateway API, Google Maps API, Sending Email APIs, or any other kind of APIs depending on the type of application and the requirements.  Many times it happens that developers read the documentation part of the API, implement it, but they do not focus on building a clean, understandable, and scalable architecture when they are implementing any kind of API in their application. These things impact a system a lot when the application grows with time. Consider a scenario that you have built an application and now you need to expose the interface to the user. Do you really think that both of you will be at the same table? Do you think that they will understand the same thing that you’re trying to depict in your system? When you’re building a Restful API it is important to design it properly to avoid any bug or issue in your application. You need to take care of the performance, security, and ease of use for API consumers. It is good to follow some good conventions to build an API that is clean, understandable, and easy to work with. There are so many aspects you need to consider when you’re building a Restful API in your application. In this blog, we will highlight those aspects in detail. Let’s discuss the best coding convention to build the REST API in your application. 1. Name of the endpoint should be accompanied by the HTTP methodBeing a backend developer you might have been familiar with the various HTTP request methods to perform CRUD actions in your application especially the ones, which are common such as GET, POST, PUT, DELETE, and PATCH. In case you are not familiar with these methods then read the blog HTTP Request Methods. When you’re implementing an API make sure that the name of the endpoints linked with the resources go along with the HTTP method related to the actions you’re using in your application. Look at the example given below for reference…- GET /get_customers
– POST /insert_customers
– PUT /modify_customers
– DELETE /delete_customers
+ GET /customers
+ POST /customers
+ PUT /customers
+ DELETE /customers2. Return standard error codes according to the result of our APIWhile implementing an API the endpoints return the result that whether the action is successful or not. The result is always associated with some status code. For example: if you get the status 200 (ok) then it means the result is successful and if you get the status code 400 (bad request) then the result is failed (You can check the response using some tools like Postman to get to know the status code for the actions you perform in your application).Handle the errors gracefully and return the HTTP response code to indicate what kind of error is generated. This is helpful for API maintainers to understand the issues and troubleshoot them. Make sure that you know the existing status code to identify the case you need to apply each one of them. Sometimes it happens that the return message does not match with the status code and that creates confusion for the developers as well as for the consumers who are using that REST API. This is really harmful to the application. So it’s good to take care of the status code for the actions you perform in your application. Below is one of the examples…// Bad, status code 200 (Success)
// associated with an error object
{
“status”: 200,
“error”: {…}
}// Good
{
“status”: 200,
“data”: […]
}Some common error codes are given below…00 Bad Request – Client-side input fails validation.401 Unauthorized – User isn’t authorized to access a resource. It usually returns when the user isn’t authenticated.403 Forbidden – User is authenticated, but it’s not allowed to access a resource.404 Not Found – Resource is not found.500 Internal server error – Generic server error. It probably shouldn’t be thrown explicitly.502 Bad Gateway – This indicates an invalid response from an upstream server.503 Service Unavailable – Something unexpected happened on the server-side (It can be anything like server overload, some parts of the system failed, etc.).3. Support for the Filter, Sort, and PaginationHow would your server react if you implement an API in your application and the endpoints return the results in millions….???Your server will be down and it’s really going to cry in front of you…(jokes apart…)Many times it happens that we only need to consume some specific or fewer resources from our server. The reason could be anything. It can be the performance of the system, search system, or the massive amount of information that is not needed to return all at once. You can use a filter to return some specific item based on the condition. If you want to return a few results at a time then use pagination in your API. These concepts will help you to display only a specific type of information and it will increase the performance of your system by consuming fewer resources. Examples are given below…Filter: filter the customer with the following properties… the last name is Smith and the age is 30.GET /customers?last_name=Smith&age=30Pagination: Return 20 rows starting from 0GET /customers?limit=20&offset=0Sort: Return rows sorted by email in the ascendant.GET /customers?sort_by=asc(email)4. Endpoints name should be pluralIf you have implemented any kind of API in your application then you might have come across a question that whether the endpoint name should be singular or plural. Remember that you need to maintain consistency throughout your application. So it’s good to build the endpoints in the plural to be consistent in your database. It’s not necessary that you will always get a single item. You can have many items in a table but even if you consider the scenario of getting the result only one and you place it singular everywhere then you won’t be able to maintain the consistency in the name of your routes. – GET /article
– GET /article/:id
+ GET /articles
+ GET /articles/:id5. Nesting resources for hierarchical objectsWhile implementing an API you need to take care of the path for the endpoints. The path of the endpoint deal with the nested resources. To create this path treat the nested resource as the name of the path and append it after the parent resource. Make sure that the nested resource matches the table you have stored in your database else it will create confusion for you. If you don’t get the above point then understand this in a way that you have a list of students in your database. Each one of them has chosen the subjects they are interested in. Treat the ‘subject’ table as a child of a ‘student’ table in your database. Now, if you want to create the endpoint for the subjects associated with the student then append the /subjects path to the end of the /student path. If you’re using the GET method then an example of the endpoint path will look something like the given below…‘/students/:studentId/subjects’We get subjects on the students identified by studentId and then the response will be returned. Here, students are the parent’s resources and the subject is the child’s resources of the student.  So as discussed, we are adding subjects after the ‘/students/:studentId’. Each student has their own subject. The same kind of nesting structure will be applied to other methods as well such as POST, PUT and DELETE endpoints.6. Follow good security practicesWhen you’re implementing an API make sure that the communication between the client and the server is private because you often send and receive private information. For security purposes, you can use SSL/TLS.Using the SSL certificate isn’t too difficult. You can easily load it onto the server and the cost of an SSL certificate is also free and very low. Don’t make your REST API open. It should communicate over secure channels.When a user is accessing the information, they shouldn’t be able to access more data they have requested. Being a user you are not allowed to access the information of another user or the data of admins. To implement the principle of the least privilege, add role checks for a single role or more granular roles for each user. If you want to group users into a few roles then they should be allowed to cover all they need and no more. For each feature that users have access to if you have more granular permission then make sure that the admins can easily add and remove those features for each user accordingly. Add some preset roles that can be applied to group users. You won’t have to do this for every user manually. 7. Cache data to increase the performanceYou might have used caching during the implementation of some features in your application. Caching is really a powerful tool to speed up the performance of your application. Using caching you will get faster results and you won’t have to extract the data from the database multiple times for the same query. Use caching during the implementation of your API. It will speed up the performance of your application and it will reduce the consumption of the resources. It’s good to cache the data instead of running the same query and asking the database to give the same result (your database will start crying in front of you….lolzzz). One of the precautions you need to take care is that you don’t get outdated data. Due to the old data, something wrong can happen and your system can generate a lot of bugs in a production environment. Do not keep the information for a long period of time in the cache. It is good to keep the data for a short period of time in the cache. Depending on the needs you can change the way data is cached. One of the great services to implement caching is Redis8. VersioningKeeping the different versions of your API will help you to track the changes and it will help you to restore the previous version in case if something goes wrong with the latest one. Consider a scenario that you implemented an API, deploy it and a lot of clients start using it. Now at some point, you want to make some changes and you added or removed the data from a resource. Chances are there that it will generate bugs on the external services that consume the interface. This is the reason you should keep the different versions of your API. From the previous version, you can get the backup and work on it further. Versioning can be done according to the semantic version. Don’t force everyone to work on the same version at the same time, you can gradually remove the old versions of your API once you see that it’s not required anymore. Most of the time versioning is done with /v1/, /v2/, etc. added at the start of the API path.GET /v1/customers
GET /v2/studentsConclusionJSON, SSL/TLS, HTTP Status codes are the standard building blocks of the modern web app API. TO design a high-quality Restful API follow the best conventions we have discussed above. Being a backend developer your job is not just to implement the features you are asked to do. You also need to take care of doing it in the best possible way. Apply the best principle when you’re implementing an API so that people who consume and work on it as it.