I’m working on a web API, based on MVC4 RC and using database-first Entity Framework as my model.
2 of the entities I have are Item and Group.
There’s a many-to-many relationship between these 2 entities.
Now, after quite easily implementing the API of CRUD operation for both, using the standard HTTP methods (GET, POST, PUT and DELETE), I came to the point in which I want to implement the binding and unbinding of items to and from groups.
I’ve tries other verbs, such as LOCK and UNLOCK, without success (they seem not to support them), and tried to somehow manipulate the POST and the PUT commands, again, without success.
Does any of you good people have an idea how to implement this?
Thanks a lot!
You can represent the many-to-many as a sub-collection on the root resource. E.g. You have /items/1234 and /groups/4567 – you could have groups as a subcollection as /items/1234/groups or /groups/4567/items
Either way is equally valid. I usually go the route of using a
PUTto set the relationship and aDELETEto remove it – some would say that’s not really REST but it’s worked fine in the scenarios I’ve used it in.PUT /items/1234/groups/4567– create a relationship between item 1234 and group 4567DELETE /items/1234/groups/4567– delete a relationship between item 1234 and group 4567This post helped me a lot. When I was looking into this last…
How to handle many-to-many relationships in a RESTful API?
Update: Routing
So for these more complex scenarios we’ve ended up simply using more specific routes. It can get ugly quickly trying to cram everything into a single generic route. We’ve got a suite of unit tests that make sure the relevant URL gets routed to the right controller and action.
The ItemGroupController then has Get, Delete and Put methods. Which we unit test like this…
Cheers,
Dean