REST API with multiple update actions


(Madi Sheri) #1

Hi everyone!

I’m new in Yii2 REST API and i have following scenario:

I have User model with UserController.

UserController has many actions with update actions like activate, deactivate, placeInBlackbox, updatePassword, and other actions which update record partially and manage relations of record.

I learned that it can be resolved by PATCH method setting operation ID like the following:


PATCH /users/123


[

    { "op": "activate", "path": "/activate"}

]

PATCH /users/123


[

    { "op": "deactivate", "path": "/deactivate"}

]



But i can’t understand how to explain to UserController which action should be called based on operation ID sent by PATCH method.

Of course, i can do it making like:


PUT /users/123/do/activate or PUT /users/123/do/deactivate

but it’ not according to basic REST API Best practices: Use nouns but no verbs


(Alexander Makarov) #2

Activate/deactivate is changing status so these both are regular POST. updatePassword as well. Not sure what placeInBlackbox but I think you should have a separate blackbox endpoint for it.


(Madi Sheri) #3

As I understand there is no opportunity to call separate action via PATCH method? Yes, activate/deactivate can be made by regular POST/PUT sending columns in bodyParams. But i have actions which make multiple operations besides update record like (it just example):




public function actionPlaceInBlackBox() {

    $user = $this->findModel(Yii::$app->user->id);

    $user->deactivate(); //change enable to false


    $blackBox = new BlackBox();

    $blackBox->create($user->id); //create BlackBox Model

    

    Log::process(Log::EVENT_PLACE_IN_BLACKBOX, $user->id); //create Log;

    

    return ['status_code' => 200];

}



this action can be executed by


PUT /users/123/do/placeinblackbox

and it works. But i’m not sure that it’s correct according to REST API best practices (Use nouns but no verbs).

Is there any ways to call separate action according to recommendation above? I’ve read one article (unfortunately i can’t paste link according forum policy) about PATCH method, where it is possible to send operation_id via bodyParams:




[

    { "op": "test", "path": "/a/b/c", "value": "foo" },

    { "op": "remove", "path": "/a/b/c" },

    { "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },

    { "op": "replace", "path": "/a/b/c", "value": 42 },

    { "op": "move", "from": "/a/b/c", "path": "/a/b/d" },

    { "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }

]



And I do not exclude that I misunderstood the aim of PATCH method.


(Alexander Makarov) #4

No, patch method like you’re saying isn’t supported.


(Madi Sheri) #5

Thank you for your answer. I’ll continue using verbs, hope its not so strictly :)