Saturday, 6 October 2018

Developing and Consuming WEB API


Below steps to Develop Web API in Visual Studio
1.Create Blank Asp.Net Web Application.
2. Select empty project with Web API.
3.Add a new Class in model as EmployeeDetail and properties as below and paste below code for the same

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiDemo.Models
{
    public class EmployeeDetail
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }

    }
}

 4. Add New Item in Controller as Empty Web API Controller and paste below code for the same.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Models;
namespace WebApiDemo.Controllers
{
    public class EmployeeController : ApiController
    {
        List<EmployeeDetail> emp = new List<EmployeeDetail>()
        {
              new EmployeeDetail {Id="1",Name="Mohd Rizwan", City="Saharanpur" },
              new EmployeeDetail {Id="2",Name="Mohd Jabir", City="Delhi" },
              new EmployeeDetail {Id="3",Name="Mohd Waseem", City="Mumbai" }
        };
        [HttpGet]
        public IEnumerable<EmployeeDetail> GetAllEmplyees()
        {
            return emp;
        }
        [HttpGet]
        public IEnumerable<EmployeeDetail> GetEmployeeById([FromUri]string empid)
        {
            var empList = emp.Where(w => w.Id == empid).ToList();
            return empList;
        }
      
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [HttpPost]
        public HttpResponseMessage AddNewEmployee(EmployeeDetail empd)
        {

            EmployeeDetail s = new EmployeeDetail();
            s.Id = empd.Id;
            s.Name = empd.Name;
            s.City = empd.City;
            emp.Add(s);
            return Request.CreateResponse(HttpStatusCode.OK, emp);
        }
        [System.Web.Http.AcceptVerbs("GET", "PUT")]
        [HttpPut]
        public HttpResponseMessage UpdateEmployee(EmployeeDetail empd, [FromUri]string empid)
        {
            var emps = emp.Where(w => w.Id != empid).ToList();
            EmployeeDetail s = new EmployeeDetail();
            s.Id = empd.Id;
            s.Name = empd.Name;
            s.City = empd.City;
            emps.Add(s);
            return Request.CreateResponse(HttpStatusCode.OK, emps);
        }
        [System.Web.Http.AcceptVerbs("GET", "DELETE")]
        [HttpDelete]
        public HttpResponseMessage DeleteEmployee([FromUri]string empid)
        {
            var emps = emp.Where(w => w.Id != empid).ToList();
            EmployeeDetail s = new EmployeeDetail();
            return Request.CreateResponse(HttpStatusCode.OK, emps);

        }
    }
}

5.Change WebApiConfig under App_Start folder to default response in JSON format and add action after controller in webapiconfig paste below code for the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace WebApiDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
    
How to Consume Web API in jQuery

1.      Create HTML page.
2.      Add below code on HTML page.
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
$(document).ready(function()
{
    GetAllEmployees()//Load All Details by default
    $('#btnAdd').click(function () {
        AddNewEmployee();
    });
    $('#btnUpdate').click(function () {
        UPdateEmployeeDetails();
    });
    $('#btnDelete').click(function () {
        DeleteEmployyeById();
    });
    $('#btnGetAll').click(function () {
        GetAllEmployees();
    });
    $('#btnGetById').click(function () {
        GetEmployeeById();
    });

});


    function GetAllEmployees()
    {
        var resturl = "http://localhost:44739/api/Employee/";
        resturl += "GetAllEmplyees";
        $.ajax({
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data)
            {
                alert('error');
            }
        });
    }
      function GetEmployeeById()
    {
      
          var resturl = "http://localhost:44739/api/Employee/";
          resturl += "GetEmployeeById?empid=" + $('#txtId').val();
        $.ajax({
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data)
            {
                alert('error');
            }
        });
    }
      function AddNewEmployee()
    {
        var stringData= JSON.stringify({
            'Id': '5',
            'Name':'Salim',
            'City':'MZN'
        })
        var resturl = "http://localhost:44739/api/Employee/";
        resturl += "AddNewEmployee";
        $.ajax({
                      type:'POST',
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            data: stringData,
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data) {

                alert('error');
            }
        });
    }
      function UPdateEmployeeDetails()
    {
          var stringData = JSON.stringify({
            'Id': '5',
            'Name':'Salim',
            'City':'MZN'
        })
          var resturl = "http://localhost:44739/api/Employee/";
          resturl += "UpdateEmployee?empid=" + $('#txtId').val();
        $.ajax({
            type: 'PUT',
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            data:stringData,
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data) {

                alert('error');
            }
        });
    }
      function DeleteEmployyeById()
    {
          var resturl = "http://localhost:44739/api/Employee/";
          resturl += "DeleteEmployee?empid=" + $('#txtId').val();
        $.ajax({
                      type:'DELETE',
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose'
            },
            async: false,
            success: function (data)
            {
                GenerateHTMLTable(data);
                console.log(data)
            }, eror: function (data) {

                alert('error');
            }
        });
    }
      function GenerateHTMLTable(data)
      {
          $('.itemCollection').html('');
          if (data.length > 0)
          {
              for (var i = 0; i <data.length; i++)
              {
                  $('.itemCollection').append("<tr><td>" + data[i].Id + "</td><td>" + data[i].Name + "</td><td>" + data[i].City + "</td></tr>");
              }
          }
      }
    </script>
</head>
<body>
    <div>
        <div><input type="text" id="txtId" /></div>
        <div><input type="button" id="btnAdd" value="Add New" /></div>
        <div><input type="button" id="btnUpdate" value="update" /></div>
        <div><input type="button" id="btnDelete" value="Delete" /></div>
        <div><input type="button" id="btnGetAll" value="GetAll" /></div>
        <div><input type="button" id="btnGetById" value="Get By ID" /></div>
        <div></div>
    </div>
  <table width='500px' style='border-collapse: collapse;border: 1px solid #1e7fb8' border='1'>
      <thead><tr style='background-color: #1e7fb8;color:white;'><td>Id</td><td>Name</td><td>City</td></tr></thead>
      <tbody class="itemCollection"></tbody>
  </table>
</body>
</html>

Note:- if you face any challenge in consuming API

Paste below code in web.config file inside <system.webServer>

<httpProtocol>
   <customHeaders>
      <clear />
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
   </customHeaders>
</httpProtocol>





No comments:

Post a Comment