Query composition with the ASP.NET Web API

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 do is change this to return an IQueryable<Product> instead of an IEnumerable<Product> and most of the work is done.

   1: public class ProductsController : ApiController


   2: {


   3:     private NorthwindContext _db = new NorthwindContext();


   4:  


   5:     // GET /api/<controller>


   6:     public IQueryable<Product> Get()


   7:     {


   8:         return _db.Products;


   9:     }


  10:  


  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.

image



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.



image



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



image



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



image



 



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?



 



Enjoy!

2 thoughts on “Query composition with the ASP.NET Web API

  1. @Brock. No they won’t. But now we can add it and send a pull request ourselves. Just trying to figure out how to do so to fix the decimal bug I reported. Not much luck yet.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>