0

I have an application I've built using Laravel. I'm just trying to understand the right naming conventions for the application. Since Laravel is RESTful, I want to stick the right naming conventions for REST.

Suppose I have a User resource who has a Car resource. So I am saving the user_id foreign key in my cars table. In the application, I want to update the details of the car using PUT. So how do I name my URI? Below are the three options that I'm considering. But I want to know which once is right:
1. /user/{id}/car/{id}
2. /car/{id}
3. /user/car/{id}

My question is, should I include the parent resource (user) in the URI or can I just use the car ID and update it? I have seen in some places (like the GitHub API) that they use the parent resource before the child resource.

If there is a duplicate question for this, please do let me know, as I searched for the exact answer before posting here, but couldn't find any.

ashishsanjayrao
  • 101
  • 2
  • 14

2 Answers2

1

My two cents:

I'd go for

  • /car/{id} when the car id is known
  • /car/?user_id={userId} To get all the cars owned by the user with a known id.

If a car is always owned by a user (the FK cannot be null) then you can prepend the URLs with /user, but it would make more difficult to find a car if you don't know whose car it is:

  • user/{userId}/cars/ To get all the cars owned by the user with a known id.
  • user/{userId}/car/{id} To get a specific car

For me the first option makes more sense, because I don't see a car as a child of a user, but as I don't know any of your requirements maybe the second option is the correct one.

The parent-child relation suits better for things like company-department (it makes no sense look for an IT department if you don't specify the company, for example)

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
  • Personally only change is I would go for a plural for the edge `car` when id is unknown, i.e. `/user/{userId}/cars/`. – Leon Storey Jan 12 '17 at 08:35
  • Thanks Pablo. So I guess, to generalize the answer, if there is a sure relationship between the two resources, then showing the hierarchy makes sense. If not, then it's better to individually use the resource. Correct me if I'm wrong. There are also various types of relationships other than one-to-one, that I must explore. Thanks a lot though! – ashishsanjayrao Jan 12 '17 at 09:52
0

I'd say 1 is the appropriate case since the 'car' by itself isn't stand alone. It expresses better the idea that that car is under that user, and it can be used for validation so you don't update by chance a car that's not that user's car.

CoolGoose
  • 508
  • 1
  • 5
  • 16