A couple of months ago I had written a blog comparing the two most popular .Net API Service Frameworks, Web API and WCF where I compared the advantages of using the lightweight HTTP protocol to create web services over the fluent MVC architecture and the robustness and flexibility of the WCF framework. Given that the Web API framework has been gaining more popularity in recent years mainly for its simplicity and flexibiity I had decided to write another blog on this exciting framework where I described how we can use the framework to create a basic API exposing simple CRUD operations over the HTTP protocol using the MVC architecture. If you haven't read the Web API article, I would suggest that you read through it quickly before moving on with this article because today I am going to discuss some new upgrades on the Web API framework found in the Web API 2.0 and how we can take advantages of such improvements.

OWIN interface Hosting Package

 One of the more exciting features that comes with Web API 2 is that it comes with a new self hosting package called Microsoft.AspNet.WebApi.OwinSelfHost. As I've probably mentioned before, I am very much in favour of Microsoft's recent migration to the open source ecosystem of the .Net web development tools. The OWIN interface defines a set of rules (standards) between .Net web servers and web applications. It aims at decoupling the server and application and encourage the development of simple modules seperated into small chunks. Web API 2 through the use of Katana (an OWIN implementation for Microsoft servers) supports self hosting through the OWIN interface and therefore can be abstracted from the IIS server. This scenario might be ideal for small stand alone aplications or integration tests.

Routing Attributes

In the previous Web API blog post I had mentioned that one of the main advantages of Web API is its simplicity in building web services over the elegant MVC architecture using the convention over configuration principle. However, as you might have experienced with some more eleborate projects that this approach might be a little bit constricting especially when you want to expose a service with several different actions. The Web API 2 overcomes this limitation by providing the Attribute routing. On top of each action exposed, one can define the specifi route which will invoke that particular action as shown in the example below:

[Route("people/{parentId}/children")]
public IEnumerable<Person> GetChildrenByParent(int parentId) { ..... }

Sounds great right? But what if you're still using Web API 1.0 and the migration to the Web API 2.0 is not possible for 1 reason or another? No need to worry about it as there is a nice Nuget package which will allow you to have the exact same functionality for your web services. If you need to download this Nuget package, follow this link.

IHttpActionResult

 In Web API 1 we basically had 2 ways of creating a response from an API action, we could either return the object itself and let the Web API pipeline to convert it to an HttpResponseMessage or we could return a raw HttpResponseMessage in which case one had to manually construct it from scratch while bypassing all the juices of the Web API framework such as formatters and content negotiation. In Web API 2 we have an extremely powerful 3rd option which is the IHttpActionResult. The IHttpActionResult can be simply thought of a wrapper around the HttpResponseMessage. It's essentialy a factory for the HttpResponseMessage and by implementing the interface you can provide specific instructions on how a new response should be constructed. The interface itself has just one method, the ExecuteAsync method which can be implemented to modify the response returned by the service.

 CORS - Cross Origin Resource Sharing

When using API services, its not unusual to have your service method called from an AJAX javascript method originating from a page hosted on a different domain, more commonly known as a cross-domain call. Browsers usually don't allow making cross domain calls due to a policy called the'same origin policy'. CORS is a mechanisim that allows a web page to make an AJAX call to a domain other than the domain which actually rendered the specific web page. CORS is a compliant W3C standard and now the Web API 2 framework has support for it. You can restrict the URL from where the calls could potentially originate. In order to define these CORS permissions, you would need to reference the CORS libraries. The CORS libraries can be retrieved from the following Nuget package link

In order to enable CORS on your action method, first and foremost you need to enable the CORS configuration in the WebApiConfig file as shown below:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }

 On the API method itself you would need to use the EnableCors attribute in order to give permission to a particular domain to make the call to your service as shown below:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://myclient.incredible-web.com", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

 An thats it! The TestController class will allow calls originating from the http://myclient.incredible-web.com domain.

Web API OData

 I left my favourite for last, the OData protocol integration for your WebAPI service. For those of you who are not familiar with the Open Data Protocol, I'm going to explain what this protocol actually does and how useful it can be for API providers and consumers.

I this its best if I describe the awsomeness of this protocol with an example. Imagine you're working with a 3rd party provider who provides you with a list of available flights from one destination to another. Now each item in the list is an available flight right, it contains the flight number, flight duration,  number of stops, airline provider and so on. Now lets say that you're going to create a filter for your website which will retrieve only flights which are longer than two hours (for the sake of argument). Traditionally what you would do is the following:

  1. Get all flights given the point of origin and destination
  2. Filter through the retrieved list and get the once which are longer than two hours
  3. Return the list to the users

A couple of months ago I had written a blog comparing the two most popular .Net API Service Frameworks, Web API and WCF where I compared the advantages of using the lightweight HTTP protocol to create web services over the fluent MVC architecture and the robustness and flexibility of the WCF framework. Given that the Web API framework has been gaining more popularity in recent years mainly for its simplicity and flexibiity I had decided to write another blog on this exciting framework where I described how we can use the framework to create a basic API exposing simple CRUD operations over the HTTP protocol using the MVC architecture. If you haven't read the Web API article, I would suggest that you read through it quickly before moving on with this article because today I am going to discuss some new upgrades on the Web API framework found in the Web API 2.0 and how we can take advantages of such improvements.

OWIN interface Hosting Package

 One of the more exciting features that comes with Web API 2 is that it comes with a new self hosting package called Microsoft.AspNet.WebApi.OwinSelfHost. As I've probably mentioned before, I am very much in favour of Microsoft's recent migration to the open source ecosystem of the .Net web development tools. The OWIN interface defines a set of rules (standards) between .Net web servers and web applications. It aims at decoupling the server and application and encourage the development of simple modules seperated into small chunks. Web API 2 through the use of Katana (an OWIN implementation for Microsoft servers) supports self hosting through the OWIN interface and therefore can be abstracted from the IIS server. This scenario might be ideal for small stand alone aplications or integration tests.

Routing Attributes

In the previous Web API blog post I had mentioned that one of the main advantages of Web API is its simplicity in building web services over the elegant MVC architecture using the convention over configuration principle. However, as you might have experienced with some more eleborate projects that this approach might be a little bit constricting especially when you want to expose a service with several different actions. The Web API 2 overcomes this limitation by providing the Attribute routing. On top of each action exposed, one can define the specifi route which will invoke that particular action as shown in the example below:

[Route("people/{parentId}/children")]
public IEnumerable<Person> GetChildrenByParent(int parentId) { ..... }

Sounds great right? But what if you're still using Web API 1.0 and the migration to the Web API 2.0 is not possible for 1 reason or another? No need to worry about it as there is a nice Nuget package which will allow you to have the exact same functionality for your web services. If you need to download this Nuget package, follow this link.

IHttpActionResult

 In Web API 1 we basically had 2 ways of creating a response from an API action, we could either return the object itself and let the Web API pipeline to convert it to an HttpResponseMessage or we could return a raw HttpResponseMessage in which case one had to manually construct it from scratch while bypassing all the juices of the Web API framework such as formatters and content negotiation. In Web API 2 we have an extremely powerful 3rd option which is the IHttpActionResult. The IHttpActionResult can be simply thought of a wrapper around the HttpResponseMessage. It's essentialy a factory for the HttpResponseMessage and by implementing the interface you can provide specific instructions on how a new response should be constructed. The interface itself has just one method, the ExecuteAsync method which can be implemented to modify the response returned by the service.

 CORS - Cross Origin Resource Sharing

When using API services, its not unusual to have your service method called from an AJAX javascript method originating from a page hosted on a different domain, more commonly known as a cross-domain call. Browsers usually don't allow making cross domain calls due to a policy called the'same origin policy'. CORS is a mechanisim that allows a web page to make an AJAX call to a domain other than the domain which actually rendered the specific web page. CORS is a compliant W3C standard and now the Web API 2 framework has support for it. You can restrict the URL from where the calls could potentially originate. In order to define these CORS permissions, you would need to reference the CORS libraries. The CORS libraries can be retrieved from the following Nuget package link

In order to enable CORS on your action method, first and foremost you need to enable the CORS configuration in the WebApiConfig file as shown below:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }

 On the API method itself you would need to use the EnableCors attribute in order to give permission to a particular domain to make the call to your service as shown below:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://myclient.incredible-web.com", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

 An thats it! The TestController class will allow calls originating from the http://myclient.incredible-web.com domain.

Web API OData

 I left my favourite for last, the OData protocol integration for your WebAPI service. For those of you who are not familiar with the Open Data Protocol, I'm going to explain what this protocol actually does and how useful it can be for API providers and consumers.

I this its best if I describe the awsomeness of this protocol with an example. Imagine you're working with a 3rd party provider who provides you with a list of available flights from one destination to another. Now each item in the list is an available flight right, it contains the flight number, flight duration,  number of stops, airline provider and so on. Now lets say that you're going to create a filter for your website which will retrieve only flights which are longer than two hours (for the sake of argument). Traditionally what you would do is the following:

  1. Get all flights given the point of origin and destination
  2. Filter through the retrieved list and get the once which are longer than two hours
  3. Return the list to the users

You might agree with me that retrieving all the flights and then filter the list to only get the desired ones is not efficient to say the least. We're wasting valuable resources while making our users wait longer to get their desired results (we all know how slow these airline search engines are).

One way to solve the problem is to ask the 3rd party provider to include a filter parameter which will allow you to input the time duration. This will force the API to return only the flights with your specific durations and problem solved right? Of Course NOT! If the 3rd party provider is kind enough to upgrade their API because one of their clients needs extra filters, they will surely not do it for free. It is time consuming for both parties, it involves meetings, roadmap changes, plans and a bag load of $$$. What happens if in a few months you decide to have another filter, which will allow you to search for flights using the number of stops too? Will you go thorugh the whole charade again?

The OData protocol has the answer for both the API provider and the consumer. What if the API returned a list of items which is practically queryable? What if entities could be filtered, modified and analyzed throgh the API itself using some simple queries on the API call? That's essentially what OData does. It allows the consumer to have some restricted access to the Entity Data Model without compromising the integrity and reliability of the server. The provider can authenticate calls and even choose which operations are available on the Queryable List and which are phrobited.

Although OData was supported by WCF and through some external libraries by Web API 1.0, it is now, with Web API 2.0 that we actually have real support for the $expand, $select  and $value operators. In the coming weeks I shall be posting an nice article with more in depth features provided by OData integrated with Web API 2. I will show you how you can allow your API consumers to filter their data and view which underlying Entity Data Model they can access so that they can be aware of the entities and properties available through the API. 

I hope I gave you enough reason to try and use Web API 2 for your API services in the future and I hope you find it as interesting and as powerful as I did. As promised, in a few weeks I will be posting a full blown example of the OData protocol combined with the lightweight Web API 2.0 framework. Trust me, you wouldn't want to miss it!

Thanks for reading and as always, if you have any questions don't hesitate to comment and ask below.

Shaun