10

Is there a way to query a web api through "GET", but with complex object in its parameter?

All the examples I have seen so far seems to indicate I would have to use "POST". But I don't want to use "POST", because this is a query, at the same time I don't want a function with 16 arguments because that just screams brittle.

public Product Get(int id, string name, DateTime createdBy, string stockNumber, ... ) 
    { 
          ...
    }

I want the above to be turned into:

public Product Get(ProductQuery query) 
    { 
          ...
    }

Is there a way to do this? And how do you make the HttpClient work with the above service.

Alwyn
  • 8,079
  • 12
  • 59
  • 107
  • 1
    No, you cannot pass a model via a GET request. The common practice is to pass the id to the method and then fetch the remainder of the data from the source. – Forty-Two Jan 04 '13 at 19:08

2 Answers2

23

You could have the ProductQuery parameter be passed [FromUri].

Let's say this is your ProductQuery class:

public class ProductQuery
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedBy { get; set; }
    public string StockNumber { get; set; }
}

You can annotate your action parameter with [FromUri]...

    public Product Get([FromUri] ProductQuery productQuery)
    {...}

... and have properties of ProductQuery (i.e. Id, Name, ...) can be passed in from the the query string in the Uri:

http://.../api/products?Id=1&Name=Product1&CreatedBy=1/4/2013&StockNumber=ABC0001
Maggie Ying
  • 10,095
  • 2
  • 33
  • 36
3

You may want to look at the OData support in Web API - perhaps that would do what you want? Depends on how complicated the implementation of your query is!

http://blogs.msdn.com/b/alexj/archive/2012/08/15/odata-support-in-asp-net-web-api.aspx

Richard
  • 29,854
  • 11
  • 77
  • 120
  • I agree with Richard. If it's a public api, you may end up with issues where a client may not support a GET request with a body. Discussed more at http://stackoverflow.com/questions/11091160/rest-api-get-request-with-body. – smlync Jan 04 '13 at 19:11
  • Can a POST support OData? Not the restful kind - I guess. This is tough, I need to choose between bad practice and losing out of the box OData support. – Alwyn Jan 04 '13 at 19:23
  • I am not sure why you would not want to use OData? If you use a library like [AutoMapper](https://github.com/AutoMapper/AutoMapper), you can expose only the properties of your model that you wish. You can do some pretty complex queries using OData, so I would agree with @Richard and go with Odata. – TYRONEMICHAEL Jan 04 '13 at 20:32