Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design REST API for non-CRUD "commands" like activate and deactivate of a resource?

Tags:

rest

Before I decided to ask this question I have searched quite a long for the answer but I haven't found any satisfactory. (e.g. Examples of the best SOAP/REST/RPC web APIs? And why do you like them? And what's wrong with them?)

And the problem is actually quite simple. I have an object/resource named Account. My REST API supports all CRUDs with GET, POST, PUT and DELETE already with proper error handling, status codes etc.

Additionally however I want to expose an API ("command") to activate and deactivate selected Account resource. Even if the "isActive" is a property of the Account I don't want to use just the Update from my CRUD of the whole Account.

I know it is easy to violate REST principles and make RPC style design with such design like this:

PUT /api/account/:accountId/activate

PUT /api/account/:accountId/deactivate

So what is the best solution for this use case?

My current idea is to use PUT and DELETE verbs like this (to treat it as a sub-resource) as proposed here http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful:

PUT /api/account/:accountId/isActive // for activate

DELETE /api/account/:accountId/isActive // for deactivate

What are your solutions?

like image 699
Adam Bogdan Boczek Avatar asked Feb 15 '14 07:02

Adam Bogdan Boczek


People also ask

Is REST API only for CRUD?

CRUD functions can exist in a REST API, but REST APIs are not limited to CRUD functions. CRUD can operate within a REST architecture, but REST APIs can exist independent of CRUD. For example, a REST API can allow clients to reboot a server even if it doesn't correspond to any CRUD functions.


2 Answers

How about coming up with a noun for the feature you want to modify - 'status' in this instance. This would then become a sub resource of the parent entity. So for your case I would model the URI as follows:

/api/accounts/{accountId}/status 

If the 'update' semantics are idempotent then PUT would be most appropriate, else that would need to be a POST (e.g if nonces are involved and are invalidated by the service). The actual payload would include a descriptor for the new state.

Note, I pluralized 'accounts' since you can have multiple of those, but status is singular since your account can have only one state.

like image 163
Michael-7 Avatar answered Sep 17 '22 13:09

Michael-7


PATCH is the most appropriate method in this case. Please find more at RESTful URL for "Activate"

like image 24
Narendra Kalekar Avatar answered Sep 18 '22 13:09

Narendra Kalekar