Getting Started With WEB API Step By Step With A Sample Application

In this article you will learn what is ASP.NET Web API and why do we use it. Here I will also show you how to create your first Web API service with Visual Studio 2015.

What is Web API?

 
ASP.NET Web API is a powerful platform for building HTTP enabled service APIs that expose service and data. It can be consumed by a broad range of clients including browsers, mobiles, desktop and tablets. As it is HTTP service, so it can reach a broad range of client.
 
ASP.NET Web API is very much similar to ASP.NET MVC because it contain  the ASP.NET MVC feature like routing, controllers, action results, filter, model, etc. Note ASP.NET Web API is not a part of MVC framework. It is a part of the core ASP.NET. You can use Web API with ASP.NET MVC or any other type of web application. You can also create a stand-alone service using the Web API.
 
Note: Using ASP.NET Web API we can only create HTTP services which are non-SOAP based.
 

Why do we need Web API?

 
As you know, today we all are connected with internet. Only web based application is not enough to reach to everyone. Now a days, we all are using apps through mobile devices, tablets which makes our life easy. So, if you want to expose your service to everyone which is accessible on browser as well as modern devices [Mobiles and Tablets Apps] and run fast then you need to expose your service as API which is compatible with every browser as well as these modern devices.
 
ASP.NET Web API uses the full features of HTTP like request/response headers, caching, versioning, etc. It is also a great platform where you can create your REST-FUL services. You don’t need to define extra configuration setting for different devices unlike WCF REST Services.
 
WCF Rest service 
 
Note:
 
I want to clear one misconception that Web API does not replace to WCF. WCF is still a powerful programming model for creating SOAP based services which supports a variety of transport protocols like HTTP, TCP, Named Pipes or MSMQ etc.
 

Start with First Web API Project

 
Open Visual Studio (I am using Visual studio 2015) and from the File menu, select New and then click on the Project. It will open a New Project window.
 
start page 
 
I am using C#, so from the Installed Templates, choose the Visual C# node and under Visual C#, select Web. In the list of project templates, choose ASP.NET Web Application. Give the following name to the project, "WebApiSampleProject" and click OK. It will open a new ASP.NET Project dialog where you can select many types of template for the project.
 
new project 
 
In the new ASP.NET Project dialog, select the Empty template and check Web API. Click OK.
 
select template 
 
So, finally you have created a Web API project. It will create a default structure for the project.
 
solution explorer 
 
Add a model class
 
Model represents the data. It is an object of your data. The model contains all application logic such as business logic, validation logic, data access logic, etc. Web API can automatically serialize the model data to JSON, XML or some other format. The serialize data write into the body of HTTP response message. Client can access the data after de-serialization.
 
To add new model class, in the Solution Explorer, right click on the Models, select Add and Class.
 
add new model class 
 
It will open a dialog for Add New Item, select Visual C# node and select Class and give the proper name “Employee” for the model class and select Add. Modify the code for the model as below:
  1. namespace WebApiSampleProject.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public int EmployeeId  
  6.         {  
  7.             get;  
  8.             set;  
  9.         }  
  10.         public string EmployeeName  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Address  
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public string Department  
  21.         {  
  22.             get;  
  23.             set;  
  24.         }  
  25.     }  
  26. }  
Add a controller
 
Web API Controller is responsible for handing all HTTP requests which can come from browser, mobile device, desktop web application or any other.
 
In Solution Explorer, right click the Controllers folder and select Add and then select controller. 
 
Add controller 
 
Note: Web API controller inherit the ApiController class instead of the Controller class.
 
It will open Add Scaffold dialog, select the Web API Controller - Empty template and click on Add.
 
Add scaffold 
 
In the Add Controller dialog, give a proper name to the controller, "EmployeeController" and click on Add.
 
Add controller 
 
You will see scaffolding creates an “EmployeeController.cs” class inside the controller folder.
 
Add two methods in the controller “GetAllEmployees” and “GetEmployeeDetails” and make dummy data for the Employee. See the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using WebApiSampleProject.Models;  
  8. namespace WebApiSampleProject.Controllers  
  9. {  
  10.     public class EmployeeController: ApiController  
  11.     {  
  12.         IList < Employee > employees = new List < Employee > ()  
  13.         {  
  14.             new Employee()  
  15.                 {  
  16.                     EmployeeId = 1, EmployeeName = "Mukesh Kumar", Address = "New Delhi", Department = "IT"  
  17.                 },  
  18.                 new Employee()  
  19.                 {  
  20.                     EmployeeId = 2, EmployeeName = "Banky Chamber", Address = "London", Department = "HR"  
  21.                 },  
  22.                 new Employee()  
  23.                 {  
  24.                     EmployeeId = 3, EmployeeName = "Rahul Rathor", Address = "Laxmi Nagar", Department = "IT"  
  25.                 },  
  26.                 new Employee()  
  27.                 {  
  28.                     EmployeeId = 4, EmployeeName = "YaduVeer Singh", Address = "Goa", Department = "Sales"  
  29.                 },  
  30.                 new Employee()  
  31.                 {  
  32.                     EmployeeId = 5, EmployeeName = "Manish Sharma", Address = "New Delhi", Department = "HR"  
  33.                 },  
  34.         };  
  35.         public IList < Employee > GetAllEmployees()  
  36.         {  
  37.             //Return list of all employees  
  38.             return employees;  
  39.         }  
  40.         public Employee GetEmployeeDetails(int id)  
  41.         {  
  42.             //Return a single employee detail  
  43.             var employee = employees.FirstOrDefault(e => e.EmployeeId == id);  
  44.             if (employee == null)  
  45.             {  
  46.                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  47.             }  
  48.             return employee;  
  49.         }  
  50.     }  
  51. }  
In the above controller you can see that the method “GetAllEmployees” return the list of all employees and the method “GetEmployeeDetails” returns the detail of single employee. See the following chart which shows how controller use route URL to perform action.
 
Controller Method Route URI
GetAllEmployees /api/employee
GetEmployeeDetails /api/employee/id
 

Run the Web API

 
To see the result, you can just create a client application which will use this web api or you can just simply press F5 or Ctrl+F5. It will open the browser with Url like http://localhost:53037/
 
To get all employees list, you need to make changes in the Url such as http://localhost:53037/api/employee.
 
To get the details of single employee, you need to pass the employee id in the Url http://localhost:53037/api/employee/4
 
Thanks for reading this article, hope you enjoyed it.