Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Web API, or Cutting Out the Middle Man

5.00/5 (5 votes)
15 Jul 2014CPOL5 min read 10.8K  
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 it's 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.

Reddington

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.

image

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.

image

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.

C#
public class HomeController : Controller
   {
     //
     // GET: /Home/
     public ActionResult Index()
     {
       return View();
     }
   }

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 will also be creating a view for this “Index” action, called “Index.cshtml”. Below is the view.

HTML
<!DOCTYPE html>

<html>
   <head>
   <meta name="viewport" content="width=device-width" />
   <title>Index</title>
   </head>
   <body>
   <div> 

   </div>
   </body>
</html>

Ok, now for the fun part. We are going to build a 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 stuff later.

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

image

We are going to select a “Web API 2 Controller – Empty”. Given that we 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:

C#
public class MathController : ApiController
   {
      public int AddNumbers(int number1, int number2)
       {
          int answer = number1 + number2;
         return answer;
      }
   }

We have a single action that is called “Get”, and allows 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 its 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:

C#
public static void Register(HttpConfiguration config)
  {
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
    );

    config.Routes.MapHttpRoute(

      name: "MathApi",
      routeTemplate: "api/{controller}/{number1}/{number2}"
      );
  }

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:

HTML
<script type="text/javascript">
   function AddNumbers()
   {
     var num1 = $("#number1").val();

     var num2 = $("#number2").val();

     $.ajax({
       url: 'http://localhost:50008/api/math/' + num1 + '/' + num2,
       type: 'Get',
       dataType: 'json',
       success: function (data) {
         $("#divAnswer").html("The answer is " + data);
       }
     });
   }
 </script>

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

image

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

Batman66

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 this topic.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)