I'm in the progress of creating a REST API and currently, I'm encountering the following problem:
Foo
is the first resource. CRUD operations can be applied via the/foo/
URI.Bar
is the second resource. CRUD operations can be applied via the/bar/
URI.- Every
Foo
is associated with zero or oneBar
. The reason why I don't treatBar
as a subresource ofFoo
is because the sameBar
instance can be shared between mutipleFoo
s. 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 theFoo
resource 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 thefooandbar
resource. 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?
Bar
cannot exist without being associated to aFoo
. However, as I wrote above, it's possible that multipleFoo
s share the sameBar
. It should be possible to create aFoo
without aBar
associated, so I don't thinkBar
should be treated as parent.