Ahmed Nabil
Ahmed Nabil

Reputation: 18986

REST URL naming convention /users/{id}/cars/{carId} vs /cars/{carId}?

I have a simple model
Each Use can have multiple cars

Now when I decide to name the related REST URL naming for Cars service
Initially I suggest to be as the following
GET /cars/{carId}

But when I read about best practices in REST Resource Identifier (URI) Naming
I found that its better to put parent information in the URI as the following
GET /users/{userId}/cars/{carId}

Any one explain to us
Why the second one is the recommended naming
However, I need ONLY a carId to fetch the car
And no need to userId

Upvotes: 0

Views: 320

Answers (2)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57257

REST does not care what spelling you use for your identifiers.

/a4e199c3-ea64-4249-96aa-abb71d860a55

Is a perfectly satisfactory REST identifier.

Guidelines such as the one that you linked should be understood a style guide; human readable identifiers that adhere to local spelling conventions are goodness for exactly the same reasons as human readable variable names that adhere to local spelling conventions.

Some URI guidelines advocate convention over configuration -- put broadly, you can simplify your implementations if you choose identifier spellings that allow your framework to deduce where things should live.

when I read about best practices in REST Resource Identifier (URI) Naming I found that its better to put parent information in the URI

Maybe; part of the problem may be confusing resources with entities. It's an entirely normal thing for one single row in your database to contribute to the representation of many different resources, each of which has its own identifier

/users/:userId/cars/:carId
/cars/:carId

In HTTP, you might even send to the client information that the representation of one of these resources is equivalent to another (see RFC 7231).

The good news: hypermedia clients can deal this sort of thing automatically, because they have built into them awareness of the semantics of links; web aware hypermedia clients (for instance: browsers) will also be able to do the right thing with the meta data.

The bad news: you probably aren't using hypermedia types as your representations, so you won't see those benefits.

Upvotes: 1

Goblin
Goblin

Reputation: 54

IMO, it depends more on the context. Consider the following example:

GET /users/user001/cars/car001 Response: owner-name, car-license-no, purchase-date, first-owner Here the response is - car details, specific to a user

GET /cars/car001 Response: car-model-no, manufacturer, displacement, car-type Here the response is - car details, specific to the car

Upvotes: 1

Related Questions