How to Design A Rest API ?
With the inclination towards microservice architecture, REST Service is gaining popularity at a tremendous speed However this leaves us with a question that Are we designing the Rest APIs correctly ? Before getting into the answer let us put a light on the basic concept.
REST - This stands for Representational State Transfer. This indicates a Software architecture style, created in the year 2000 Roy Fielding.
RESTful - Any API that follows the REST design principles is known as RESTful API.
I built a lot of REST endpoints for the current company application and consider the below points while designing them.
The basic expectation from an API is to fetch, update, delete and insert data in the system. Our expectation could be met by the HTTP methods such as GET,POST,DELETE,PUT and OPTION.
HTTP method GET :: http://mysite.com/getEmployees
HTTP method POST :: http://mysite.com/createEmployees
get and create is redundant since the HTTP method clearly defines the intent of the method. A more optimised version of the API could be
HTTP method GET :: http://mysite.com/Employees
HTTP method POST :: http://mysite.com/Employees
The data coming out from the system is the group of records and naming as a singular noun hampers clarity and spreads confusion.
HTTP method GET :: http://mysite.com/Employee
HTTP method POST :: http://mysite.com/Employee
The above API looks like we are dealing with one employee however in reality there could be a group of employee records. A simple fix is to make them plural
Recommended by LinkedIn
HTTP method GET :: http://mysite.com/Employees
HTTP method POST :: http://mysite.com/Employees
A scenario that is relatable and happens all the time is that endpoints are interlinked such as Employee and Salary. To make a clear representation of the context we make valid nesting in the API such as
HTTP method GET :: http://mysite.com/Employees/234/salary
A database may contain several records and it is impractical to fetch all the data in a single request. we add condition as a query parameter to narrow down the results.
http://mysite.com/Employees?city=banagalore
A failure of an API is unavoidable however how to deal with the failure is an indispensable part of API design. HTTP error codes are the best way that lets the user know what is going bad in the system.
List Of HTTP error code
100 - 199 [Information Response] For example, 102 indicates the resource is being processed
300 - 399 [Redirects] For example, 301 means Moved permanently
400 - 499 [Client-side errors] 400 means bad request and 404 means resource not found
500 - 599 [Server-side errors] For example, 500 means an internal server error.