Blog Moved

My blog has moved!

Friday, February 28, 2014

Web API, or Cutting out the middle man

Ok, so I’m back with another blog post.  Tonight I sit here, with the wife and the munchkin passed out and am taking this singular opportunity to catch up on the Blacklist and thinking about the latest blog post.  And then it hit me, Web API.

This past week I’ve been doing a lot of reading and research into Web API, and I have to say I’m impressed with how completely flexible it is, and the overall possibilities it opens up.

All of us as Web developers have been tasked whether we like it or not with working towards a common goal….RIA.  Or Rich Internet Applications.  The challenge is that despite the Web being a disconnected model, to make the user feel like its not. 

I have to admit that Web API, is a technology that quickly and simply allows us developers to work towards that by allowing a new way of sending data back and forth between the client and the server without needing a postback of the page, in any capacity.

In short, Web API functions a lot like Raymond Reddington, it transmit and utilizes information in a way that cuts through all the red tape.  In the show, thanks to underworld connections, Reddington is able to trade back and forth information without having to go through proper channels that the FBI has to. 


My job is to deal in information…all kinds. 

But analogies aside, Web API utilizes a special type of controller to allow the ability to sending and receiving information. 

In MVC, the controller is used to route requests from the server to the client.  It traditionally is used to send requests to the server for specific views, and allowing the server to send back the appropriate view after performing any server side functions. 

In Web API, controllers function largely in the same way.  They allow calls too be made to the server, those requests are processed and responses are sent back.  The key difference is though that Web API does it without having to be weighed down by views and models and instead is primarily concerned with passing data.

Enough Theory though, let’s look at the code.

When you create a new project in Visual Studio 2013, thanks to Project Katana there is now only an “ASP.NET Web Application”.  When you do, you will receive the following prompt.


When your project is created, you are given the option, no matter what type of application you create to add “WebForms”, “MVC”, and / or “Web API”.  For this project We are going to select “MVC”, and “Web API”.

Now, if you look at your Solution Explorer, you will notice that several key folders and classes have been created for you.


First and foremost, I’m going to create a basic MVC Controller and view to display a page.  Below you will see our Home Controller.

   1:  public class HomeController : Controller
   2:      {
   3:          //
   4:          // GET: /Home/
   5:          public ActionResult Index()
   6:          {
   7:              return View();
   8:          }
   9:      }

Just a simple controller that is going to render a view, that’s it.  Nothing special, after all this blog post is about Web API not MVC.  I also will be creating a view for this “Index” action, called “Index.cshtml”.  Below is the view.

   1:  <!DOCTYPE html>
   3:  <html>
   4:  <head>
   5:      <meta name="viewport" content="width=device-width" />
   6:      <title>Index</title>
   7:  </head>
   8:  <body>
   9:      <div> 
  10:      </div>
  11:  </body>
  12:  </html>

Ok, now for the fun part.  We are going to build an Web API controller that is going to add two numbers together.  I know ground breaking stuff, but for right now I’m just trying to show the basics, watch this space for more advanced later. 

To start, right click on “Controllers” and select “Add Controller”.  After doing so, you will be prompted with the following menu:


We are going to select a “Web API 2 Controller – Empty”.  Given that are creating a very basic Web API controller, this will suit our purposes.  But it’s worth noting that you do have the option to create Web API controllers that are already set up with Scaffolding for Entity Framework or Read / Write actions.

We are going to name our controller “MathController”, and set it up as follows:

   1:  public class MathController : ApiController
   2:      {
   3:          public int AddNumbers(int number1, int number2)
   4:          {
   5:              int answer = number1 + number2;
   6:              return answer;
   7:          }
   8:      }

We have a single action that is called “Get”, and allow for passing two numbers and returning an integer amount. 

Now, the next step is that one I find most people miss.  For Web API to work, we need to set up routing for this controller.  For MVC controllers we don’t need to do this because it is already done for us.  But because we have a lot more flexibility with Web API we need to tell the application how to handle it’s routing.

In the “App_Start” folder, you will see a file called “WebApiConfig.cs”.  By default, Visual Studio created the most basic routing I’ve ever seen.  We are going to add an additional route to this file so it looks like the following:

   1:  public static void Register(HttpConfiguration config)
   2:          {
   3:              // Web API configuration and services
   5:              // Web API routes
   6:              config.MapHttpAttributeRoutes();
   8:              config.Routes.MapHttpRoute(
   9:                  name: "DefaultApi",
  10:                  routeTemplate: "api/{controller}/{id}",
  11:                  defaults: new { id = RouteParameter.Optional }
  12:              );
  14:              config.Routes.MapHttpRoute(
  16:                  name: "MathApi",
  17:                  routeTemplate: "api/{controller}/{number1}/{number2}"
  18:                  );
  19:          }

Notice the placeholders we defined, denoting the controller and numbers needed.  The next step now is building the client side script to call it.  That script is shown below:

   1:  <script type="text/javascript">
   2:          function AddNumbers()
   3:          {
   4:              var num1 = $("#number1").val();
   6:              var num2 = $("#number2").val();
   8:              $.ajax({
   9:                  url: 'http://localhost:50008/api/math/' + num1 + '/' + num2,
  10:                  type: 'Get',
  11:                  dataType: 'json',
  12:                  success: function (data) {
  13:                      $("#divAnswer").html("The answer is " + data);
  14:                  }
  15:              });
  16:          }
  17:      </script>

Now, when you run this, you get the followiing:


Ok, so that’s well and great.  And Holy-No-Postback-Batman.


Great Scott!

So, I know some of you are saying that you could just have easily built that into your MVC controller using a JSON response, and you’d be right.  The benefits of Web API controllers are really as follows in my experience:

  • Separation of Concerns:  We as programmers strive to separate our classes to have a singular concern, so that they are easier to manage, easier to follow, and easier to test and maintain.  Arguably by using the MVC controller for these types of requests you are mixing navigation concerns with Business / Data Concerns.  By separating your concerns you are making more testable code, and eliminating the possibility that changes to the navigation of your site affects how data is passed to the client.
  • More versatile:  Because we are using a custom controller we are not bound by the rules of how an MVC controller functions and can set this up to work differently.
  • Easy integration with other platforms:  Web API controllers are using HttpRequests to pass data, and all major platforms and languages can use those requests.  So by separating your logic to Web API, I can have my views, iPhone, iPad, and other platforms use the same services with minimal effort for installation. 

Well that’s it for me, like I said this was an intro blog post looking at web api, watch this space for more posts on thsis topic.