Thursday, May 2, 2019

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

To read resource collection from server you must use HTTP GET method. If GET Api returns a collection then it must be plural.
GET /api/v1/departments/15/employees
In above example API returns all employees from department with ID=15


Basic rules:

  1. You must use HTTP GET method for finding a resource.
  2. End point must be plural
  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 collection's parent record does not exist.
In above example return 404 if department 15 does not exist
204 - No ContentsWhen resource collection is empty.
In above example return 204 if there are no employees in a department

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/employees?$select=Name
Above API can return only Names of the employees present in department with id=15.

Performance consideration

  1. Use pagination so that you do not return whole data at once. Pagination helps in fragmenting data, reduce unwanted network traffic, speed up data query.



No comments:

Post a Comment