How to model a RESTful API with inheritance?

I would suggest:

  • Using only one URI per resource
  • Differentiating between animals solely at the attribute level

Setting up multiple URIs to the same resource is never a good idea because it can cause confusion and unexpected side effects. Given that, your single URI should be based on a generic scheme like /animals.

The next challenge of dealing with the entire collection of dogs and cats at the “base” level is already solved by virtue of the /animals URI approach.

The final challenge of dealing with specialized types like dogs and cats can be easily solved using a combination of query parameters and identification attributes within your media type. For example:

GET /animals (Accept : application/vnd.vet-services.animals+json)

{
   "animals":[
      {
         "link":"/animals/3424",
         "type":"dog",
         "name":"Rex"
      },
      {
         "link":"/animals/7829",
         "type":"cat",
         "name":"Mittens"
      }
   ]
}
  • GET /animals – gets all dogs and cats, would return both Rex and Mittens
  • GET /animals?type=dog – gets all dogs, would only return Rex
  • GET /animals?type=cat – gets all cats, would only Mittens

Then when creating or modifying animals, it would be incumbent on the caller to specify the type of animal involved:

Media Type: application/vnd.vet-services.animal+json

{
   "type":"dog",
   "name":"Fido"
}

The above payload could be sent with a POST or PUT request.

The above scheme gets you the basic similar characteristics as OO inheritance through REST, and with the ability to add further specializations (i.e. more animal types) without major surgery or any changes to your URI scheme.

Leave a Comment