Kiren S
Kiren S

Reputation: 3097

REST API design and implementation for non CRUD operations in Laravel

A user resource has properties name, status and so many other fields. A user can update his name but only an admin user can update the status.

In typical rest design, a name update could be

patch
/users/123
{
  name:"John"
}

Route will be

Route::apiResource('users',UserController::class);

Here the patch request will invoke the update method of the UserController class

Likewise, the status update is also a patch request which invokes the update method of the UserController class.

Now the situation is, both the updates are different actions from the perspective of business logic but from the REST design it is the same patch request that could be used for both operations.

So my questions are

  1. As I said above, we have the same controller action update will get invoked for both operations. But in the case of the status update, we have to check if the logged-in user is admin. How can I distinguish the operations and write the checking of the admin user

  2. Are my understanding of REST correct?

Note: Please don't tell me status is a resource in that case imagine if every property of that user is having different business logic to be done before the update. Then, will every property be a resource?

Curiously waiting for the suggestions

Thank You

Upvotes: 0

Views: 206

Answers (1)

inf3rno
inf3rno

Reputation: 26139

Your understanding is correct though this can be still two endpoints from my perspective:

PATCH /current/user {"name": "John"}
PATCH /users/123 {"status": "deceised"}

You add access control to your code something like:

  • if the user is an admin, then everything is fine
  • else if the user is trying to edit their own profile and does not try to change the status property, then everything is fine
  • otherwise 401

You should be able to do this based on the documentation. https://laravel.com/docs/5.1/authorization I don't use Laravel, but after 1 min read, I think you need to add a Policy where you put the upper if-else statements and that's all.

Upvotes: 1

Related Questions