Home > Software engineering >  Restful API: Best practice for admin and user scope
Restful API: Best practice for admin and user scope

Time:12-05

I am building an API where users and admins can interact with the same data, but with different needs. A user can also have access to the admin panel, if he has the "admin" role.

Let's see for example we have a resource like Badges. A Badge is simply a reward when you achieve some actions into the app.

GET http://localhost/api/v1/badges

An authenticated user can call this endpoint and it returns the list of all badges, if they have it or not, with progress details.

GET http://localhost/api/v1/badges?user_id=2

with user_id parameter, we can see these details of another user (if he allows it).

But from the admin scope, I just need to see the list of all badges, without achievement details (CRUD operations).

So I have 2 options in mind:

  • Create "admin" endpoints: GET http://localhost/api/v1/admin/badges.
  • Adding custom header "X-App-Scope" to identify if I am in admin or user.

I don't like the second one because I think I will have so many if statements and behavior in the same endpoint, depending of the scope.

Because I have lots of use cases like this, I want to make sure my API architecture is good to handle user/admin needs.

Do you guys have any idea/example to manage stuff like this?

Thanks!

CodePudding user response:

TL;DR: REST is designed in the expectation that you would use two different resources here.

The core problem is this: how would a general purpose component, like a browser, know that your special resource needs to have this custom header added?

In particular, consider the case where I send to you a copy of the URL for this resource, and nothing else. How are you to know to add the customer header to the request?

On the other hand, if you use different resources to share this information with each audience, everything just works.

CodePudding user response:

The only way I found to stay as simple/clear as possible is to make multiple endpoints, for each use case:

GET http://localhost/api/v1/badges to get all badges in raw data

GET http://localhost/api/v1/users/badges to get all badges with user stats (progression, achievement...) in a transformed format

GET http://localhost/api/v1/users/{uuid}/badges to get all badges with user stats (progression, achievement...) in a transformed format for the specified user, if his profile is public

Now I have a lot of /users/XYZ endpoints, but my code seems easier to read & maintain, and I don't really need to see the code to guess what data will be returned, the conditions, etc...

I keep wondering how the other APIs are written when you have an admin section, because having /users everywhere isn't really "pretty", and I don't see that anywhere else.

  • Related