Tharaka Tharaka - 6 months ago 15
JSON Question

REST: Updating multiple records

I need to update multiple records using a single HTTP request. An example is selecting a list of emails and marking them as 'Unread'. What is the best (Restful) way to achieve this?

The way I doing right now is, by using a sub resource action

PUT http://example.com/api/emails/mark-as-unread


(in the body)

{ids:[1,2,3....]}

Answer

Create an algorithm-endpoint, like

http://example.com/api/emails/mark-unread

bulk-update is an algorithm name, a noun. It gets to be the endpoint name in REST, the list of ids are arguments to this algorithm. Typically people send them as URL query arguments in the POST call like

http://example.com/api/emails/mark-unread?ids=1,2,3,4

This is very safe, as POST is non-idempotent and you need not care about any side effects. You might decide differently and if your bulk update carries entire state of such objects opt for PUT

http://example.com/api/emails/bulk-change-state

then you would have to put the actual state into the body of the http call. I'd prefer a bunch of simple algo like mark-unread?ids=1,2,3,4 rather than one monolithic PUT as it helps with debugging, transparent in logs etc