Translate

Web API Introduction

Web API is a technology which allows us to easily create services which provide an API for clients who are using the HTTP protocol. The idea behind the Web API and its first implementations were developed inside ASP.NET MVC. The actual implementation is at the framework level. So, it is available to all types of ASP.NET applications not just MVC. The Web API classes are located under the System.Web.Http namespace which is different from the MVC namespace (System.Web.Mvc).

As Web API works with HTTP so it can be used to create RESTful APIs. RESTful API is a web API that is built using HTTP. It also follows the principles of REST (Representational State Transfer). The architecture of REST consist of clients and servers both. Clients initiate requests to servers and servers process requests and return appropriate responses to client. Request and response are built around the transfer of representation of resources. A resource can be essentially coherent and meaningful concept which may be addressed. Following are the key goals of REST:

Scalability of component interactions

Generality of interfaces

Independent deployment of components

Intermediary components to enforce security, reduce latency and encapsulate legacy systems.

REST was first defined in context of HTTP. It is not limited to that protocol. It can be used for any protocol which provides a rich and uniform vocabulary which can be sent as request from client to server. Each verb in the vocabulary presents meaningful representational state. In other words, it tells the server how to treat request to produce response.

In HTTP, there are many verbs which can be included for the requests to the server. Following are most widely used verbs:

GET: Instructs the server to return specified resource. For example, if we request
/api/Pet/Fido then the server should find information about Fido and return the information and do nothing more.

POST: Instructs the server to accept information of the resource included in request.
It is used to send any type of information to server like blog post, a new
comment, a file to be uploaded etc.

PUT: Instructs the server to accept information of resource in the
request. If the resource already exists then it can be updated otherwise it can be created.

DELETE: Instructs the server to delete specified resource.

Using the ASP.NET MVC 4 Web API Project Template

Working with Web API is not complex. Visual Studio 2012 includes a project template to build Web API project. To create a new Web API project we start by creating an ASP.NET MVC 4 web application project as we would normally do and then we select the Web API template as shown in Figure 1:

 
Figure 1. A new Web API project in Visual Studio 2012

Structure of the project is almost similar to a typical ASP.NET MVC 4 web application. The difference is that this project has a new type of controller which is based on System.Web.Http.ApiController class opposed to the regular controllers that inherit from the System.Web.Mvc.Controller class. We can see the structure in Figure 2.


 
Figure 2. Structure of Web API application

The Controllers / ValuesController.cs file is shown in Figure 3. Please note that the controller includes some sample action methods for each of the four common HTTP verbs.


 
Figure 3. Content of ValuesController Class in Controllers/ValuesController.cs File

This new controller has two characteristics that make it different from regular controllers:

Action methods return objects only as this type of controller is designed to provide
data service over HTTP protocol. It does not make sense to implement views or view models. The objects are returned in JSON or XML format based on HTTP accept request header.

The names of action methods can be actual HTTP method used in the request.

Additionally, few other characteristics of Web API are worth mentioning. First one is related to the JSON representation is generated. In action methods which returns JsonResult from regular controllers, the JSON object is created using the built in JSON serializer whereas action methods in Web API controllers use the library Json.NET for serialization. This is important as Json.NET library has implemented some improvements over built in JSON serializer such as in dealing with dates. A DateTime value would be serialized to milliseconds in form of Date(1362117600000). Using Json.NET, same date would be serialized to standard ISO 8016 format like 2013-03-01T00:00:00 -06:00.

Another more important characteristic is that Web API can choose which format to return automatically based on the HTTP accept header from the client. A request using jQuery ajax() function would look like:


Web API Controller creation

We have noticed that the Internet Application template used in our sample application does npt include any Web API controllers. Creation of this type of controller is very simple. Follow below steps to create a Web API controller to serve data for pets:

1. Right click on “Controllers” directory and choose Add => Controller as shown in Figure 4. Alternatively, we can use the keyboard shortcut Ctrl + M, Ctrl + C.



Figure 4. New controller creation
2. In the Add Controller dialog box, put the name of controller PetDataController and select “Empty API controller” from the Template drop down list as shown in Figure 5 and then click “Add”.


Figure 5. Putting name PetDataController and choosing Empty API controller

We have now created our first Web API controller. The generated code should be similar
to the presented code in Figure 6.

 
Figure 6. Empty Web API Controller

3. To add GetInfo() action method, first import the Models and Models.Business
namespaces like:

using HaveYouSeenMe.Models;
using HaveYouSeenMe.Models.Business;

4. Add an action method named GetInfo(). This action method will return a pet type of object. The method should take a string type parameter.

public Pet GetInfo(string name)
{
}

5. Add functionality to find pet information and return the object:

public Pet GetInfo(string name)
{
var pet = PetManagement.GetByName(name);
return pet;
}

6. Open /Views/Message/Send.cshtml file to modify the view to use Web API controller. Modify the Ajax form definition by removing action method and controller definition and adding Url property to the AjaxOptions parameter:




 
Please note that the HttpMethod property is set to Get and Url property is set to /Api/
PetData/Info. These two properties instruct the form to make request to GetInfo action method in the PetData controller.

The api part of Url property is defined by a route. This route is created in App_
Start/WebApiConfig.cs class. It was added in the Visual Studio template by default.

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


// Old code for dates serialized with built in Json serializer
// var lastSeenOn = new Date(parseInt(petData.LastSeenOn.substr(6)));

// New code for dates serialized with Json.NET
var lastSeenOn = new Date(petData.LastSeenOn);

Using Web API has many advantages over regular controllers to present data to clients. We would suggest using it when we want to control the return data format (XML or JSON) without writing the specific serialization. Also, if we need to implement an API by following the principles of REST as it is actually designed for that goal.

No comments:

Post a Comment