JSON and RESTful Web services using ASP.NET MVC WebApi–Its what every Web Programmer should know !

In my last post I indicated as to how Microsoft & MS technologies have made programming for the web simple and easy. I also suggested how these same MS technologies have created misinformed web developers (like me) as well.

All the abstraction over the RESTful nature of HTML (or HTTP) have solved at least one purpose. They have managed to “abstract” a large number of developers from the inner workings of HTML or for that matter the HTTP/web. Well, I would say making an Intranet business Application using ASP.NET does not necessarily require you to have any knowledge regarding JSON or the RESTful nature of Web for that matter. Using Web forms and WCF you could easily create a Service Oriented Application without much knowledge of how the web actually works. But if you just dive in a bit deeper you’ll get to know how WCF has its own quirks.

Ok, enough of “MS bashing” and “Developer belittling”. Learning the ropes of JSON is not that tough I would say.

Ironically, with the recent emphasis MS has laid on introducing Open source packages into our VS projects, it has become easier to learn things like JSON and programming in HTML as it should be(RESTful) using things like ASP.NET webapi.

Lets get over that block in our head and quickly create a running JSON example (using Visual Studio of course 😉 😛 )

Before Starting, it would be great to have some background.

So, What is JSON?

Its short for JavaScript Object Notation. In theory we can describe CLR object as an equivalent Object in JavaScript. As you know JavaScript is not a strictly object oriented language, BUT it has some features of OOP Language.

Why is JSON popular?

So, folks using WCF should know that the data transferred and consumed in a web application is usually in the Form of XML. That is any CLR object could be easily represented as an equivalent XML document. JSON is quite similar but has a lot less characters when representing the same data. Hence its lighter and faster across the wire. Also, its very easy to consume JSON objects in HTML/JavaScript as they are actually JavaScript objects.

What do we mean by RESTful nature of Web?

REST stands for Representational State Transfer. What it says is that any request in/over HTTP should be one of the following types:

  • GET – Get a resource from a server
  • POST – Post/Insert/Input some information on a server
  • PUT – Update some information on a server
  • DELETE – Delete some information on a server

These are the standard “verbs” (along with a few others) supported by HTTP protocol.

This is where ASP.NET MVC WebApi comes into picture. It helps us create a Web service on the paradigms of REST. Its similar to WCF with the difference that an ASP.NET WebApi service is usually consumed by a Client(browser) and we have more control as to what format (XML/JSON) flows through the wire.

Enough of theory, Lets get to the Hands On!

1. Open File –>new Project and select ASP.NET MVC 4 –> Internet template

image_thumb5

2. Add a new New Class to the Models Folder of your Solution as below :

public class Person
{
public string Name { get; set; }
    public int Age { get; set; }
    public string Sex
{ get; set; }
}

This is the class which we’ll be serializing and consuming in JavaScript

3. Right click on Controllers folder and Add a new Controller; Select Empty Api Controller from the dropdown options as shown below :

image_thumb11

4. Add a new method returning IEnumerable to the PersonApiController just added. Our objective is to send over a list of persons from the server and consume it via JSON in JavaScript.

public class PersonApiController : ApiController
    {

[HttpGet]
public IEnumerable Get()
{
List lstPerson = new List() {
new Person(){Name=”Rahul“,Age=28, Sex=”M“},
new Person(){Name=”Chinmoy“, Age = 28, Sex=”M“},
new Person(){Name=”Charu“,Age = 27, Sex=”F“}
};

return lstPerson;
}
}

Just one more thing. Since its a RESTful service, we need to decorate our function with one of the HTTP verbs. In this case we’ll use [HttpGet]

We are now done with the server side implementation. Now onto the client side of things.

5. Open up Index.chstml in the Home Views Folder and add the following markup at the end of the page. What we are doing here is that we are placing a button on whose click we’ll make a call to get a list of people. Upon successful completion, we are going to display the details in a table.

@Scripts.Render(“~/bundles/jquery“)

<input type=”button” id=”btnGetPeople” value=”Get People“>
<div id=”divPeople“>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
</tr>
</thead>
<tbody id=”tBody“>
</tbody>
</table>
</div>
<script type=”text/javascript“>
var AllPeople;
$(document).ready(function () {

$(“#btnGetPeople“).click(function () {
//Do an AJAx Call here
$.getJSON(‘@Url.Action(“PersonApi“, “api“)’)
.done(function (data) {
// On success, ‘data’ contains a list of Person.
AllPeople = data;

for (var i = 0; i < AllPeople.length; i++) {
$(“tBody“).append(‘
‘ + AllPeople[i].Name + ‘ ‘ + AllPeople[i].Age + ‘ ‘ + AllPeople[i].Sex + ”);
};
});

});

});
</script>

So what does the above code do?

  • It creates markup for a button and an empty html table
  • It declares a JavaScript variable AllPeople for storing the returned list of people. As you can see JavaScript supports implicit variable declaration.
  • It makes a Call to our PersonApi Controller using a jQuery method called $.getJSON(). Its this call that does all the magic.

The ASP.NET MVC WebApi is intelligent enough to identify the format in which data is requested. Here we are requesting JSON so the WebApi Controller action returns JSON; If we request XML it will happily return XML.

  • Now, once the web service call is “done” we iterate through our JSON object and populate our table as shown below.

image_thumb21

Once you Click the “Get People” button and If you place a debugger and see how the AllPeople Variable looks like once populated by the returned “data”, it looks like below :

image_thumb31

Its like any other array which we can iterate over

The final result is as under:

image_thumb41

We have successfully consumed and used JSON in our ASP.NET application over a REST service using WebApi. That’s how easy it is folks!

Of course, this was one of the most basic examples I could come up with, BUT hey, you gotta start somewhere (if you haven’t already started)

WebApi is cool! JSON is great! (WebApi + JSON) = Awesome !!

If you are creating for the web and are not using these technologies, I would suggest you start being Awesome right away.

Building, consuming and deploying WebApi services has a few Gotchas, which I’ll discuss in a future blog post.

Do post your views/comments/feedback/questions below. I’ll try my best to answer them.