Thursday, May 2, 2019

How do I write API to read/get/find a resource ?

To read resource from server you must use http method i.e. GET. In general, GET APIs end with plural end points followed by identifier.
GET /api/v1/departments/15
In above example API returns department with ID=15 from a collection called departments

Basic rules:

  1. You must use HTTP GET method for finding a resource.
  2. End point may be plural followed by identifier or it can be singular too
  3. Proper http response codes must be returned
  4. Do not use body, use uri parameters instead

Http response codes to return

HTTP CodeWhen to return
200 - OKWhen resource exists. Also, return a response with expected information
404 - Not foundWhen resource does not exist.

Additionally -

You may also use query parameters to select fields which you want to return in response. This helps when you want less fields on presentation layer which ultimately reduces unwanted network traffic. Asp.net Web API 2 provides OData $select to select specific fields e.g.
GET /api/v1/departments/15?$select=Name
Above API can return only Name of the department.




No comments:

Post a Comment