Query composition with the ASP.NET Web API

Wednesday 21 March 2012

Having the ASP.NET Web API as a REST service returning data is kind of nice but to be efficient on the wire we don’t want to return more data that required only to discard it in the client.


As we have seen in a previous post just returning a collection data was real easy.


As it turns out changing the service so the client can filter data is almost just as easy. In the previous example we returned an IEnumerable<Product>. All we need to di is change this to return an IQueryable<Product> and most of the work is done.

   1: public class ProductsController : ApiController
   2: {
   3:     private NorthwindContext _db = new NorthwindContext();
   5:     // GET /api/<controller>
   6:     public IQueryable<Product> Get()
   7:     {
   8:         return _db.Products;
   9:     }
  11:     // GET /api/<controller>/5
  12:     public Product Get(int id)
  13:     {
  14:         return _db.Products.Single(p => p.ProductID == id);
  15:     }
  16: }

Loading the products with the original URL returns exactly the same result as before.


But now the client can also decide to order and filter data. This request “http://localhost:6876/api/Products?$orderby=ProductName&$skip=10&$top=5” returns only product 11 to 15 ordered by the product name.


You can also search for specific data using the $filter clause like this “http://localhost:6876/api/Products?$filter=ProductName eq 'Chocolade'


Or something like “http://localhost:6876/api/Products?$filter=startswith(ProductName, 'Cha')



Sweet right? And all of that by just changing IEnumerable<T> to IQueryable<T> Smile 


In fact the only thing I would like to see added to this was projections. After all we don’t do a “Select * from Table where …” either right?