Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API different responses based on user roles

Tags:

rest

php

laravel

i'm using Laravel as my PHP framework. its a convention to put index show store ... functions in controllers.

i have 2 types of users(Admin & normal user). lets assume there is an Order(in restaurant) model and i want to implement index function for its controller. a user can have more than one Order.

what i need is that this function:

  • if admin is calling this API: returns all Orders
  • if normal user is calling this API: returns just Orders owned by this user

i searched but i couldn't find anything(tbh i didn't know what to search).

once i did this as below which i didn't like because it looks two different functions gathered in one:

if ($user->role == admin) {
       // fetch all orders
   } else if ($user->role == normal_user) {
       // just find user orders
     }

so my question is what's best approach to achieve what i want?

like image 359
Amas Avatar asked Jun 28 '19 11:06

Amas


People also ask

What are the different types of API responses?

The API supports 3 response types: JSON (Recommended) XML. NVP (Deprecated)

What are the 4 most common REST API operations?

These operations stand for four possible actions, known as CRUD: Create, Read, Update and Delete. The server sends the data to the client in one of the following formats: HTML. JSON (which is the most common one thanks to its independence of computer languages and accessibility by humans and machines)

What are the different ways to communicate through a REST API?

These methods – GET, POST, PUSH, PATCH, and DELETE – correspond to create, read, update, and delete resources. REST headers contain information that represent metadata associated with every single REST API request.


1 Answers

Such a REST API endpoint is typically a search allowing multiple filters, sorting and pagination. If so it is completly fine to apply different defaults for filters and also restrict filters to roles.

I would auto apply a filter user=currentUser for missing admin role and return a forbidden if a user without the admin role tries to apply a user filter for a different user.

With this approach you give admins also the functionality to search for offers of a specific user and you only need one search api to be used by the controller.

like image 60
Arne Burmeister Avatar answered Sep 29 '22 14:09

Arne Burmeister