Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restful MVC Web Api Inheritance

Im building myself an asp.net mvc 4 web api

I've been through the Microsoft videos and I think they are good. Http Verbs are used. Resources are nouns, it's dandy with repositories, etc.

But one thing really bugs me

I'm under the impression that this GET http://www.myurl.com/api/sellers/{id}/products is restful and GET http://www.myurl.com/api/products?$filter = sellerID eq {id} is not.

All I see in what I've read about the new web api is the former latter.

Is there native support for the latter former? If not, is there a way to do it without routing everything?


Edit-
Im looking for something that will allow GET http://www.myurl.com/api/sellers/{id}/products and GET http://www.myurl.com/api/products etc


Update:
This question didn't make sense for a while, I've fixed that, but that's why the first answer isn't marked as correct.


Update:
After chatting with MilkyWayJoe we talked about converting /Seller/2/Products to /Products?$filter = sellerID eq 2. Has anybody got any idea on how one can go about doing this?

like image 328
MrJD Avatar asked Jul 05 '12 05:07

MrJD


Video Answer


2 Answers

The url http://www.myurl.com/api/products?$filter= sellerID eq {id} is using OData filters, which in the Web API is consumed out of the box when your controller is returning the collection as IQuerable. The default in VS 2012 is currently set to IEnumerable, which does not support OData.

You can find more about this here and here.

like image 143
MilkyWayJoe Avatar answered Sep 28 '22 00:09

MilkyWayJoe


It is possible to have nested resources (at least in URL construction), but there's not a great deal of support for in MVC; you'll have to do most of the work yourself.

Firstly, you'll need to create a route to deal with your structure:

url: "sellers/{sellerId}/products",
defaults: new { controller = "sellers", action = "GetProducts" }

Then, you'll want to create the GetProducts action on your "Sellers" controller, which this route should direct callers to:

[HttpGet]
public IEnumerable<Product> GetProducts(int sellerId)
{
    //TODO: Add query to return results.
}

The sellerId parameter will be passed in through the route and should be used to drive your query.

The major drawback to this approach is that the custom route makes it harder to generate URLs for links between resources, and when they get more complicated they can start matching URLs you didn't expect them to.

like image 21
Paul Turner Avatar answered Sep 28 '22 02:09

Paul Turner