Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful subtype resource

Tags:

rest

one best-practice question. If you are designing RESTful interface how would you differentiate subtypes. E.g. your application has animals (each animal is identified by its animalId) with subtypes of dog and bird where each subtype has its specific subresources. E.g. dogs has tail-length and bird wings-length (whatever it could be). What of these (or do you have in mind any better) approaches would you choose?

1)
/animals/{animalId}/tail-length (400 when animal is bird)
/animals/{animalId}/wings-length (400 when animal is dog)

2)
/dogs/{animalId}/tail-length
/birds/{animalId}/wings-length

3)
/animals?type=dog/{animalId}/tail-length
/animals?type=bird/{animalId}/wings-length
like image 369
zdenda.online Avatar asked Jan 08 '12 15:01

zdenda.online


2 Answers

Assuming that there is no ID collusion between the different subclasses I would recommend the following.

GET /animals/:id

With a response like this. (This example is JSON but could just as easily be XML/etc)

{
  "id": "xyz",
  "type": "dog",
  "tailLength" 400
}

This keeps it simple and RESTful.

like image 137
abraham Avatar answered Nov 15 '22 07:11

abraham


It's really a matter of personal preference.

I personally avoid putting information in the the query string as with option 3, since I tend to use the query string for non-hierarchical information. (The accepted answer to this question says that the first two are more correct, whereas the most upvoted answer states that it really doesn't matter.)

Caching is also a factor, as proxies might not cache a resource containing a query string (see Google's advice on leveraging proxy caches).

I think I would pick the second, or perhaps a hybrid (/animals/dogs/...) to indicate the hierarchical structure of your resources, but it's up to you.

like image 2
cmbuckley Avatar answered Nov 15 '22 09:11

cmbuckley