How to Create WEB API Using Repository in Visual Studio?

Hey Guys!!  I am back with my new blog i.e. how to create WEB API using Repository in Visual Studio Framework. In this blog, we will see how to create WEB API in our application. As all the developers Know, Visual Studio is a framework for developing an extensive and responsive web application.

First of all, we would like to know related to WEB API, What is the use of it? and Where is it used? and Lots of things related to WEB API.

What is WEB API?

Before we going practically, let’s understand the term of an API (Application Programming Interface).

API  is a group of subroutine definitions, documents, and tools for developing software, applications etc. In short, An API is a kind of interface which has a predefined (Readymade) set of functions that allow programmers to access distinct features or data of a web application.

  • WEB API is an API which we access over the internet using HTTP protocol.
  • It is an idea and not a technology.
  • We can build Web API also in Java and in many technologies like PHP,.NET etc.

It is a defined Structure for building HTTP web-based services over an internet that uses JSON/XML for request/response data and can be accessed in different applications like web, windows, mobile and many more platforms. It is very much similar to a web service or WCF service but the exception is that it only supports HTTP protocol.

Web API Characteristics

  1. When we want to build RESTful services then we can use Web API.
  2. It supports request/response Cycle of ASP.NET because It is built on top of the ASP.NET.
  3. Another feature is that it Connects HTTP verbs (Get, Put, Delete, Update) to method names.

The basic and common question that revolves around a DotNet Developer mainly Freshers is that where we use WEB API? and Where we use WCF?. So, I am going to tell you in-depth where we use WEB API and where we use WCF.

When to choose WCF?

  • If we talk about WCF then we use .NET Framework Version 3.5.
  • When we want multiple protocols such as HTTP, TCP, Named pipe etc then WCF is preferable.
  • If Service has WS standards like Reliable Messaging, Transactions, Message Security etc.

When to choose Web API?

  • If we talk about Web API then we are using .NET Framework Version 4,5.
  • We use WEB API for access data, it needs supports only HTTP protocol.
  • It only builds RESTFUL API based services.
  • Web API is most useful when we are familiar with ASP.NET MVC.

Let’s talk about the versions of WEB API that Microsoft has provided to us.

Web API Versions

Web API Version Supported DOT-NET Framework Match with Supported in
Web API 1.0 DOT-NET Framework 4.0 ASP.NET MVC 4 VS 2010
Web API 2 – Current DOT-NET F- 4.5 MVC 5 VS 2012, 2013

How to Configure Web API

Now we are going to configure Web API.If we need to configure WEB API, we can accommodate the experience of Web API hosting environment and components such as Routes, Formatter, Filters, DependencyResolver, MessageHandlers, properties, services etc. in an application.

Now move to the Practical part, we created a simple Web API project in the Create WEB API Project section. It already has default WebApiConfig class in the App_Start folder in our web application and also includes Global.asax as shown below.

Global.asax

public class WebAPIApplication : System.Web.HttpApplication
{
 protected void Application_Start()
 {
 GlobalConfiguration.Configure(WebApiConfig.Register);
 
 //other configuration
 }
}
     

WebApiConfig file

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {

config.MapHttpAttributeRoutes();

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

Web API configuration process starts when we run our application and it automatically calls GlobalConfiguration.Configure(WebApiConfig.Register) in the Application_Start() then Configure() method searches the callback method in the Code where Web API has been configured. By default, this is the static WebApiConfig.Register() method.

How to Create WEB API Using Repository in Visual Studio?

finally, I am going to define step by step process of how to create WEB API using Repository in Visual Studio.

Step 1: 

Open Visual Studio then select “File” -> “New” -> “Project…” as in the below Screenshots:

Step 2:

And After Click on Project tab then we created an ASP .NET Web Application as shown in this figure.

Step 3:

Select the location where we want to save our project and enter the name of it. Click OK. Select WebAPI from the template.

Step 4:

Now, click OK and the Web API project is created. It takes time to load all the libraries installed into the Project.

Step 5: 

The Project has been created successfully and then add a class called Employee to create a model in our Application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestWebAPIApplication.Models
{
 public int Employee
 {
 public int EmpId {get;set;}
 public string EmpName {get;set;}
 public string EmpAddress {get;set;}
 public string EmpDesig {get;set;}
 public string EmpDepartment {get;set;}
 public decimal EmpSalary {get;set;}
 }
}

Step 6:

Now, we are going to add an Interface i.e. Repository class IEmployeeRepository.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestWebAPIApplication.Models
{
   public interface IEmployeeRepository
   {
   IEnumerable<Employee> GetAll();
   Employee Get(int id);
   }
}

Step 7:

And after that, we add the class EmployeeRepository to implement that method defined in the interface.

Step 8:

finally, we Implement that method which we have defined in the repository interface.

public class EmployeeRepository:IEmployeeRepository
{
 private List<Employee> emp=new List<Employee>();
 private int nextEmpId=1;
 
 public EmployeeRepository()
 {
 Add(new Employee {EmpName="Ameeq",EmpAddress="Noida", EmpDesig="Software Engineer",EmpDepartment="IT",EmpSalary=32000});
 Add(new Employee {EmpName="Maahi",EmpAddress="Delhi", EmpDesig="Student",EmpDepartment="BA",EmpSalary=28000});
 }
 
 public IEnumerable<Employee> GetAll()
 {
 return emp;
 }
 
 public Employee Get(int id)
 {
 return emp.Find(p=>p.EmpId == id);
 }
 public Employee Add(Employee objEmp)
 {
 if(objEmp==null)
 {
 throw new ArgumentNullException("Error Thrown");
 }
 
 objEmp.EmpId= nextEmpId++;
 emp.Add(objEmp);
 return objEmp;
 }
}

Step 9:

And Add a controller class of EmployeeController to access the data.

Step 10:

In the last step add a reference to Models in the controller and Implement 2 methods as follows:

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Collections.Generic;
using TestWebAPIApplication.Models;

namespace TestWebAPIApplication.Models
{
 public class EmplyeeController : ApiController
 {
 static readonly IEmployeeRepository empRepository = new EmployeeRepository();
 public IEnumerable<Employee> GetAllEmployees()
 {
 return empRepository.GetAll();
 }
 public Employee GetEmployee(int empId)
 {
 Employee emp= empRepository.Get(empId);
 if(emp == null)
 {
 throw new HttpResponseException(HttpStatusCode.NotFound);
 }
 return emp;
 }
 }
}

Results: Build the Application and Run it.

API Call: http://localhost:xxxx/api/employee/getallemployees/

API Call: http://localhost:xxxx/api/employee/getemployee?empid=2

Here in this blog, I have tried to explain in depth of each and every concept of WEB API and How to Create WEB API using Repository in Visual Studio. It is easier, unique and most widely concept in Dot Net. Now-a-days, it is a smart concept to get the data using WEB API.

Moreover, I have defined all about how to Configure WEB API in Visual Studio framework, how to run programs and database connectivity etc. So, learn this technique of WEB API and go ahead. I have elaborated this blog to deliver easy, simple and valuable content regarding this newly innovated technology to learn step by step. I hope this blog will be more valuable and important for a new learner.

Leave a Comment