Tuesday, 10 March 2015
How to use OData query syntax with Web API
#asp.net#odata-query-syntax#web-api
This article was published at GitHub. It is open source and you can make edits, comments etc.
I was just messing around with a Web API and thought "I had better add some kind of filtering support here". I was vaguely aware of OData and knew that OData was the way to do filtering, sorting etc with REST APIs (.net Web API in my case), but had never looked into it.
When I did look into it, I have to say ... it blew my mind! It is soo easy to do and gives you so much power over your data.
In the spirit of trying to 'learn in public', I've captured the main details here.
OData query syntax is a standard way of querying RESTful APIs using a pre-defined syntax that allows the calling client to define the sort order, filter parameters and pages of data that is returned.
The full syntax can be found in section 5 of the OData Version 4.0 Part 2 specification but here are some quick examples of how the syntax is used:
This is where things get really awesome - it is super, super easy to change a regular Web API controller to support OData query syntax - once you know how to do this, you'll never not do it!
If we assume we are starting from a regular Web API project (File > New Project > ASP.net Web Application > Web API), you first need to add a scaffolded controller which you can do by following these steps:
NOTE: You do not need to choose the 'Web API 2 OData Controller...' option, you can add the query syntax to any controller
Once you've setup your controller, you should end up with a simple controller which has a default GET action that looks a little like this:
// GET: api/Peoplepublic IQueryable<Person> GetPeople(){return db.People;}
This action will simply return all the rows in the 'People' table of the database with no ability to filter, sort etc. To add full OData query support, you need to make a few changes:
Install-Package Microsoft.AspNet.Odata
using System.Web.OData;
[EnableQueryAttribute]
attribute to your GetPeople action.AsQueryable();
to your return line so it looks like this: return db.People.AsQueryable();
Your finished code will look something like this:
// GET: api/People[EnableQueryAttribute]public IQueryable<Person> GetPeople(){return db.People.AsQueryable();}
That is all there is to it! .... now you have this setup, you can use the full OData syntax to query sort etc without any extra code.
Use the best onlineHTML, CSS and JS tools at html-css-js.com: editors, code optimizers and more.
Got a comment?
All my articles are written and managed as Markdown files on GitHub.
Please add an issue or submit a pull request if something is not right on this article or you have a comment.
If you'd like to simply say "thanks", then please send me a .