CodeYogi
CodeYogi

Reputation: 1412

RESTful API for nested resource

I have two entities Hotel, Merchant where each merchant can have many hotels. Right now I am having an API endpoint like this:

/api/v1/merchants/{id}/hotels/{id}

But I was thinking what is wrong with this semantics:

/api/v1/hotels/{id}

The later one is short too.

Upvotes: 1

Views: 1487

Answers (2)

Eric Stein
Eric Stein

Reputation: 13672

In my experience, the latter is preferable because it gives you more flexibility later. In six months somebody's going to say "Hey, I want to be able to look up all the hotels in Agraba". The first URL scheme makes that painful - you need to add a new endpoint. The second URL scheme supports that with a query parameter: GET /hotels?location=Agraba.

You may want to keep /merchants/{id}/hotels as a collection endpoint so you can POST/DELETE to add/remove hotels from a particular merchant.

Upvotes: 2

Alex Marculescu
Alex Marculescu

Reputation: 5770

In REST, each URL should uniquely identify a single resource.

So if the hotel's id is globally unique, then sure, there's no problem in using the shorter link. If however hotel id 1 means something different for merchant 1 than for merchant 2, then you ought to stick with the first URL (basically a unique composite key).

Upvotes: 0

Related Questions