Building RESTful Services with Web API

One of the features I’ve most been looking forward to in the Visual Studio 11 beta is the Web API. It’s been my long-term goal to build an iPhone app to supplement my jQuery mobile view for my personal website, (once I learn Objective-C), and a RESTful API is just what I need. In this post, I’m going to explain what the Web API is and how you can use it. In subsequent posts, I’ll look at the issues with combining Web API controllers with Entity Framework data, and the thorny issue of whether to expose oData/IQueryable endpoints. There’s a lot of ground to cover, so let’s get started.

What is the Web API?

The Web API is a new feature of the latest release of ASP.NET MVC. It adds a new controller base type, ApiController, which allows you to return JSON data directly from RESTful urls. (It was always possible to return JSON from Controllers by using the Json() method, but ApiControllers don’t return views, just serialized data. We can also easily expose oData endpoints: more on that in a later post.)

The Add Controller wizard now has new options:

The controller wizard

When you select an empty API controller with read/write actions, you get a basic stubbed template as a starting point:

The empty controller

There are a couple of changes I need to make at the outset:

  1. I want to return a list of BeverageTypes (spirits, non-alcoholic, wine, etc.) rather than a string array,
  2. I already have a BeverageTypeController as part of my MVC application, so I need to change the namespace from the default (in this case, Cocktails.Controllers) to Cocktails.Controllers.API to avoid a name collision.

Here is part of the changed class with a little sample data for testing purposes:

Method returning IEnumerable

Now I can make the following RESTful query ”http://[site]/api/BeverageType” and get back JSON data:

Output from the RESTful call

The controller also stubbed out another method for me that accepted an id argument. With a little refactoring to move my data into a separate method – BeverageTypes() – I can now write code like this:

Get with an argument

Now I can make a RESTful query with an argument, thus – ”http://[site]/api/BeverageType/1”:

output from the call

So, it looks like I have a nice, simple way of exposing my data as a RESTful API from within an ASP.NET MVC application. I should be able to consume my data from new clients and/or allow third parties to integrate with my site. Unfortunately, it turns out that once you add the Entity Framework into the mix, things get a whole lot more complicated – and that’s going to be the topic of my next post.

Kevin Rattan

For related courses, check out Building Web Applications with ASP.NET MVC from Learning Tree.

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.