Home » Php » php – REST API ROUTE PATHS – best practice for authenticated resource?

php – REST API ROUTE PATHS – best practice for authenticated resource?

Posted by: admin February 25, 2020 Leave a comment


I have an API built with Laravel that works with authentication tokens (the passport package). It is unclear to me what should be the best practice for resources that are accessed within an authenticated session.

Let me explain.

Let’s say I would like to see the orders of a user as an administrator, I visit: /v1/users/5/orders and all orders get listed for user with ID 5.

But now the user with ID 5 is authenticated. What should the URL be to access his own orders resource?

Would that be: /v1/users/5/orders (and check if it’s either an admin or the session belongs to the user with ID of 5)

OR /v1/my/orders

OR /v1/my-orders

OR /v1/orders (and use session ID of user 5, – OR list all results when admin)

It just gets confusing when on the same URL the orders can be listed because an admin wants to access it. Or it is actually the session user that wants to see them.

How to&Answers:

I would suggest using /v1/orders, that will display a collection of orders based on privileges:
– all orders in case of an admin session
– orders belonging to the authenticated user, in case of a less privileged user.

Adding a prefix like /my/orders or my-orders does not bring any value.

For the sub-collections I would keep the route /v1/users/5/orders that will allow admin to access user orders.

This is a pretty good tutorial that explains API resource naming: https://restfulapi.net/resource-naming/