Skip to content

Instantly share code, notes, and snippets.

@subtainishfaq7175
Last active April 8, 2020 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subtainishfaq7175/2d4cfd6d70ec29719cbc24a2bf254123 to your computer and use it in GitHub Desktop.
Save subtainishfaq7175/2d4cfd6d70ec29719cbc24a2bf254123 to your computer and use it in GitHub Desktop.
Best Practices for Designing a Pragmatic RESTful API

Rest API

Request/URL

The URL is a sentence, where resources are nouns and HTTP methods are verbs.

  1. 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.

  2. The resources should be plural ,not singular Employees is right. Employee is wrong.

  3. To tell server , what to do , whether to add or delete , we have HTTP Methods /Verbs.

  4. Method GET path /companies should get the list of all companies.

  5. Method GET path /companies/34 should get the detail of company 34

  6. Method DELETE path /companies/34 should delete company 34

  7. Examples:

    • GET method requests data from the resource and should not produce any side effect.
    • E.g /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.
    • E.g /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.
    • E.g. /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.
    • E.g /companies/3/employees/john/ will request the server to delete john resource from the employees collection under the company 3.
  8. Few More Example HTTP methods mapped as follows:

    • GET /tickets - Retrieves a list of tickets
    • GET /tickets/12 - Retrieves a specific ticket
    • POST /tickets - Creates a new ticket
    • PUT /tickets/12 - Updates ticket #12
    • PATCH /tickets/12 - Partially updates ticket #12
    • DELETE /tickets/12 - Deletes ticket #12
  9. Exceptional Cases, Sometimes you really have no way to map the action to a sensible RESTful structure. For example, a multi-resource search doesn't really make sense to be applied to a specific resource endpoint. In this case, /search would make the most sense even though it isn't a resource. This is OK - just do what's right from the perspective of the API consumer and make sure it's documented clearly to avoid confusion.

  10. For example an activate action could be mapped to a boolean activated field and updated via a PATCH to the resource.

  11. Treat it like a sub-resource with RESTful principles. For example, GitHub's API lets you star a gist with PUT /gists/:id/star and unstar with DELETE /gists/:id/star.

  12. Filters and Sorting can be added as query parameters GET /tickets?state=open is good example of filter.

  13. GET /tickets?sort=-priority - Retrieves a list of tickets in descending order of priority

  14. GET /tickets?sort=-priority,created_at - Retrieves a list of tickets in descending order of priority. Within a specific priority, older tickets are ordered first

HTTP Response

2xx Response codes:
  1. 200 Ok : The standard HTTP response representing success for GET, PUT or POST.
  2. 201 Created : This status code should be returned whenever the new instance is created. E.g on creating a new instance, using POST method, should always return 201 status code.
  3. 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 be of 2xx Success Category but around 4xx Client Error category.
3xx Response codes:
  1. 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 Response codes:
  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. E.g sometimes the authorized client is not allowed to access the directory on the server.
  4. 404 Not Found indicates that the requested resource is not available now.
  5. 410 Gone indicates that the requested resource is no longer available which has been intentionally moved.
5xx Response codes:
  1. 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.
  2. 503 Service Unavailable indicates that the server is down or unavailable to receive and process the request. Mostly if the server is undergoing maintenance.
Response Data:
  1. Naming Convention, the "right" thing to do is to follow JavaScript naming conventions - and that means camelCase for field names! If you then go the route of building client libraries in various languages
  2. Use HTTP Status + json body (even if it is an error)
    HTTP/1.1 200 OK
    
    Content-Type: application/vnd.api+json
    {
    "status": "success", 
    "data": { /* Application-specific data would go here. */ }, 
    "message": null /* Or optional success message */ }
    
    Failed request:
    { 
    "status": "error", 
    "data": null, 
    /* or optional error payload */ 
    "message": "Error xyz has occurred" 
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment