ASP.NET Web API is a framework for building HTTP services that can be accessed from various clients, such as browsers and mobile devices. ASP.NET Web API was introduced as part of ASP.NET MVC 4; however, it has its origins in WCF as WCF Web API. This new HTTP service model is simple to develop and contains common HTTP features, including Caching, Status Code, and so on. In this short book, we will discuss Web API design, concepts, features, and compare Web API with WCF.
Implementing a Web API Project
Lets start our discussion with a sample Web API project. We will be using Visual Studio 2013 as our development environment.
Our first step will be to create an ASP.NET MVC project based on the Web API template, as shown in Figure 1. Figure 1: Creating an ASP.NET MVC project based on the Web API template Next, well create a sample model inside the model folder in the MVC solution. Right click on the Model folder from the solution explorer and select Add -> Class as shown in Figure 2. Figure 2: Add new Model For this walk-through, I am using the Product model defined in Listing 1. Listing 1: Defining the Product model public class Product { public int Id { get ; set ; } public string Name { get ; set ; } public string Category { get ; set ; } public decimal Price { get ; set ; } } Once the product model is ready, let us create a new API controller inside the controllers folder to process the Product model. By default, an MVC project based on the Web API template adds two controllers: one inherited from the Controller class and the other from ApiController class.
Right-click the controllers folder in Solution Explorer and add a new controller by selecting the Empty API controller option under template as shown in Figure 3. Figure 3: Add Empty API Controller Provide appropriate name for the new controller; say ProductsController. Figure 4: Add Controller ProductsController will define two methods for getting list of products and selected product based on product id. The code for the sample controller should look like that shown in Listing 2. Listing 2: Adding an ApiController class to the sample project public class ProductsController : ApiController { //Define the products list List < Product > products = new List < Product >(); ///
/// Web API method to return list of products /// /// public IEnumerable < Product > GetAllProducts() { GetProducts(); return products; } private void GetProducts() { products.Add( new Product { Id = 1, Name = "Television" , Category = "Electronic" , Price = 82000 }); products.Add( new Product { Id = 2, Name = "Refrigerator" , Category = "Electronic" , Price = 23000 }); products.Add( new Product { Id = 3, Name = "Mobiles" , Category = "Electronic" , Price = 20000 }); products.Add( new Product { Id = 4, Name = "Laptops" , Category = "Electronic" , Price = 45000 }); products.Add( new Product { Id = 5, Name = "iPads" , Category = "Electronic" , Price = 67000 }); products.Add( new Product { Id = 6, Name = "Toys" , Category = "Gift Items" , Price = 15000 }); } ///
/// Web API method to retrurn selected product based on the passed id /// /// /// public IEnumerable < Product > GetProducts( int selectedId) { if (products.Count() > 0) { return products.Where(p => p.Id == selectedId); } else { GetProducts(); return products.Where(p => p.Id == selectedId); } } } Run the project and access the API by appending the uniform resource locator (URL) with /api/Products , as in http://localhost: 59509/api/Products . This api call will return the list of Products.
We can also access the GetProducts method by passing the SelectedId argument as part of the query string: http://localhost:59509/api/Products?SelectedId=2 . By default Web API returns JSON data, so when you run the Web API directly from browser, it will prompt to save or open the JSON output. Following Figure shows the api output for the /api/Products request. Figure 5: Web API Response - JSON format
Passing Complex Objects to a Web API Method
Passing a simple value is a straightforward process in Web API, but in most cases youll need to pass a complex object as a method parameter. You can pass these objects either by using the [FromUrl] or by using [FromBody] attribute. The [FromBody] attribute reads data from the request body.
However, the attribute can be used only once in the method parameter list. Let us understand the importance of using complex parameters using the code snippet in Listing 3, which expects a complex object, Time , as its input. Listing 3: Passing a complex object as a method parameter public class SampleController : ApiController { ///
/// Get the time based on passed parameters /// /// /// public string GetTime( Time t) { return string .Format( "Received Time: {0}:{1}.{2}" , t.Hour, t.Minute, t.Second); } } public class Time { public int Hour { get ; set ; } public int Minute { get ; set ; } public int Second { get ; set ; } } Now, let us try to pass the values to the GetTime method using the Hour , Minute and Second values. This will throw the Object reference not set to an instance of an object exception. Even though we have mentioned the values related to the fields of the Time object, API method is not able to map the values properly to the parameter. Now modify the code to include the [FromUri] attribute so it can handle the complex object from query string.
As you can see in the following snippet, we include the [FromUri] attribute before specifying the Time object: public string GetTime([ FromUri ] Time t) { -------------------} Invoke the web API method with the same values before and observe the result, as shown in Figure 5. Figure 6: Receiving successful results when calling the GetTime method
Web API Client Implementations
Web API can be consumed from different applications including web applications, client side technologies like jQuery and AngularJS, native mobile applications and so on. This section discuss about how we can invoke Web API from various client applications; ASP.NET MVC and jQuery.