Saturday, May 4, 2019

How do I write API to update resource partially ?

PATCH method is an answer to this question. It allows you update resource partially. How? Its quite debatable topic that how you really update a resource partially. Some may say that you send only properties which need update but the problem is that you can not identify difference between setting a null value to property and ignoring a property (If you do not send some properties from request then on server they are null by default). So, guidelines state that -

  1. Use specific format for a request. i.e. a collection containing Operation, Property path, Value. This explicitly tells api that which properties are to be edited and what operation should be performed
  2. Some times people may choose to go with key-value pairs of Property name & Value considering that operation will always be an update operation.
PATCH /api/v1/departments/15

Basic rules:

  1. You must use HTTP PATCH method for update a resource.
  2. End point should be single (if not exceptional scenario e.g. Bulk update - but strongly avoid this)
  3. Proper http response codes must be returned
  4. Do not add parameters to api, 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

No comments:

Post a Comment