How to Call and Consume Web API in C# Winforms

By FoxLearn 6/29/2024 3:12:15 AM   230
To call and consume a Web API using RestSharp in a C# WinForms application, you can follow these steps.

We will use RestSharp to call web api from client. To play demo you need to install RestSharp from nuget packages or you can download it directly from https://github.com/restsharp/RestSharp

var client = new RestClient("https://localhost:44355/api/Account/");
var request = new RestRequest("Create", Method.POST);
LoginModel model = new LoginModel() { Username = "foxlearn", Password = "c-sharpcode.com" };
var json = JsonConvert.SerializeObject(model);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);

IRestResponse contains all of the information returned from the remote server. You have access to the headers, content, HTTP status and more.

Note: If there is a network transport error the RestResponse.ResponseStatus will be set to Error, otherwise it will be Completed. If your API returns to 404, the ResponseStatus will still be Completed. If you need access to the HTTP status code returned you'll find it at RestResponse.StatusCode.

You can do as same as for HttpGetHttpPut and HttpDelete.

string _url = "https://localhost:44355";
string _token = "Put your token here";
// Create RestClient instance pointing to your API base URL
var client = new RestClient(string.Format("{0}/api/Invoice/", _url));
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", _token));
// Create RestRequest with the resource you want to access
var request = new RestRequest(string.Format("delete/{0}", id), Method.DELETE);
request.RequestFormat = DataFormat.Json;
// Execute the request with RestSharp's Execute method
IRestResponse response = client.Execute(request);
// Deserialize JSON response
JToken data = JToken.Parse(response.Content);

You can use JToken to parse content response from web api. To call the Web API using JWT (Json Web Token) authorization you need to add Authorization to header as shown below.

client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", _token));

You can use RestSharp to download data, then save data as file to your hard disk

var client = new RestClient(string.Format("{0}/api/Invoice/", _url));
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", _token));
var request = new RestRequest(string.Format("pdf/{0}", id), Method.GET);
request.RequestFormat = DataFormat.Json;
byte[] res = client.DownloadData(request);

You can write data with pdf format to file base on data that you get from web api

File.WriteAllBytes(Path.Combine(Application.StartupPath, string.Format("{0}.pdf", id)), res);

Instantiate RestClient pointing to your API base URL, then create a RestRequest object specifying the endpoint (/endpoint in this example) and the HTTP method (Method.GET in this case).

Use Execute method of RestClient to execute the request.