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, www.cocktailsrus.com (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:
When you select an empty API controller with read/write actions, you get a basic stubbed template as a starting point:
There are a couple of changes I need to make at the outset:
Here is part of the changed class with a little sample data for testing purposes:
Now I can make the following RESTful query “http://[site]/api/BeverageType” and get back JSON data:
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:
Now I can make a RESTful query with an argument, thus – “http://[site]/api/BeverageType/1“:
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.
For related courses, check out Building Web Applications with ASP.NET MVC from Learning Tree.