Introduction to Web API : Part 1

I’ve been thinking of this blog post since I’ve met Web API. I’ve been following Asp.net Web API for 8-9 months already. I have faced all painless procedures of Web API because I have started with the alpha version of it :) . Microsoft changed the structure of Web API when promoted from alpha to beta and beta to RTM. For those who are following it recently, may realize that tutorials before March 2012 and June 2012 are deprecated and useless. Web API had a significant change compared today. Until Web API existence, I was using WCF mostly on my projects. After realising advantages of Web API, WCF remained as an old-fasion web service style. You may be 2X faster on development time to create web services to connect your server with your clients using Web API if you know what you need to do. Here is a really good blog post written by Ido Flatow that you may need to concern why you should use Web API and to realise the difference between WCF and Web API.

What is Web API
Web API allows you to create a Restful Web API methods for reaching broad range of clients including mobile and web clients. Theoretically, it is a framework based on Http services so that you may create web services to send/get data from your clients in an object-oriented way. Web API highly customisable, scalable framework on top of Asp.Net MVC “that is build on top of anything but .NET”. It really works well on Windows Azure if the scalability has a major role on your system. In addition to this, It is non-SOAP service, also known as a Restful web service. Compared to WCF, it doesn’t need to have lots of configurations and deployment settings, it is more like deploying a simple WCF service and you are ready to use!

What have changed so far?

There are a lot change on Asp.Net Web API but I will talk about 2 of them. One of the most significant change is on Posting Methods and parameter bindings. In Alpha version, you were able to post parameters as a plain/text like you do on MVC. Actually, Web API had 2 different binding methods : Formatter and Parameter Binding. Formatter stands for formatting your parameters with simple type of parameters like you do in MVC. For example :

[HttpPost]
public void AddUser(string Username, string Password)

In alpha version you were able to send data to this method by posting “Username=Kemal&Password=foo” with text/plain content type. However, Microsoft decided to enable posting just only for parameter binding which the method above needed to be converted to:

[HttpPost]
public void AddUser(User user);

where User class contains Username and Password property as string. The idea behind is since Web API only uses parameter binding, accepts one and only one object from POST data and converts it to an strongly typed class as defined. It was one of the radical changes while changing the version from alpha to beta. This change was a painful and a waste of time for developers who already created their web services on Web API and needed to be converted all of the things from the scratch.

The other change was on uploading files using Web API. To tell you the truth, while Web API was on beta version, It was really hard to handle DataStreamProvider however in release version, uploading a file over Web Api have never been that much easy! Moreover, async support has come to Web API while uploading your files, hence, Web API is now more responsive than ever. I will be showing how to create custom multipart data stream providers to upload your files over Web API.

Creating your First Web API

If you are using Visual Studio 2012 Web Api framework comes built-in with it including project templates. If you are familiar with Asp.NET MVC Web API classes are pretty much is the same with ASP.Net MVC controllers. The only difference is ASP.Net MVC controllers are inherited from Controller class while Web API classes are inherited from ApiController. Now let’s get started.
1- Open your Visual studio and go to File > New Project.
2- Type “Asp.NET MVC Web Application” to search at the upper right corner on the dialog. (Don’t forget to name your application :) )
3- Choose Empty template so that we can do it from the scratch.

I assume you are familiar with MVC, your project is created with the same structure as you create an MVC application. Now click right to your controller and add controller like below.
Screen Shot 2013-02-08 at 3.37.43 AM

Now name your controller. Note that you should not remove Controller suffix of your controller otherwise Web API will not able to find your controller. After naming your controller, you need to change its template to Empty Api Controller.

Screen Shot 2013-02-08 at 3.41.58 AM

Now your controller is created, we are able to work with it. We are going to start with simple hello world method.

[HttpGet]
public string SayHello(){
   
   return "Hello World";
}

Paste the code above into your controller and run your application. We firstly determined the type of Http Method with “HttpGet” so that it is reachable by simply typing URL http://localhost/api/Users/SayHello to browser. Note that, we need to give controller name before calling the method, hence, your methods will be in a structured way. In addition to this, before controller name we typed api/ because routing config of Web Api is pre-determined when creating Mvc Application. This could be changed in App_Start/WebApiConfig.cs file.

After typing URL into your browser, the result is downloaded as json or xml file. This is because Web API checks your Http Accept header and returns XML or JSON depending on the type of your header. You may get XML if you use Google Chrome and JSON on Internet Explorer, since Chrome sends Http-Accept header application/xml instead of application/json in the first place.

Learning the Basics

I guess, you now have a bit clue about how Web API behaves on a simple request and response. Let’s going deeper on it. What we are going to create is a simple user and add it to a user list that will be persisted until our web application is closed.

1- Go to Models folder right click and Add > New Item.
Screen Shot 2013-02-08 at 4.12.12 AM

2- Add code class and name it User.cs.
3- Add 2 string properties “Username” , “Password”
Screen Shot 2013-02-08 at 4.14.43 AM

Now go back to UsersController. We are now going to create a static list of users object so that it will be persisted until our application gets terminated. To do this type the code below as a property of UsersController

public static List<User> Users = new List<User>();

Now that we created some kinds of a container that can store a List of user objects without having a physical database. By the way, it is not a good way for real-world applications but a good demonstration without creating a database :). Moreover, while making any operation like adding, editing, updating an object, it is recommended to use HttpPost method to make it more convenient because there is a limit on parameters while sending with GET method of Http protocol.

I will show you how to add a new user into our mock container using both HttpGet and HttpPost methods. First of all, remove SayHello method from UsersController. I want to keep it simple so that starting with HttpGet method. We are about to create a method that takes two simple parameters Username, Password as string, create user object internally, add it to our container, and give boolean result in return. Keep in mind that, Web Api is case-sensitive, hence, you will query with parameters as like as you type it.

[HttpGet]
public bool AddUser(string Username, string Password){
    User user = new User() { Username = Username, Password = Password } ;
    Users.Add(user);
    return true;
}

[HttpGet]
public List<User> AllUsers(){
    return Users;
}

I think the code above is pretty much straight forward, so that, I’m not going to walk through over them.Run your application and add some users by typing http://localhost:YOUR_PORT/api/Users/AddUser?Username=Foo&Password=Bar . It will again return JSON/XML file. After adding bunch of data, query to AllUsers so that you will retrieve as a list of user objects with JSON/XML format. Now let’s write AddUser method with a HttPost. Actually, HttpPost method is pretty much the same, however, you are not able to post it over URL. Since I’m actually a mac user, I prefer using curl library over terminal and it helps me a lot to test my HttpPost methods. For those who wants to use it over windows please refer here

[HttpPost]
public bool AddUser(User User){
   Users.Add(User)
   return true;
}

I assume you downloaded and installed curl you may type to reach HttpPost like :
curl -H ‘Content-type:application/json’ -d ‘{ “Username” : “Foo” , “Password” : “Bar” }’ http://localhost:YOUR_PORT/Users/AddUser

What we have done in here is we set Content-type of our data that we are about to post so web-api will recognise and convert it to strongly-typed User class on the fly and execute our method.

As you play a little bit more with Asp.Net Web API you will have more questions to ask. This is just the first part of a long series of Web Api. I hope you understand the basics and the underlying idea of Web Api. As we go deeper upcoming days, you will have a lot to learn. Stay tuned, part 2 is coming soon ;)

P.S: I added the source codes, we have done so far.
MvcApplication1 Source Codes

2 Thoughts on “Introduction to Web API : Part 1

  1. A small note:

    “… Web API highly customisable, scalable framework on top of Asp.Net MVC …”

    It’s actually not. To be more accurate, ASP.NET Web API doesn’t sit on top of anything other than .NET. Have a look:

    http://www.tugberkugurlu.com/archive/newsflash-asp-net-web-api-does-not-sit-on-top-of-asp-net-mvc-in-fact-it-does-not-sit-on-top-of-anything

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation