Sunday 31 May 2020

ASP .NET WEB API Example

ASP .NET WEB API Example


ASP.NET Web API is a framework for building HTTP services that can be accessed from any client including browsers and mobile devices. 
It is an ideal platform for building Restful applications on the .NET Framework.

Let’s take a look at a simple example of Web API by creating a new ASP.NET Web Application.

Today will create two API for employee with fixed data as below.

    1- Get All Employee Details
    2- Get Employee Details

Step 1 − Open the Visual Studio and click File → New → Project menu option with Name "Demo.Web.API".

Create Project Architecture

 Application Business Models Business Layer Data Access Layer Utility
 Demo.Web.API Demo.BussinessObject Demo.BusinessLayer Demo.DataAccessLayer Demo.Utility

e.g. see in below image











1. Create New Model for employee

namespace Demo.BussinessObject
{
    public class Employee
    {
        public int EmployeeId { getset; }
 
        public string EmployeeCode { getset; }
 
        public string EmployeeName { getset; }
 
        public string City { getset; }
 
        public string ContactNo { getset; }
    }
}

2.  Create data for employee.

using Demo.BussinessObject;
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace Demo.DataAccessLayer
{
    public class EmployeeFactory : IDisposable
    {
        public void Dispose()
        {
        }
 
        /// <summary>
        /// This method is used for get all employee
        /// </summary>
        /// <returns></returns>
        public List<EmployeeGetEmployees()
        {
            try
            {
                List<Employeeemployees = new List<Employee>();
 
                employees.Add(new Employee() { EmployeeId = 1, EmployeeCode = "EMP001",
 EmployeeName = "Ramesh Kumar", ContactNo = "9876543210", City = "Delhi" });
                employees.Add(new Employee() { EmployeeId = 2, EmployeeCode = "EMP002"
EmployeeName = "Mohan Kumar", ContactNo = "9876543211", City = "Haryana" });
                employees.Add(new Employee() { EmployeeId = 3, EmployeeCode = "EMP003"
EmployeeName = "Sohan Kumar", ContactNo = "9876543212", City = "Mumbai" });
                employees.Add(new Employee() { EmployeeId = 4, EmployeeCode = "EMP004"
EmployeeName = "Vijay Kumar", ContactNo = "9876543213", City = "Bhopal" });
 
                return employees;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// This method is used for get employee by id
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public Employee GetEmployee(int empId)
        {
            try
            {
                var employees = GetEmployees();
                Employee employee = employees.FirstOrDefault(x => x.EmployeeId == empId);
                return employee;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

3. Create Business Layer method for employee to call data factory method.


using Demo.BussinessObject;
using Demo.DataAccessLayer;
using System;
using System.Collections.Generic;
 
namespace Demo.BussinessLayer
{
    public class Employees : IDisposable
    {
        public void Dispose()
        {
        }
 
        /// <summary>
        /// This method is used for get all employees
        /// </summary>
        /// <returns></returns>
        public List<EmployeeGetEmployees()
        {
            try
            {
                using (EmployeeFactory factory = new EmployeeFactory())
                {
                    return factory.GetEmployees();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// This method is used for get employee by id
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public Employee GetEmployee(int empId)
        {
            try
            {
                using (EmployeeFactory factory = new EmployeeFactory())
                {
                    return factory.GetEmployee(empId);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


4. Create API controller to create API & call business layer method

using Demo.BussinessLayer;
using Demo.BussinessObject;
using Demo.Web.API.Models;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
 
namespace Demo.Web.API.Controllers
{
    public class EmployeeController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage GetEmployees()
        {
            try
            {
                ApiResponce<List<Employee>> apiResponce = new ApiResponce<List<Employee>>();
                using (Employees employees = new Employees())
                {
                    apiResponce.Responce = employees.GetEmployees();
                    apiResponce.Message = "Record Found";
                    apiResponce.Status = "Success";
                }
                return Request.CreateResponse(HttpStatusCode.OK, apiResponce);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.InnerException);
            }
        }
 
        [HttpGet]
        public HttpResponseMessage GetEmployee(int id)
        {
            try
            {
                ApiResponce<EmployeeapiResponce = new ApiResponce<Employee>();
                using (Employees employees = new Employees())
                {
                    apiResponce.Responce = employees.GetEmployee(id);
                    apiResponce.Message = "Record Found";
                    apiResponce.Status = "Success";
                }
                return Request.CreateResponse(HttpStatusCode.OK, apiResponce);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.InnerException);
            }
        }
    }
}

5. Run this application for test APIs.
1.https://localhost:44373/api/Employee/GetEmployees
Response
{"Responce":[{"EmployeeId":1,"EmployeeCode":"EMP001","EmployeeName":"Ramesh Kumar","City":"Delhi","ContactNo":"9876543210"},{"EmployeeId":2,"EmployeeCode":"EMP002","EmployeeName":"Mohan Kumar","City":"Haryana","ContactNo":"9876543211"},{"EmployeeId":3,"EmployeeCode":"EMP003","EmployeeName":"Sohan Kumar","City":"Mumbai","ContactNo":"9876543212"},{"EmployeeId":4,"EmployeeCode":"EMP004","EmployeeName":"Vijay Kumar","City":"Bhopal","ContactNo":"9876543213"}],"Status":"Success","Message":"Record Found"}


2. https://localhost:44373/api/Employee/GetEmployee?id=1
Response
{"Responce":{"EmployeeId":1,"EmployeeCode":"EMP001","EmployeeName":"Ramesh Kumar","City":"Delhi","ContactNo":"9876543210"},"Status":"Success","Message":"Record Found"} 

Responce of API




Response of API


Factorial of a Number

Recently Viewed