node.jsrestendpoint

Best way to structure RESTful API endpoints (two roles, same endpoint)


I’m looking for input on the best way to structure my endpoints so that multiple user roles can use the same endpoint.

Assuming we have two user roles of customer and admin, I’ve read that using the role type in the endpoint is not recommended, such as: /api/customers/orders/ and /api/admin/orders/

If I have an endpoint PUT: /api/orders/{ORDER_ID}/photo-proof, I understand that I should take the user’s authenticated role and do the business logic depending on which role the user has. An admin can update the photo proof image, while a customer can approve or deny the photo proof.

My question is the use case of “What if an admin is also a customer with orders?” If the admin hits the endpoint above as an admin, all is well. But if the admin hits that endpoint from the customer UI, and the endpoint is taking the user’s role to determine which business logic it should run, then it will run the incorrect business logic because the admin is now a customer and is wanting to approve or deny their own photo proof.

Hopefully this makes sense as a question. Any guidance would be appreciated!


Solution

  • It sounds like the core issue is around:

    the endpoint is taking the user’s role to determine which business logic it should run, then it will run the incorrect business logic because the admin is now a customer and is wanting to approve or deny their own photo proof.

    'What business logic to run' is better determined on the the operation, not the user roles. For example, you have 2 separate tasks:

    Maybe these 2 operations are 2 different HTTP methods, or if they are (for example) both POST requests, you should inspect the request body to figure out what the intent of the operation is.

    Only after you figure out what the user is intending to do, you should figure out if the user is allowed to do that based on the role.