Create A Web API And Call It Using A Desktop Client Application

ASP.NET Web API is a framework to build APIs to provide web services for a broad range of clients. APIs are the online services that the client will use to get the data and updates.

Here, we will be talking about an example to create a Web API and call it, using a desktop client application.

Creating a new project

Start Visual Studio and go to File -> New -> Project.

In the template panel select Installed -> Templates -> Visual C# -> Web -> ASP.NET Web Application.

Write the name of the project APIs_tutorial and click OK.



A dialog prompting a new ASP.NET Project will appear. Select an empty ASP.NET template, check MVC checkbox and click OK.



Adding Model

Right click Models folder in Solution Explorer. Go to Add and select the Class.



In Add New Item dialog, write the class name Temperature and click Add.



Open Weather.cs and write the code, given below:

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5.     
  6. namespace APIs_tutorial.Models    
  7. {    
  8.     public class Weather    
  9.     {    
  10.         public int id { getset; }    
  11.     
  12.         public string City { getset; }    
  13.     
  14.         public string Temperature { getset; }    
  15.     
  16.         public string Precipitation { getset; }    
  17.     
  18.         public string Humidity { getset; }    
  19.     
  20.         public string Wind { getset; }    
  21.     }    
  22. }   
Adding Web API 2 Controller

Right click on the Controllers folder in Solution Explorer. Go to Add and select the Controller.



On Add Scaffold dialog, select Web API 2 Controller Empty and click Add.



Write the name of the Controller; WeatherController, and click Add.



Visual Studio scaffolds a few things and makes a new API controller.

Open the WeatherController.cs file and write the following code:
  1. using APIs_tutorial.Models;    
  2. using System;    
  3. using System.Collections.Generic;    
  4. using System.Linq;    
  5. using System.Net;    
  6. using System.Net.Http;    
  7. using System.Web.Http;    
  8.     
  9. namespace APIs_tutorial.Controllers    
  10. {    
  11.     public class WeatherController : ApiController    
  12.     {    
  13.         //The data should come from database but here I am hard coding it.    
  14.         public static List<Weather> reports = new List<Weather>    
  15.         {    
  16.             new Weather { id = 1, City = "Islamabad", Temperature = "25 f", Humidity = "70%", Precipitation = "0%", Wind = "15mph" },    
  17.             new Weather { id = 2, City = "Karachi", Temperature = "40 f", Humidity = "80%", Precipitation = "0%", Wind = "40mph" },    
  18.             new Weather { id = 3, City = "Lahore", Temperature = "35 f", Humidity = "50%", Precipitation = "0%", Wind = "10mph" },    
  19.             new Weather { id = 4, City = "Peshawar", Temperature = "25 f", Humidity = "65%", Precipitation = "0%", Wind = "15mph" },    
  20.             new Weather { id = 5, City = "Quetta", Temperature = "40 f", Humidity = "50%", Precipitation = "0%", Wind = "20mph" },    
  21.         };    
  22.     
  23.         [HttpGet]    
  24.         public List<Weather> Get()    
  25.         {    
  26.             return reports;    
  27.         }    
  28.     
  29.         [HttpGet]    
  30.         public Weather Get(int id)    
  31.         {    
  32.             return reports.Find((r) => r.id == id);    
  33.         }    
  34.     
  35.         [HttpPost]    
  36.         public bool Post(Weather report)    
  37.         {    
  38.             try    
  39.             {    
  40.                 reports.Add(report);    
  41.                 return true;    
  42.             }    
  43.             catch    
  44.             {    
  45.                 return false;    
  46.             }    
  47.         }    
  48.     
  49.         [HttpDelete]    
  50.         public bool Delete(int id)    
  51.         {    
  52.             try    
  53.             {    
  54.                 var itemToRemove = reports.Find((r) => r.id == id);    
  55.                 reports.Remove(itemToRemove);    
  56.                 return true;    
  57.             }    
  58.             catch    
  59.             {    
  60.                 return false;    
  61.             }    
  62.         }    
  63.     }    
  64. }   
In this example, we have hard coded the data. In the actual scenario, the data should be fetched from the database.

You have created a Web API. Now, open Global.asax and add the following code:
  1. protected void Application_Start()    
  2. {    
  3.     AreaRegistration.RegisterAllAreas();    
  4.     GlobalConfiguration.Configure(WebApiConfig.Register);    
  5.     RouteConfig.RegisterRoutes(RouteTable.Routes);    
  6. }   
Now our API is ready. All we have to do is to create a client.

Creating Client

Right click on the solution in Solution Explorer. Go to Add and select New Project.



On Add new project dialog, go to Installed -> Visual C# -> Windows -> Classic Desktop and select console Application.

Write the name of the project, Weather_Report, and click OK.



Install the package Microsoft.AspNet.WebApi.Client.

To install the package, right click on the References in Solution Explorer. Select Manage NutGet Packages.



Click on the browse tab and search Microsoft.AspNet.WebApi.Client.

Select the package and click Install.



Click on I Accept on the  Licence Acceptance dialog and the package will install.



Add a new class WeatherClient.



Write the following code in WeatherClient.cs:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net.Http;    
  5. using System.Net.Http.Headers;    
  6. using System.Text;    
  7. using System.Threading.Tasks;    
  8.     
  9. namespace Weather_Report    
  10. {    
  11.     class Program    
  12.     {    
  13.         static void Main(string[] args)    
  14.         {    
  15.             while(true)    
  16.             {    
  17.                 Console.WriteLine("Enter Action:");    
  18.                 string id = Console.ReadLine();    
  19.     
  20.                 GetRequest(id).Wait();    
  21.                 Console.ReadKey();  
  22.                 Console.Clear();  
  23.             }    
  24.         }    
  25.     
  26.         static async Task GetRequest(string ID)    
  27.         {    
  28.             switch (ID)    
  29.             {    
  30.                 //Get Request    
  31.                 case "Get":    
  32.                     Console.WriteLine("Enter id:");    
  33.                     int id = Convert.ToInt32(Console.ReadLine());    
  34.                     using (var client = new HttpClient())    
  35.                     {    
  36.                         client.BaseAddress = new Uri("http://localhost:38104/");    
  37.                         client.DefaultRequestHeaders.Accept.Clear();    
  38.                         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    
  39.     
  40.                         HttpResponseMessage response;    
  41.     
  42.                         //id == 0 means select all records    
  43.                         if (id == 0)    
  44.                         {    
  45.                             response = await client.GetAsync("api/Weather");    
  46.                             if (response.IsSuccessStatusCode)    
  47.                             {    
  48.                                 WeatherClient[] reports = await response.Content.ReadAsAsync<WeatherClient[]>();    
  49.                                 foreach (var report in reports)    
  50.                                 {    
  51.                                     Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}", report.City, report.Temperature, report.Humidity, report.Precipitation, report.Wind);    
  52.                                 }    
  53.                             }    
  54.                         }    
  55.                         else    
  56.                         {    
  57.                             response = await client.GetAsync("api/Weather/" + id);    
  58.                             if (response.IsSuccessStatusCode)    
  59.                             {    
  60.                                 WeatherClient report = await response.Content.ReadAsAsync<WeatherClient>();    
  61.                                 Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}", report.City, report.Temperature, report.Humidity, report.Precipitation, report.Wind);    
  62.                             }    
  63.                         }    
  64.                     }    
  65.                     break;    
  66.     
  67.                 //Post Request    
  68.                 case "Post":    
  69.                     WeatherClient newReport = new WeatherClient();    
  70.                     Console.WriteLine("Enter data:");    
  71.                     Console.WriteLine("Enter City:");    
  72.                     newReport.City = Console.ReadLine();    
  73.                     Console.WriteLine("Enter Temperature:");    
  74.                     newReport.Temperature = Console.ReadLine();    
  75.                     Console.WriteLine("Enter Precipitation:");    
  76.                     newReport.Precipitation = Console.ReadLine();    
  77.                     Console.WriteLine("Enter Humidity:");    
  78.                     newReport.Humidity = Console.ReadLine();    
  79.                     Console.WriteLine("Enter Wind:");    
  80.                     newReport.Wind = Console.ReadLine();    
  81.     
  82.                     using (var client = new HttpClient())    
  83.                     {    
  84.                         client.BaseAddress = new Uri("http://localhost:38104/");    
  85.                         client.DefaultRequestHeaders.Accept.Clear();    
  86.                         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    
  87.     
  88.                         HttpResponseMessage response = await client.PostAsJsonAsync("api/Weather", newReport);    
  89.     
  90.                         if (response.IsSuccessStatusCode)    
  91.                         {    
  92.                             bool result = await response.Content.ReadAsAsync<bool>();    
  93.                             if (result)    
  94.                                 Console.WriteLine("Report Submitted");    
  95.                             else    
  96.                                 Console.WriteLine("An error has occurred");    
  97.                         }    
  98.                     }    
  99.     
  100.                     break;    
  101.     
  102.                 //Delete Request    
  103.                 case "Delete":    
  104.                     Console.WriteLine("Enter id:");    
  105.                     int delete = Convert.ToInt32(Console.ReadLine());    
  106.                     using (var client = new HttpClient())    
  107.                     {    
  108.                         client.BaseAddress = new Uri("http://localhost:38104/");    
  109.                         client.DefaultRequestHeaders.Accept.Clear();    
  110.                         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    
  111.     
  112.                         HttpResponseMessage response = await client.DeleteAsync("api/Weather/" + delete);    
  113.     
  114.                         if (response.IsSuccessStatusCode)    
  115.                         {    
  116.                             bool result = await response.Content.ReadAsAsync<bool>();    
  117.                             if (result)    
  118.                                 Console.WriteLine("Report Deleted");    
  119.                             else    
  120.                                 Console.WriteLine("An error has occurred");    
  121.                         }    
  122.                     }    
  123.                         break;    
  124.             }    
  125.     
  126.         }    
  127.     }    
  128. }    
Use HttpClient to send the http request to the Web API we have just created. Now, let's execute the program and Get, Post and Delete some data.

Calling Web APIs

First run the Web Application by pressing F5. After it, right click on the Weather_Report console Application we have just created. Go to Debug and select Start new instance.



Let's send a request to get all the reports.



Try sending a GET request to get a specific report.



Try POST request and add some data.



Now, check if the data is really submitted or not.



The data is submitted. Now, send a delete request.



Check if the data is deleted or not.



Now, we have a working Web API.

 


Similar Articles