I'm in the progress of creating a REST API and currently, I'm encountering the following problem:
Foois the first resource. CRUD operations can be applied via the/foo/URI.Baris the second resource. CRUD operations can be applied via the/bar/URI.- Every
Foois associated with zero or oneBar. The reason why I don't treatBaras a subresource ofFoois because the sameBarinstance can be shared between mutipleFoos. So I figured it's better to access it via an independent URI instead of/foo/[id]/bar.
My problem is that in a significant amount of cases, clients which ask for a Foo instance are also interested in the associated Bar instance. Currently, this means that they have to perform two queries instead of one. I want to introduce a way that allows to get both objects with one single query, but I don't know how to model the API for doing that. What I came up with so far:
- I could introduce a query parameter similar to this:
/foo/[id]?include_bar=true. The problem with this approach is that the resource representation (e.g. the JSON structure) of the response would need to look different (e.g. a container such as{ foo: ..., bar: ... }instead of just a serializedFoo), which makes theFooresource endpoint "heterogeneous". I don't think that's a good thing. When querying/foo, clients should always get the same resource representation (structure), regardless of query parameters. - Another idea is to introduce a new read-only endpoint, e.g.
/fooandbar/[foo-id]. In this case, it's no problem to return a representation like{ foo: ..., bar: ... }, because then it's just the "official" representation of thefooandbarresource. However, I don't know if such a helper endpoint is really RESTful (this is why I wrote "can" in the title of the question. Of course it's technically possible, but I don't know if it's a good idea).
What do you think? Are there any other possibilities?
Barcannot exist without being associated to aFoo. However, as I wrote above, it's possible that multipleFoos share the sameBar. It should be possible to create aFoowithout aBarassociated, so I don't thinkBarshould be treated as parent.