astex
astex

Reputation: 1045

How to "correctly" add an existing entity to a collection RESTfully

I have two already extant objects,

/foo/1 GET
/bar/1 GET

Each foo has bars and each bar has foos. How do I RESTfully add my bar to my foo's bar collection?

This seems like one possible interpretation:

/foo/1 PATCH { bars: [1] }

but it breaks the idea that bars attached to that foo should be displayed via /foo/1/bar/. This also seems valid:

/foo/1/bar/ POST { id: 1, ... }

and fits closest to the wikipedia description, but since we're not creating a new bar this is a bit confusing. This also creates a kind of bizarre ambiguity, since it may also be possible to create a new bar assigned to this foo via this method. Lastly, there's:

/foo/1/bar/1 POST

which I just plain like due to its simplicity, but doesn't agree with the wikipedia description and gives no obvious way to remove the bar from the list (since DELETE would delete the bar).

I realize REST is an architectural style rather than an explicit standard, but there must be some least-problematic way to do this.

Upvotes: 1

Views: 63

Answers (1)

Eric Stein
Eric Stein

Reputation: 13672

I usually see this solved by using a third resource to own the mapping between foo and bar, such as:

POST /foo
<- "id": 22

POST /bar
<- "id": 17

POST /foo-bars
-> { "fooId": 22, "barId": 17 }

Upvotes: 1

Related Questions