RESTful subtype resource

one best practice question. If you are developing a RESTful interface, how would you differentiate the subtypes. For instance. your application has animals (each animal is identified by its animalId) with subtypes of dog and bird, where each subtype has its own specific sub-resources. For instance. dogs have tail lengths and bird wings (whatever that is). Which of these (or do you mean 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 
+4
source share
2 answers

Assuming there is no ID collusion between the various subclasses, I would recommend the following.

GET /animals/:id

With such an answer. (This example is JSON, but it could just as easily be XML, etc.)

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

It simplifies and is RESTful.

+3
source

This is really a matter of personal preference.

I personally avoid putting information in the query string, as is the case with parameter 3, since I prefer to use the query string for non-hierarchical information. (The accepted answer to this question says that the first two are more correct, while the most correct answer states that it really does not matter.)

Caching is also a factor because proxies cannot cache a resource containing a query string (see Googleโ€™s advice on using proxy caches ).

I think I would choose a second, or perhaps a hybrid ( /animals/dogs/... ) to indicate the hierarchical structure of your resources, but that is up to you.

+1
source

Source: https://habr.com/ru/post/1389908/


All Articles