Web-API With AJAX: Understand GET Request in Web-API

This is the "Web-API with AJAX" article series. The previous article explained the POST method, you can read it at:

This article explains the GET method. If you read the previous article then you know how a HTTP verb can be mapped with a CRUD operation. We have learned that the POST verb maps with a Create operation. In the same way a GET verb maps with Read operations. So, when we want to read something or get something from the Web-API then we can use a GET HTTP request. Now, the phase "can be" is purposefully used. We are not saying "must be". This means that to get data from a server we can also use a POST verb. But in a general scenario it's always recommended to use a GET request when we are trying to read data from the server.

So, that are the fundamentals of GET requests. Now, let's understand with an example. Since this example is a service application we need to configure the both client and the server.

Create client application to consume service

This is the client configuration where we will configure the ajax() function of the jQuery library. Have a look at the following example.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
<head runat="server">  
    <script src="jquery-1.7.1.js" type="text/javascript"></script>  
     <script>  
         $(document).ready(function () {  
             $("#Save").click(function () {  
                 $.ajax({  
                     url: 'http://localhost:3413/api/person',  
                     type: 'GET',  
                     dataType: 'json',  
                     success: function (data, textStatus, xhr) {  
                         console.log(data);  
                     },  
                     error: function (xhr, textStatus, errorThrown) {  
                         console.log('Error in Operation');  
                     }  
                 });  
             });  
         });  
    </script>  
</head>  
<body>  
</body>  
</html>

Now, please observe that we have specified that the request type is GET and the data type is JSON. So, this is the configuration of the client code.

Create Web API to serve client

Here we will define the Get() method within the "person" controller to serve the HTTP GET request. Here is the code to implement that.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
namespace WebApplication1.WebAPI  
{  
    public class personController : ApiController  
    {  
        [HttpGet]  
        public List<string> Get()  
        {  
            List<string> List = new List<string>();  
            List.Add("sourav kayal");  
            List.Add("Ajay Joshi");  
            List.Add("Nontey Banerjee");  
            return List;  
        }  
    }  
}

This is the output of the code above.

 

We are seeing that it's returning JSON data to the client.

Get complex object using GET request

In this example we will return complex data (read class object) from the Web-API; have a look at this example. This is the code for the client-side implementation.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
<head runat="server">  
    <script src="jquery-1.7.1.js" type="text/javascript"></script>  
     <script>  
         $(document).ready(function () {  
             $("#Save").click(function () {  
                 $.ajax({  
                     url: 'http://localhost:3413/api/person',  
                     type: 'GET',  
                     dataType: 'json',  
                     success: function (data, textStatus, xhr) {  
                         console.log(data);  
                     },  
                     error: function (xhr, textStatus, errorThrown) {  
                         console.log('Error in Operation');  
                     }  
                 });  
             });  
         });  
    </script>  
</head>  
<body>  
        <input type="button" id="Save" value="Save Data" />  
</body>  
</html>

The client code is very similar to the previous example, nothing great is here. Here is the example of the server code.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
namespace WebApplication1.WebAPI  
{  
    public class person  
    {  
        public string name { get; set; }  
        public string surname { get; set; }  
    }  
    public class personController : ApiController  
    {  
        [HttpGet]  
        public person[] Get()  
        {  
            person[] p = new person[3];  
            p[0] = new person();  
            p[0].name = "sourav";  
            p[1] = new person();  
            p[1].name = "ajay";  
            p[2] = new person();  
            p[2].name = "Nontey";  
            return p;  
        }  
    }  
}

We have defined the model class returning an array of objects of the person class. Here is sample output.

 

Use GET method to get data by passing a parameter

In our previous two examples we saw unconditional data fetches, in other words data is being fetched without a condition. But in a real scenario it's very obvious that we need to fetch data depending on conditions. Have a look at the following example.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
    <script src="jquery-1.7.1.js" type="text/javascript"></script>  
     <script>  
         $(document).ready(function () {  
             $("#Save").click(function () {  
                 $.get('http://localhost:3413/api/person', {id:0} ,function (person) {  
                     console.log('Information' + JSON.stringify(person));  
                 });  
             });  
         });  
    </script>  
</head>  
<body>  
        <input type="button" id="Save" value="Save Data" />  
</body>  
</html>

Here we have used a simplified version of the ajax() method. And within the get() method we are passing conditional data. In the Web-API we are receiving the value using an int variable.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
namespace WebApplication1.WebAPI  
{  
    public class person  
    {  
        public string name { get; set; }  
        public string surname { get; set; }  
    }  
    public class personController : ApiController  
    {  
        [HttpGet]  
        public person Get(int id)  
        {  
            person[] p = new person[3];  
            p[0] = new person();  
            p[0].name = "sourav";  
            p[0].surname = "Kayal";  
            p[1] = new person();  
            p[1].name = "ajay";  
            p[1].surname = "joshi";  
            return p[id];  
        }  
    }  
}

Here is the returned data in JSON format.

 

Conclusion

In this example we saw the get() method to communicate with the Web-API. Hope you have enjoyed it. In a future article we will see the remaining verb for communicating with the Web-API. Happy learning.


Similar Articles