restweb-applicationsrestful-url

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.


Solution

  • 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.