Introduction:
In this article, we will learn that how we can call the REST API from a C# console application, well, we might go into the depths of what actually is a REST API, but in this article, we will just discuss how can we call an API from a console C# application.
Some of you might have been thinking that C# its self being a server side programing language would never need to call an API, since we call API's from a front-end interface or most probably from a mobile application in a cross platform, but sometimes, we find our selves in a situation, where we might be asked to consume a WEB API even from a c# interface, since there can be different scenarios, where we might need to develop an application in a cross platform, or an application having no database, and we are to do all the CRUD operations just by calling the WEB API.
For such scenarios, we would like to know how can we call an API from our C# console based application,
In this example of calling an API, we will call a fake API, and we will call that particular API just to see how can we fetch the data.
Step 1:
Create a new c# console application Project in visual studio 2017 and we will name this project as RestAPIExample and then click OK
Step 2:
So, now we will be looking to consume an API, so we do not need to create an API, we will consume a fake API from this given Url.
https://jsonplaceholder.typicode.com/todos, so we are getting something like this, we are having a JSON array with multiple JSON objects.
Step 3:
Now, we need to install a Nuget package called REST SHARP, so for that right click your console application project and go to the Manage Nuget Packages and browse for restsharp, or go to the package manager console and type Install-Package RestSharp -Version 106.11.7.
We use REST SHARP for consuming an API from the c# interface,
Step 4:
So, now we have to code for consuming the fake REST API, remember whenever we consume an API in c#, we will have to create a new class, which is to be mapped upon the JSON objects, which we get from the API, so lets create a class called UsersData with the rest of the code.
ok, so lets illustrate the code, first up we created a class called UsersData for mapping the class properties on the JSON object properties we receive from the API, in the Main function, we simple called a method called GetApiData to fetch the API data, url refers to the Base Url on the web server, the RestRequest built in class is from the rest sharp library and it takes the resource along with the method, for fetching purpose the method is GET and in our case the resource name is todos, the method returns the users data in a variable called as queryResult.
finally press crtl+f5 to run the application and see the output window.