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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <head runat="server">  
  3.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  4.      <script>  
  5.          $(document).ready(function () {  
  6.              $("#Save").click(function () {  
  7.                  $.ajax({  
  8.                      url: 'http://localhost:3413/api/person',  
  9.                      type: 'GET',  
  10.                      dataType: 'json',  
  11.                      success: function (data, textStatus, xhr) {  
  12.                          console.log(data);  
  13.                      },  
  14.                      error: function (xhr, textStatus, errorThrown) {  
  15.                          console.log('Error in Operation');  
  16.                      }  
  17.                  });  
  18.              });  
  19.          });  
  20.     </script>  
  21. </head>  
  22. <body>  
  23. </body>  
  24. </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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. namespace WebApplication1.WebAPI  
  8. {  
  9.     public class personController : ApiController  
  10.     {  
  11.         [HttpGet]  
  12.         public List<string> Get()  
  13.         {  
  14.             List<string> List = new List<string>();  
  15.             List.Add("sourav kayal");  
  16.             List.Add("Ajay Joshi");  
  17.             List.Add("Nontey Banerjee");  
  18.             return List;  
  19.         }  
  20.     }  
  21. }  
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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <head runat="server">  
  3.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  4.      <script>  
  5.          $(document).ready(function () {  
  6.              $("#Save").click(function () {  
  7.                  $.ajax({  
  8.                      url: 'http://localhost:3413/api/person',  
  9.                      type: 'GET',  
  10.                      dataType: 'json',  
  11.                      success: function (data, textStatus, xhr) {  
  12.                          console.log(data);  
  13.                      },  
  14.                      error: function (xhr, textStatus, errorThrown) {  
  15.                          console.log('Error in Operation');  
  16.                      }  
  17.                  });  
  18.              });  
  19.          });  
  20.     </script>  
  21. </head>  
  22. <body>  
  23.         <input type="button" id="Save" value="Save Data" />  
  24. </body>  
  25. </html>  
The client code is very similar to the previous example, nothing great is here. Here is the example of the server code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. namespace WebApplication1.WebAPI  
  8. {  
  9.     public class person  
  10.     {  
  11.         public string name { getset; }  
  12.         public string surname { getset; }  
  13.     }  
  14.     public class personController : ApiController  
  15.     {  
  16.         [HttpGet]  
  17.         public person[] Get()  
  18.         {  
  19.             person[] p = new person[3];  
  20.             p[0] = new person();  
  21.             p[0].name = "sourav";  
  22.             p[1] = new person();  
  23.             p[1].name = "ajay";  
  24.             p[2] = new person();  
  25.             p[2].name = "Nontey";  
  26.             return p;  
  27.         }  
  28.     }  
  29. }  
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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <script src="jquery-1.7.1.js" type="text/javascript"></script>  
  7.      <script>  
  8.          $(document).ready(function () {  
  9.              $("#Save").click(function () {  
  10.                  $.get('http://localhost:3413/api/person', {id:0} ,function (person) {  
  11.                      console.log('Information' + JSON.stringify(person));  
  12.                  });  
  13.              });  
  14.          });  
  15.     </script>  
  16. </head>  
  17. <body>  
  18.         <input type="button" id="Save" value="Save Data" />  
  19. </body>  
  20. </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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. namespace WebApplication1.WebAPI  
  8. {  
  9.     public class person  
  10.     {  
  11.         public string name { getset; }  
  12.         public string surname { getset; }  
  13.     }  
  14.     public class personController : ApiController  
  15.     {  
  16.         [HttpGet]  
  17.         public person Get(int id)  
  18.         {  
  19.             person[] p = new person[3];  
  20.             p[0] = new person();  
  21.             p[0].name = "sourav";  
  22.             p[0].surname = "Kayal";  
  23.             p[1] = new person();  
  24.             p[1].name = "ajay";  
  25.             p[1].surname = "joshi";  
  26.             return p[id];  
  27.         }  
  28.     }  
  29. }  
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.