simonhaines
simonhaines

Reputation: 501

Association of entities in a REST service

I have a REST service modelling items and containers. Items are single atomic entities, containers are entities that contain items. How would I model this relationship in a RESTful way?

For example, here is a request for an item:

http://server/items/1
=> {"name": "Item 1"}

Assume the item is in a container:

http://server/containers/1
=> [{"name": "Item 1"}, {"name": "Item 2"}...]

How would I model adding an item to a container? Or removing an item from a container? Items know nothing about the containers they are in, so a PUT to the item won't work. Containers know what items they contain, but to PUT to the container, the entire container needs to be loaded first (potentially very large).

At the moment, I am POSTing to the container, but the 'action' query parameter has a code smell about it:

http://server/containers/1?action=add
POST {"name": "Item 1"}

Is there a better way for this?

Upvotes: 1

Views: 569

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142134

One of the most common uses of POST is to add a subordinate resource. Therefore simply using,

http://server/container/1
POST {"name": "Item 1"}

would be sufficient. To remove an item from a container you could do,

DELETE http://server/container/1/Item/1

Upvotes: 1

Related Questions