You might be wondering why we should consume Web API in console applications.
Nowadays, we have tasks such as consuming data from a third-party Server on a timely basis [run after every 1 hour or 3 hours]. To do this, we need a console app consuming a Web API hosted on a third-party server, and then we can configure it in the Task Scheduler to run on a timely basis.
![webapi]()
Why use the Web API when a Web service is available?
Currently, most mobile devices, Browsers, and tablets are the media for accessing most of the internet, and people are using mobile apps the most. To provide data to apps, we are now going to use Microsoft's new technology.
Web API is easy to consume.
Web API returns the data in various formats, as JSON (JavaScript Object Notation), XML (Extensible Markup Language), and CSV (comma-separated values).
Web Services are also easy to consume.
Web Service returns data in only one form, at SOAP [Simple Object Access Protocol], which is XML-based.
If we try this, many content types will return to the web service. We need to create different Web Services for different formats, and also, to do this, it needs lots of R&D work.
Topics
- Creating a Web API.
- Consuming Web API, using Web Client in Console.
Creating a Web API
Creating a Web API is a simple step. Let's start……
Open Visual Studio IDE from Visual Studio. Select a file. Inside it, select the project. After selecting, a new dialog will pop up with the name “New Project”. In this dialog, in the left pane, you will find Templates, just expand it and you can see Visual C#, which needs to be expanded, select Web Template from it. After selecting the final template, we are going to choose the Project “ASP.NET MVC4 Web Application” and name our project as “MvcEventManager”.
![Add and Naming Project]()
Fig 1. Add and Naming Project
After adding, new dialogs will pop up for choosing the template.
![Add and Naming Project]()
Inside this, we are going to choose Web API and finally click the OK button.
After clicking the OK button, a New Web API project is created, as shown below:
![Project View after adding]()
Fig 2. Project View after adding
After creating the project, we are going to have a look at the database part first, before moving forward.
Database part
I have a database named MVCAPP in it. I have the tables with the name EventTB, which we are going to use for creating the API.
EventTB Table
![EventTB Table]()
Fig 3. Event Table in Design Mode
EventTB Table Contains Data
![EventTB Table Contains Data]()
Fig 4. Shows data in the EventTB table
After having a look at the tables and data, we are going to add ADO.NET Entity Framework to the project.
Adding ADO.NET Entity Framework to the project
To add ADO.NET Entity Framework to the project, just right-click on the Model folder. Inside it, select Add and finally select ADO.NET Entity Data Model.
For reference, look at the snapshot given below:
![Adding ADO.NET entity Data Model]()
Fig 5. Adding ADO.NET Entity Data Model
After selecting ADO.NET Entity Data Model, a new dialog will pop up with the name “Specify Name for Item”.
![Naming ADO.NET entity Data Model]()
Fig 6. Naming ADO.NET Entity Data Model
Enter the name of the Item as EventModel. Click the OK button.
After clicking the OK button, a New Wizard of Entity Data Model will pop up.
![Choosing Model Content]()
Fig 7. Choosing Model Content
In this, we are going to choose the Generate from the database option and click the Next button.
After clicking the Next button, a new wizard will pop up for choosing the database connection.
![Choosing your data connection]()
Fig 8. Choosing your data connection
To choose a new database connection for the Application, just click the New Connection button, and a dialog will pop up with the name “Connection Properties”.
In this Connection Properties dialog, you need to enter the Server name of SQL. Afterwards, you need to choose the mode, which you are going to use for the connection - either Windows Authentication Mode or SQL Server Mode Authentication for showing a demo, and I have chosen SQL Server mode.
Finally, select the database that you want to use “Select or enter database Name”. I have chosen MVCAPP as my database for a demo.
The last step is to click the OK button.
![Setting Connection Properties]()
Fig 9. Setting Connection Properties
After choosing the database connection, the final view of the connection Wizard is shown below:
![Choosing your data connection for adding in Web.config file]()
Fig 10. Choosing your data connection for adding to the Web.config file
Select the Connection string option as Yes, which will be added to the Web.Config file with the sensitive data, and finally click the Next button.
After clicking the Next button, a new dialog will pop up for choosing the database objects.
Choosing database objects
![Choosing your database objects]()
Fig 11. Choosing your database objects
In this wizard, we are just going to choose an object that we want to use.
I am going to choose only the EventTB table from the Tables objects and click the Finish button.
After clicking the Finish button and event, the Model diagram is created along with the table that we have chosen.
![EventModel Diagram]()
Fig 12. EventModel Diagram
The next step is to add an API Controller.
Adding API Controller
To add an API Controller, just right-click on the Controller folder and select Add. Inside it, select Controller, and after selecting Controller, a new dialog will pop up with the name Add Controller. Now, to create a Controller, we need to name the controller. I am going to name it “EventController” and then in the scaffold option, we are going to choose. We have Templates to choose from, and we are going to choose “API controller with read/write actions, using Entity Framework”.
![Adding Event Controller and setting Scaffolding option]()
Fig 13. Adding Event Controller and setting the Scaffolding option
Note. If you are not finding a model, just build your Application once and retry this step. After clicking the Add button, a complete, ready-made API is created, and you do not need to manually do things here.
![Event Controller API]()
Fig 14. Event Controller API
Now, we have created an API. Let’s test on Fiddler.
We are going to call the Get all Records of Event API [http://localhost:50024/api/Event]
After calling, here is the JSON response we have got.
Note: If you do not have Fiddler, you can check it in the Browser to just enter the URL and execute.
![Testing Event Controller API in Fiddler]()
Fig 15. Testing Event Controller API in Fiddler
Now, we have created an API, and the API begins with creating a Console Application and consuming the API in it.
Creating a Console application
Open Visual Studio IDE from Visual Studio IDE select File. Inside this select project, select a new dialog, and it will pop up with the name “New Project”. In this dialog, in the left pane, you will find the templates, just expand them and you can see Visual C#. Just expand it and select Windows Template from it. After selecting the final template, we are going to choose Project “Console Application” and name our Project as “ConsoleEventManager”.
![Creating Console application]()
Fig 16. Creating a Console application and naming it
After entering the project name, finally click the OK button and your console project creates.
![View after adding Console application]()
Fig 17. View after adding a Console application
Now, after creating a console Application, we are going to consume the Event Web API, which we created. To do this, we are going to create 2 new classes with the names “ConsumeEventSync” and “ConsumeEventAsync”.
ConsumeEventSync in this class is going to consume the API in a synchronous way.
ConsumeEventAsync in this class is going to consume the API in an asynchronous way.
![Project View after adding]()
Fig 18. Project View after adding
Now, after adding the classes, we are going to first consume the API in a synchronous way.
Get All Events Records
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace ConsoleEventManager
{
public class ConsumeEventSync
{
public void GetAllEventData() //Get All Events Records
{
using(var client = new WebClient()) //WebClient
{
client.Headers.Add("Content-Type:application/json"); //Content-Type
client.Headers.Add("Accept:application/json");
var result = client.DownloadString("http://localhost:50024/api/Event"); //URI
Console.WriteLine(Environment.NewLine + result);
}
}
}
}
Calling Method in Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleEventManager
{
class Program {
static void Main(string[] args) {
ConsumeEventSync objsync = new ConsumeEventSync();
objsync.GetAllEventData();
}
}
}
Output. Showing the data for all Events.
![Get All Events Records]()
Fig 19. Get All Events Records
Get All Events Records By ID
public void GetAllEventData_ByEventID(string EventID) //Get All Events Records By ID
{
using(var client = new WebClient()) //WebClient
{
client.Headers.Add("Content-Type:application/json"); //Content-Type
client.Headers.Add("Accept:application/json");
var result = client.DownloadString("http://localhost:50024/api/Event/" + EventID); //URI
Console.WriteLine(Environment.NewLine + result);
}
}
Calling Method in Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleEventManager
{
class Program {
static void Main(string[] args) {
ConsumeEventSync objsync = new ConsumeEventSync();
objsync.GetAllEventData_ByEventID("2"); //Get All Events Records By ID
}
}
}
Output. Showing the data against EventID, which we have passed to the Method.
![Get All Events Records by ID]()
Fig 20. Get All Events Records by ID
Adding Data
For posting the data, we require parameters to send the data. I have added a similar class of EventTB in a console project.
![Adding EventTB Class in Console Project]()
Fig 21. Adding EventTB Class in Console Project
Adding Newtonsoft.Json to a console application
To add the Newtonsoft.Json, just select Tools Menu from Visual Studio IDE and add the NuGet Package Manager inside the Manage NuGet Packages for Solution.
After selecting the Manage NuGet Packages dialog popup, type Newtonsoft.Json and click the install button.
![Adding Newtonsoft.Json]()
Fig 22. Adding Newtonsoft.Json
public void PostEvent_data() //Adding Event
{
using(var client = new WebClient()) {
EventTB objtb = new EventTB(); //Setting parameter to post
objtb.EventID = 0;
objtb.EventName = "Late-Night Music";
objtb.EventStartsDate = DateTime.Now;
objtb.EventEndsDate = DateTime.Now;
objtb.EventLocation = "Mumbai";
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
var result = client.UploadString("http://localhost:50024/api/Event", JsonConvert.SerializeObject(objtb));
Console.WriteLine(result);
}
}
Calling Method in Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleEventManager
{
class Program {
static void Main(string[] args) {
ConsumeEventSync objsync = new ConsumeEventSync();
objsync.PostEvent_data(); //Adding Event
}
}
}
Output. In response, we are getting the data that we have inserted.
![Adding Event Data]()
Fig 23. Adding Event Data
Updating Data
In this PUT method, we need to set EventID, which we want to update, and along with that, in the URL, we also need to set the parameter (EventID).
Along with it, we need to set Method ["PUT"] in UploadString.
public void PutEvent_data(int EventID) //Update Event
{
using(var client = new WebClient()) {
EventTB objtb = new EventTB();
objtb.EventID = 7;
objtb.EventName = "Late-Night Music Rocks"; //Value to Update
objtb.EventStartsDate = DateTime.Now;
objtb.EventEndsDate = DateTime.Now;
objtb.EventLocation = "Mumbai";
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
var result = client.UploadString("http://localhost:50024/api/Event/" + EventID, "PUT", JsonConvert.SerializeObject(objtb));
Console.WriteLine(result);
}
}
Calling Method in Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleEventManager
{
class Program
{
static void Main(string[] args) {
ConsumeEventSync objsync = new ConsumeEventSync();
objsync.PutEvent_data(7); //Update Event
}
}
}
Output. The output for the update is empty.
![Updating Event Data]()
Fig 24. Updating Event Data.
Updated Data
![Updated Event Data]()
Fig 25. Updated Event Data
Delete Data
In this Delete method, we need to set EventID, which we want to delete.
Along with it, we need to set Method ["Delete"] and data as [""] in UploadString.
public void DeleteEvent_data(int EventID) //Update Event
{
using(var client = new WebClient()) {
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
var result = client.UploadString("http://localhost:50024/api/Event/" + EventID, "Delete", "");
Console.WriteLine(result);
}
}
Calling Method in Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleEventManager
{
class Program {
static void Main(string[] args) {
ConsumeEventSync objsync = new ConsumeEventSync();
objsync.DeleteEvent_data(7); //Delete Event
}
}
}
Output. Delete the record is shown as output.
![Deleted Event Data]()
Fig 26. Deleted Event Data