Introduction to Web API

The Web API was introduced in MVC 4. It is a framework to create RESTfull services to support a large number of clients like browsers and mobile/tablet devices. Microsoft also has REST WCF. But WCF does require many more configuration settings than the Web API and we can host the Web API in our own applications.

WCF or ASP.NET Web API

  • If you want to create resource-based services and need to take full advantage of HTTP like cache control for browsers, transfer various kinds of content types like documents, images and HTML pages then ASP.NET Web API should be selected.

  • If you have heterogeneous clients for the same service and need to call the service using various protocols, like netTCPBinding, netNamedPipeBinding and wsHttpBinding then WCF is the obvious choice.

  • If you have special requirements like CallBackContract, one-way communication or queuing then WCF should be selected.

Create a new web application with the template "Web API". Delete all the default controllers, models and views.

Web API

The Web API supports MVC routing. If you open "WebApiConfig.cs" then you can see that. Since we will not use any atuthentication and authorizatoion I have changed the Register method in this file as:

  1. public static void Register(HttpConfiguration config)  
  2. {  
  3.    config.MapHttpAttributeRoutes();  
  4.    config.Routes.MapHttpRoute(  
  5.    name: "DefaultApi",  
  6.    routeTemplate: "api/{controller}/{action}/{id}",  
  7.    defaults: new { id = RouteParameter.Optional }  
  8.    );  
  9. }  
And Startup.cs as:
  1. public partial class Startup  
  2. {  
  3.    public void Configuration(IAppBuilder app)  
  4.    {  
  5.   
  6.    }  
  7. }  
To get data for our API, I have created a dummy DB as follows. Of course, in a real application, you would query a database or use some other external data source.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Collections;  
  6. namespace HelloWebAPI.Models  
  7. {  
  8.     public class EmployeeModel  
  9.     {  
  10.         public int EmployeeId { getset; }  
  11.         public string EmployeeName { getset; }  
  12.         public string EmployeeDepartment { getset; }  
  13.         public decimal Salary { getset; }  
  14.         public int ManagerId { getset; }  
  15.     }  
  16.   
  17.     public class DunmmyEmployeeDB  
  18.     {  
  19.         public static List<EmployeeModel> EmployeeDB = null;  
  20.         static DunmmyEmployeeDB()  
  21.         {  
  22.             EmployeeDB = new List<EmployeeModel>();  
  23.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 11, EmployeeName = "Abhinandan", EmployeeDepartment = "CTS", ManagerId = 0, Salary = 83232 });  
  24.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 1, EmployeeName = "Amit", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 34343 });  
  25.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 2, EmployeeName = "Sushil", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 6565 });  
  26.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 3, EmployeeName = "Gauri", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 24578 });  
  27.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 4, EmployeeName = "Rahul", EmployeeDepartment = "CTS", ManagerId = 11, Salary = 34543 });  
  28.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 5, EmployeeName = "Rajib", EmployeeDepartment = "MST", ManagerId = 15, Salary = 45454 });  
  29.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 6, EmployeeName = "Savan", EmployeeDepartment = "MST", ManagerId = 15, Salary = 2323 });  
  30.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 7, EmployeeName = "Nafisul", EmployeeDepartment = "MST", ManagerId = 15, Salary = 34322 });  
  31.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 8, EmployeeName = "Hemant", EmployeeDepartment = "MST", ManagerId = 15, Salary = 4321 });  
  32.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 9, EmployeeName = "Sandeep", EmployeeDepartment = "MST", ManagerId = 15, Salary = 3456 });  
  33.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 10, EmployeeName = "Ganesh", EmployeeDepartment = "MST", ManagerId = 15, Salary = 8765 });  
  34.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 12, EmployeeName = "Devesh", EmployeeDepartment = "Testing", ManagerId = 0, Salary = 84344 });  
  35.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 13, EmployeeName = "Yogesh", EmployeeDepartment = "Testing", ManagerId = 12, Salary = 4343 });  
  36.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 14, EmployeeName = "Bhavik", EmployeeDepartment = "Testing", ManagerId = 12, Salary = 3547 });  
  37.             EmployeeDB.Add(new EmployeeModel { EmployeeId = 15, EmployeeName = "Manjul", EmployeeDepartment = "MST", ManagerId = 0, Salary = 73547 });  
  38.   
  39.         }  
  40.     }  
  41. }  
Now add an empty WebAPI Controller as we do in a normal MVC application as in the following:

WebAPI Controller

We can see here that this new controller is inherited form ApiController instead of Controller.
  1. namespace HelloWebAPI.Controllers  
  2. {  
  3.    public class EmployeeController : ApiController  
  4.    {  
  5.    }  
  6. }  
First we would add a method to get all the Employee data. For this I have added a method to my controller as in the following:
  1. public IEnumerable GetAllEmployees()  
  2. {  
  3.    return DunmmyEmployeeDB.EmployeeDB;  
  4. }  
  5. Change the Application_start as  
  6. protected void Application_Start()  
  7. {  
  8.    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
  9.    GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);   
  10.    AreaRegistration.RegisterAllAreas();  
  11.    GlobalConfiguration.Configure(WebApiConfig.Register);  
  12.    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  13.    RouteConfig.RegisterRoutes(RouteTable.Routes);  
  14.    BundleConfig.RegisterBundles(BundleTable.Bundles);  
  15. }  
Since this supports the MVC Routing we can access this service at:

http://localhost:[port]/api/Employee/GetAllEmployees.

Now run the application. It will open our index view of the home controller. Now open the rest client from Firebox and call the API with the get method as shown. We will get the JSON for the entire employee in our DB.

entire employee in our D

We can also get the information of one single user. For this we need to pass a parameter to our service. So our new service would look such as:
  1. public IHttpActionResult GetEmployeeData(int id)  
  2. {  
  3.    var Employee = DunmmyEmployeeDB.EmployeeDB.FirstOrDefault((p) => p.EmployeeId == id);  
  4.    if (Employee == null)  
  5.    {  
  6.       return NotFound();  
  7.    }  
  8.    return Ok(Employee);  
  9. }  
And our service URL would be:

http://localhost:[port]/api/Employee/GetEmployeeData?id=10

or

http://localhost:[port]/api/Employee/GetEmployeeData/10

Employee

 

Since we know REST has mainly the following four methods:

  • GET: This should be used to retrieve the required state of a resource.
  • PUT: This should be used to update the required state of a resource.
  • POST: This should be used to create a new resource.
  • DELETE: This should be used to delete the required state of a resource.

By default the API works with HttpGet. We can also use the other HTTP methods by decorating our action methods with [HttpPost] or [HttpPut] or [HttpDelete].

Now decorate GetEmployeeJsonData with [HttpPost] and try to run the preceding URL. You will get "The requested resource does not support http method 'GET'".

requested resource

GET

As I motioned earlier, the Web API uses MVC routing so Web API2 can also use the attribute routing that is a new feature introduced in MVC 5. To test this we can decorate the action as in the following:

  1. [Route("api/Employees")]  
  2. [HttpGet]  
  3. public IEnumerable GetAllEmployees()  
  4. {  
  5.    return DunmmyEmployeeDB.EmployeeDB;  
  6. }  
DunmmyEmployeeDB

For more on Attribute Routing please refer to this link.

Passing Complex Data to Service

We have learned how to pass simple data as an argument to a service. We can also pass complex data as JSON to the service. Create one new service method that takes an object of EmployeeModel as an argument.
  1. public HttpResponseMessage RecieveEmployeeJsonData(EmployeeModel obj)  
  2. {  
  3.   
  4.    var responce = Request.CreateResponse(HttpStatusCode.OK, "Recieved");  
  5.    return responce;  
  6. }  
Passing Complex Data to Service

responce

Please note that we need to add contentType: 'application/json; charset=utf-8' in the headers.

We can call the post service with jQuery as in the following:
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title></title>  
  5.     <script src="http://code.jquery.com/jquery-latest.js"></script>  
  6. </head>  
  7. <body>  
  8.     <button id="TestService" onclick="CallAPI()">Test Service</button>  
  9.     <script type="text/javascript">  
  10.   
  11.         function CallAPI() {  
  12.             var Employee = {  
  13.                 EmployeeId: 12,  
  14.                 EmployeeName: 'Devesh',  
  15.                 EmployeeDepartment: 'Testing',  
  16.                 Salary: 4344,  
  17.                 ManagerId: 10  
  18.                   
  19.                  
  20.   
  21.             };  
  22.   
  23.             var str = JSON.stringify(Employee);  
  24.             $.ajax({  
  25.                 url: 'http://localhost:14925/api/Employee/RecieveEmployeeJsonData',  
  26.                 cache: false,  
  27.                 type: 'POST',  
  28.                 contentType: 'application/json; charset=utf-8',  
  29.                 data: str,  
  30.                 dataType: "json",  
  31.                 success: function (data) {  
  32.                     alert('succeed');  
  33.                 }  
  34.             }).fail(  
  35.         function (xhr, textStatus, err) {  
  36.             alert(err);  
  37.         }  
  38.   
  39.         );  
  40.         }  
  41.     </script>  
  42.   
  43. </body>  
  44. </html>  
code

 

Up Next
    Ebook Download
    View all
    Learn
    View all