Saturday, May 4, 2019

How do I write API to update a resource ?

Updating a complete resource in terms of API is nothing but replacing (PUTing) contents of a resource. Optionally, it can be used for creating a resource if it does not exist. Generally, end point is a singular.

PUT /api/v1/departments/15

Basic rules:

  1. You must use HTTP PUT method to update a resource. Optionally, you can create a resource if it does not exist.
  2. End point should be single (if not exceptional scenario e.g. Bulk update)
  3. Proper http response codes must be returned
  4. Do not add parameters to url, use body instead. Exposing data in url is a risk.

Http response codes to return

HTTP CodeWhen to return
200 - OKWhen api updates a complete resource successfully.
400 - Bad requestWhen api fails to update a resource because request sent by client in either invalid or incomplete. E.g. Request does not have values for mandatory properties or alphabets are sent in place of numeric values.
404 - Not foundWhen resource you are looking for does not exist (If you do not support resource creation. You may create resource if it does not exist, in such case don't return 404)

Bulk Update

Rarely you may want to update resources in bulk or batch to avoid round trips. In this case, you need to deal with few more http response codes -
HTTP CodeWhen to return
207 - Multi StatusWhen api tries to update multiple resources then it may happen that few resources succeed and few fail. In such cases, api can return detailed status for each resource. These detailed status can be OK, Bad request (any one from above table)
202 - AcceptedASYNC? if you do not want client to wait for your response and start update process in background then its good to return Accepted so that client gets feedback to not to wait further.
Its a good practice to validate request so that you can ensure successful modification of resources

No comments:

Post a Comment