This tutorial will discuss the methods to make a REST API call in C#.

REST API Call With the RestSharp Client in C

The RestSharp is probably the most popular REST API client in C#. We can cast the data received from the API into Plain Old Class Objects (POCO) with this client. For this purpose, We first have to make a data model class that contains fields to be returned by the API call. The following code example shows a sample data model class in C#. The RestSharp client is a third-party package and does not come pre-installed. We need to install the RestSharp package for this approach to work.

class dataModel{
    public int UserID{get; set;}
    public string UserName{get; set;}

The above dataModel class can save the users’ ID and name returned in the API call response. The following code example shows us how we can execute an API call with the RestSharp client in C#.

Uri Url = new Uri("");
IRestClient restClient = new RestClient(Url);
IRestRequest restRequest = new RestRequest("get", Method.GET) { Credentials = new NetworkCredential("Admin", "strongpassword") };
IRestResponse<dataModel> restResponse = restClient.Execute<dataModel>(restRequest);

            if (restResponse.IsSuccessful)
                dataModel model = restResponse.Data;

In the above code, we made a GET request to a rest API with the RestSharp client in C#. We created a class that holds the data returned by the API called the dataModel class. We then executed our request and saved the data returned in the response in an instance of the dataModel class.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Network

  • Get Local IP Address in C#