RESTful API – Design Best Practices

0

Category :

A well-designed API is easy to use and makes the developer’s life simple. API is the GUI for developers, if it is confusing or not verbose they will not use it.

RestvSoap
ThingsvActions
NounsvVerbs
ResourcesvMethods
Resource-GetvGetUserData

Terminologies

Resource - is an object or representation of something, which has some associated data with it and there can be 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 - are set of resources, e.g Companies is the collection of Company resource.

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

API endpoint

Some sample API endpoints for Companies which has some Employees: /getAllEmployees is an API endpoint which will respond with the list of employees.
  • /addNewEmployee
  • /updateEmployee
  • /deleteEmployee
  • /deleteAllEmployees
  • /promoteEmployee
  • /promoteAllEmployees
  • And lots of other similarly named enpoints for different operations. All of which will contain many redundant actions. Hence, all these API endpoints would be burdensome to maintain, when API count increases.

    What is wrong?

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

    Correct way

    /companies endpoint is a good example, which contains no action. So how do we tell the server about the actions to be performed on companies resource. 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.

    1. method GET path /companies should get the list of all companies
    2. method GET path /companies/34 should get the detail of company 34
    3. 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:

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

    HTTP methods (verbs)

    HTTP has methods which indicates the type of action to be performed on the resources.
    1. GET requests data from the resource and should not produce any side effect.
      /companies/3/employees
    2. POST method requests the server to create a resource in the database, mostly when a web form is submitted.
      /companies/3/employees
      non-idempotent which means multiple requests will have different effects.
    3. PUT method requests the server to update resource or create the resource, if it doesn’t exist.
      /companies/3/employees/john
      idempotent which means multiple requests will have the same effects
    4. DELETE method requests that the resources, or its instance, should be removed.
      /companies/3/employees/john/
    REST Request Methods

    HTTP response status codes

    When a caller makes a request to the API the caller needs to know if the call passed, failed or if it was an incorrect request. There are standardized HTTP codes which have various explanations in different scenarios, ideally the server should always return the most applicable code.

    2xx (Success category)

    The requested action was received and successfully processed by the server.
    1. 200 Ok The standard HTTP response representing success for GET, PUT or POST.
    2. 201 Created returned whenever the new instance is created.
    3. 204 No Content represents the request is successfully processed, but has not returned any content.

    4xx (Client Error Category)

    1. 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.
    2. 401 Unauthorized indicates that the client is not allowed to access resources, and should re-request with the required credentials.
    3. 403 Forbidden indicates that the request is valid and the client is authenticated, but the client is not allowed access the page or resource for any reason.

    5xx (Server Error Category)

    1. 500 Internal Server Error the request is valid, but the server is totally confused and the server is asked to serve some unexpected condition.
    2. 503 Service Unavailable the server is down or unavailable to receive and process the request. Mostly if the server is undergoing maintenance.

    Field name casing convention

    If the request body or response type is JSON then please follow camelCase to maintain the consistency.

    Searching, sorting, filtering and pagination

    All of these actions are simply the query on one dataset.
    1. Sorting endpoint should accept multiple sort params in the query. GET /companies?sort=rank_asc would sort the companies by its rank in ascending order.
    2. Filtering we can pass various options through query params. GET /companies?category=banking&location=india filter the companies list data with the company category of Banking and where the location is India.
    3. Searching When searching the company name in companies list the API endpoint should be GET /companies?search=Digital Mckinsey
    4. Pagination GET /companies?page=23 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.

    Versioning

    Upgrading the API 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

    Another common approach to dealing with formats is instead to set the Accept and Content-Type headers to describe what format you want and what format the response is respectively
    Accept: application/json;version=2
    /users/123

    This also has some additional benefits. For example, when you want to deprecate a given version, you can now use HTTP status code 406 to indicate the API can no longer produce an acceptable format for the client.
    One exception to this approach is if the API is to be accessed mostly by browsers as the user cannot easily set the headers.


    my thanks to these amazing posts on the subject:
    https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9
    http://www.restapitutorial.com/lessons/restquicktips.html