Web API Deep Dive - OData URL Query Options (Part 4 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

OData URL Query Options

In your API, have you ever created a GET /Orders endpoint, then you discover you need to support paging, so you add an GET /Orders?start={start}&pageSize={pageSize} endpoint? Then you learn another endpoint is needed for sorting by Date, so you also create GET /OrdersByDate and GET /OrdersByDate?start={start}&pageSize={pageSize} endpoints. Before you know it, even though it feels like it should only be a single method, you end up with a collection of endpoints that all do pretty much the same thing except for basic sorting and filtering.

There is an easier way.

Turn on OData URL Query options. To do this, open App_Start\WebApiConfig.cs and add this to the top of the Register method:

// Allow OData Queries on all methods that return IQueryable

Next, return an IQueryable from your GET /Orders endpoint and consumers of your API can do paging, filtering, and sorting. As long as the IQueryable comes all the way from your Entity Framework context, then the paging, filtering, and sorting is all done where it should be - in the database.

For example, if someone only wanted to get the first 10 orders, they could call /Orders?$top=10. The paging for $top=10 is implemented automatically - you don’t have to implement anything other than returning an IQueryable and turning on OData URL Query Options as described just above.

For more documentation on the OData URL conventions, see http://docs.oasis-open.org/odata/odata/v4.0/os/part2-url-conventions/odata-v4.0-os-part2-url-conventions.html#_Toc372793790. Please note that the technique described in this post does not implement a full OData service - it only uses the querystring structure of OData to allow for filtering, sorting, and paging. A full OData web service can be provided by Web API, but that is beyond the scope of this series.

In the next post in the series, we’ll see how you can return a custom Data Transfer Object (DTO) from your API methods, where the DTO differs from your EF models, but without breaking the functionality provided by OData Query Filtering.