Calling Web APIs from jQuery and JavaScript

WEBINAR:
Live

Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js


Date: 1/31/2018 @ 2 p.m. ET

Introduction

In this article, I will demonstrate how to create a Web API using the ASP.NET MVC framework and consume it from a client application. Web API is new version of Microsoft's service-oriented application built on top of MVC architecture. Web API is a great framework for exposing your data and service. It can be consumed by a broad range of clients, including browsers, mobiles, iPhone, and tablets. Web API supports conventional CRUD actions. It also supports MVC features such as routing, controllers, action results, filter, model binders, IOC container, and dependency injection; that makes it more simple and robust.

Creating a Web API in MVC and Consuming It from a Client Application

Let's first create the ASP.NET MVC Web API project. The following steps are mentioned for creating a Web API and consuming it from the client application.

Step 1

Open Visual Studio 2017 and select "File" -> "New" -> "Project."

In the Template Project Window, select Visual C# >ASP.NET Web Application and then select "Web API." Change the name of the project to "MyWebAPI" and click the "OK" button (see Figures 1 and 2).

Creating a new Web API Project
Figure 1: Creating a new Web API Project

Selecting a Web API Template
Figure 2: Selecting a Web API Template

Step 2

We have to add a new model now. The Web API Model can be serialized automatically in JavaScript Object Notation (JSON) and Extensible Markup Language (XML) format. We can use the model to represent the data in our application.

To add a new model in the application, go to the Solution Explorer and right-click the "Model" folder. From the context menu, select "Add" and select the class. Name the class Employee.cs, as shown in Figure 3.

Adding a new Model in the Project
Figure 3: Adding a new Model in the Project

Step 3

Add the following code in the Employee class. I have created an employee and employee details classes.

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

namespace TestWebAPIProj.Models
{
   public class Employee
   {
      public string EmployeeName { get; set; }
      public EmployeeDetails empdetails { get; set; }
   }
   public class EmployeeDetails
   {
      public string email { get; set; }
      public int age { get; set; }
      public double salary { get; set; }
      public string department { get; set; }
      public int totalexp { get; set; }
   }
}

Step 4

Next, add a Controller. The Controller handles the HTTP requests. To add a new Controller, go to the Solution Explorer and right-click the "Controller" folder. Select "Add and Select Controller". Change the name of the controller to "EmployeeController" (see Figure 4).

Adding a new Controller in the Project
Figure 4: Adding a new Controller in the Project

From the Template, select "Web API 2 Controller - Empty", as shown in Figure 5.

Selecting a Web API Controller Template
Figure 5: Selecting a Web API Controller Template

Step 5

My controller inherits the ApiController class and exposes two API methods. Now add the following code to the Employee Controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TestWebAPIProj.Models;
using System.Web.Script.Serialization;

namespace TestWebAPIProj.Controllers
{
   public class EmployeeController : ApiController
   {
      public string GetEmpInfo(string JSONString)
      {
         var seriptSerialization = new System.Web.Script
            .Serialization.JavaScriptSerializer();
         Employee employee = seriptSerialization
            .Deserialize<Employee>(JSONString);
         return "EmployeeName - " + employee.EmployeeName +
            "Employee Age- " + employee.empdetails.age +
            "Employee Dept - " + employee.empdetails.department +
            "Employee Email -  " + employee.empdetails.email +
            "Employee Salary - " + employee.empdetails.salary +
            "Employee Experience - " +
            employee.empdetails.totalexp ;


      }

      public string SubmitEmpdata([FromBody]Employee emp)
      {
         return "EmployeeName - " + emp.EmployeeName +
            "Employee Age - " + emp.empdetails.age +
            "Employee Dept - " + emp.empdetails.department +
            "Employee Email - " + emp.empdetails.email +
            "Employee Salary - " + emp.empdetails.salary +
            "Employee Experience - " + emp.empdetails.totalexp;

      }
   }
}

Step 6

Next, I have added the following route in the WebApiConfig.cs file present in App_Start folder.

public static void Register(HttpConfiguration config)
{
   // Web API configuration and services
   // Configure Web API to use only bearer token authentication.
   config.SuppressDefaultHostAuthentication();
   config.Filters.Add(new HostAuthenticationFilter
      (OAuthDefaults.AuthenticationType));
   // Web API routes
   config.MapHttpAttributeRoutes();
   config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{action}/{id}",
      defaults: new { id = RouteParameter.Optional }
   );
}

Step 7

We have to add client-side HTML code now and consume the Web API created in the previous step. In the Solution Explorer, expand the Home Folder and double-click Index.cshtml (see Figure 6).

Updating the Index.chtml view with HTML Code
Figure 6: Updating the Index.chtml view with HTML Code

Add the following code in the Index.cshtml page. I have called the GetEmpInfo () and SubmitEmpdata () API functions from JavaScript code. Now, execute the application to see the output.

<!DOCTYPE&
<html>
<head>
   <title></title>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/
      1.11.1/jquery.min.js"></script>
   <title>ASP.NET Web API Sample</title>
   <link href="../../Content/Site.css" rel="stylesheet" />
   <script src="../../Scripts/jquery-1.7.1.min.js"
   type="text/javascript"></script>
   <script language="javascript" type="text/javascript">
      var reqdata = {
         EmployeeName: "Robert Ben",
         empdetails: {
            email: 'robertben@hotmail.com',
            age: '50',
            salary: '10000',
            department: 'IT',
            totalexp: '10'

         }
      }
      var stringReqdata = JSON.stringify(reqdata);

      function GetEmpInfo() {
         var url = "http://localhost:58475/api/Employee/
            GetEmpInfo?JSONString=" + stringReqdata;
         jQuery.ajax({
            dataType: "json",
            url: url,
            async: false,
            context: document.body
         }).success(function (data) {
            alert(data);
         });
      };
      function SubmitEmpdata() {
         var url = "http://localhost:58475/api/Employee/
            PostSubmitdata";
         jQuery.ajax({
            async: false,
            type: "POST",
            url: url,
            data: stringReqdata,
            dataType: "json",
            context: document.body,
            contentType: 'application/json; charset=utf-8'
         }).success(function (data) {
            alert(data);
         })
      }
   </script>
</head>
<body>
   <a href="#" onclick="GetEmpInfo();">
      Get Employee</a><br />
   <a href="#" onclick="SubmitEmpdata();">
      Post Employee</a>
</body>
</html>

Conclusion

Reading this article, you learned about Web APIs and how to consume them from a Web page. ASP.NET Web API is a framework that makes it easy to build HTTP services, and it's an ideal platform for building RESTful applications on the .NET Framework.



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date