RestSharp C# (How It Works For Developer)

Introduction

RestSharp is a popular open-source .NET library for making HTTP requests in C#. It simplifies the process of working with peaceful APIs, furnishing a straightforward and flexible way to communicate with web services. In this composition, we'll explore the crucial features of RestSharp and IronPDF and demonstrate how you can cost data and induce a PDF.

Why RestSharp?

In modern multi tier applications, different services have to communicate with each other very often and RestSharp offers a simple and efficient way, by encapsulating all the complexities. This simplifies the software development process greatly.

Install RestSharp

RestSharp is available as NuGet package and can be installed in your C# design. One can do this using the NuGet Package Manager Console or the Visual Studio NuGet Package Manager UI.

Install-Package RestSharp

Making Simple GET Requests

Let's start with a simple example of making a GET request to a RESTful API using RestSharp. Suppose we want to retrieve information from a public ASP.NET core API that returns user data:

using RestSharp;
namespace rest_sharp_demo;
class Program
{
    static void Main()
    {
        // Create a RestClient instance
        var baseUrl = "https://jsonplaceholder.typicode.com/users";
        RestClientOptions options = new RestClientOptions(baseUrl)
      {UseDefaultCredentials = true};
        var client = new RestClient(options);
        // Create a RestRequest for the GET method
        var request = new RestRequest();
        // Execute the request and get the response
        var response = client.Get(request);
        // Check if the request was successful
        if (response.IsSuccessful)
        {
            // Output the response body content
            Console.WriteLine(response.Content);
        }
        else
        {
            // Handle the error
            Console.WriteLine($"Error: {response.ErrorMessage}");
        }
    }
    public void LogData(string msg)
    {
        Console.WriteLine(msg)
    }
}
using RestSharp;
namespace rest_sharp_demo;
class Program
{
    static void Main()
    {
        // Create a RestClient instance
        var baseUrl = "https://jsonplaceholder.typicode.com/users";
        RestClientOptions options = new RestClientOptions(baseUrl)
      {UseDefaultCredentials = true};
        var client = new RestClient(options);
        // Create a RestRequest for the GET method
        var request = new RestRequest();
        // Execute the request and get the response
        var response = client.Get(request);
        // Check if the request was successful
        if (response.IsSuccessful)
        {
            // Output the response body content
            Console.WriteLine(response.Content);
        }
        else
        {
            // Handle the error
            Console.WriteLine($"Error: {response.ErrorMessage}");
        }
    }
    public void LogData(string msg)
    {
        Console.WriteLine(msg)
    }
}
Imports RestSharp
Namespace rest_sharp_demo
	Friend Class Program
		Shared Sub Main()
			' Create a RestClient instance
			Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
			Dim options As New RestClientOptions(baseUrl) With {.UseDefaultCredentials = True}
			Dim client = New RestClient(options)
			' Create a RestRequest for the GET method
			Dim request = New RestRequest()
			' Execute the request and get the response
			Dim response = client.Get(request)
			' Check if the request was successful
			If response.IsSuccessful Then
				' Output the response body content
				Console.WriteLine(response.Content)
			Else
				' Handle the error
				Console.WriteLine($"Error: {response.ErrorMessage}")
			End If
		End Sub
		Public Sub LogData(ByVal msg As String)
			Console.WriteLine(msg)
		End Sub
	End Class
End Namespace
VB   C#

RestSharp also supports asynchronous requests and responses using the async API methods.

Handling Response Data

RestSharp provides convenient methods for deserializing response content into C# objects. Let's extend our example to deserialize the JSON response data into a list of user objects:

// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Output user information
foreach (var user in users)
{
    Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}");
}
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Output user information
foreach (var user in users)
{
    Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}");
}
' Deserialize JSON response into a list of User objects
Dim users = JsonSerializer.Deserialize(Of List(Of User))(response.Content)
' Output user information
For Each user In users
	Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}")
Next user
VB   C#

In this example, we have defined a User class with properties corresponding to the JSON fields. We have used "JsonSerializer.Deserialize" from "System.Text.Json.Serialization" namespace.

public class User
{
[JsonPropertyName("company")]public Company Company { get; set; }
[JsonPropertyName("id")]public int Id { get; set; }
[JsonPropertyName("phone")]public string Phone { get; set; }
[JsonPropertyName("website")]public string Website { get; set; }
[JsonPropertyName("name")]public string Name { get; set; }
[JsonPropertyName("username")]public string Username { get; set; }
[JsonPropertyName("email")]public string Email { get; set; }
[JsonPropertyName("address")]public Address Address { get; set; }
}
public class User
{
[JsonPropertyName("company")]public Company Company { get; set; }
[JsonPropertyName("id")]public int Id { get; set; }
[JsonPropertyName("phone")]public string Phone { get; set; }
[JsonPropertyName("website")]public string Website { get; set; }
[JsonPropertyName("name")]public string Name { get; set; }
[JsonPropertyName("username")]public string Username { get; set; }
[JsonPropertyName("email")]public string Email { get; set; }
[JsonPropertyName("address")]public Address Address { get; set; }
}
Public Class User
<JsonPropertyName("company")>
Public Property Company() As Company
<JsonPropertyName("id")>
Public Property Id() As Integer
<JsonPropertyName("phone")>
Public Property Phone() As String
<JsonPropertyName("website")>
Public Property Website() As String
<JsonPropertyName("name")>
Public Property Name() As String
<JsonPropertyName("username")>
Public Property Username() As String
<JsonPropertyName("email")>
Public Property Email() As String
<JsonPropertyName("address")>
Public Property Address() As Address
End Class
VB   C#

Output

All the userId and names are displayed in the output.

RestSharp C# (How It Works For Developer): Figure 1 - Console Output displaying all the User IDs and Names.

The entire code is available in git here.

Content type

RestSharp supports sending an XML or JSON body requests. AddJsonBody or AddXmlBody methods of the RestRequest instance can be used to add JSON or XML body. RestSharp will set the content type automatically.

RestSharp handles JSON or XML responses automatically.

//using RestSharp;
// Serialize the user object to JSON
var jsonBodyString = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request data
var requestData = new RestRequest().AddJsonBody(jsonBodyString);
var response=client.ExecutePost(requestData);
//using RestSharp;
// Serialize the user object to JSON
var jsonBodyString = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request data
var requestData = new RestRequest().AddJsonBody(jsonBodyString);
var response=client.ExecutePost(requestData);
'using RestSharp;
' Serialize the user object to JSON
Dim jsonBodyString = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request data
Dim requestData = (New RestRequest()).AddJsonBody(jsonBodyString)
Dim response=client.ExecutePost(requestData)
VB   C#

Sending Data with POST Requests

RestSharp also supports sending data in the request body, which is common when creating or updating resources. Let's modify our example to demonstrate a POST request API:

using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com/users");
// New user object
var newUser = new User
{
    Name = "John Doe",
    Email = "john.doe@example.com"
};
// Serialize the user object to JSON
var jsonBody = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request body
var request = new RestRequest().AddJsonBody(jsonBody);
if (response.IsSuccessful)
{
// Output the response content
    Console.WriteLine(response.Content);
}
else
{
    Console.WriteLine($"Error: {response.ErrorMessage}");
}
using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com/users");
// New user object
var newUser = new User
{
    Name = "John Doe",
    Email = "john.doe@example.com"
};
// Serialize the user object to JSON
var jsonBody = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request body
var request = new RestRequest().AddJsonBody(jsonBody);
if (response.IsSuccessful)
{
// Output the response content
    Console.WriteLine(response.Content);
}
else
{
    Console.WriteLine($"Error: {response.ErrorMessage}");
}
Imports RestSharp
Private client = New RestClient("https://jsonplaceholder.typicode.com/users")
' New user object
Private newUser = New User With {
	.Name = "John Doe",
	.Email = "john.doe@example.com"
}
' Serialize the user object to JSON
Private jsonBody = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request body
Private request = (New RestRequest()).AddJsonBody(jsonBody)
If response.IsSuccessful Then
' Output the response content
	Console.WriteLine(response.Content)
Else
	Console.WriteLine($"Error: {response.ErrorMessage}")
End If
VB   C#

In this example, we create a new User object data, serialize it to JSON, and include it in the request body using the AddJsonBody method. The server receives the JSON data and processes the request accordingly

Output

RestSharp C# (How It Works For Developer): Figure 2 - Console Output

Authentication

RestSharp also supports sending request with authentication. The RestClientOptions can include authentication parameters.

var options = new RestClientOptions("https://auth.net"){Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)};
var options = new RestClientOptions("https://auth.net"){Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)};
Dim options = New RestClientOptions("https://auth.net") With {.Authenticator = New HttpBasicAuthenticator(_clientId, _clientSecret)}
VB   C#

Here we are using basic clientId secret authentication which is sent in every request.

Error handling

RestSharp can handle errors that occur during URL requests, such as timeout, authentication or authorization errors. RestSharp doesn't throw an exception if the request fails automatically. It needs to be configured manually.

Following error handling configurations can be done.

  • FailOnDeserializationError: Setting this property to true will tell RestSharp to consider failed deserialization as an error and set the ResponseStatus to Error accordingly.
  • ThrowOnDeserializationError: Setting this property to true will tell RestSharp to throw when deserialization fails.
  • ThrowOnAnyError: Throws Exception if any errors occur when making a request or during deserialization.
var restClentOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClentOptions);
var restClentOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClentOptions);
Dim restClentOptions = New RestClientOptions(url) With {.ThrowOnAnyError = True}
Dim client = New RestClient(restClentOptions)
VB   C#

Introducing IronPDF

IronPDF is a C# PDF library from IronSoftware that helps to read and generate PDF docs. It can convert easily formatted documents with style information to PDF. IronPDF can easily generate PDFs from HTML content, it can download the HTML from URL and then generate PDFs

Install IronPDF Library

C# NuGet Library for PDF

Install with NuGet

Install-Package IronPdf
or
C# PDF DLL

Download DLL

Download DLL

Manually install into your project

Install Using NuGet Package Manager

To Integrate IronPDF into your Selenium RestSharp project using the NuGet Package manager, follow these steps:

  1. Open Visual Studio and in the solution explorer, right click on your project.
  2. Choose “Manage NuGet packages…” from the context menu.
  3. Go to the browse tab and search IronPDF.
  4. Select IronPDF library from the search results and click install button.
  5. Accept any license agreement prompt.

If you want to include IronPDF in your project via Package manager console, then execute the following command in Package Manager Console:

Install-Package IronPdf

It’ll fetch and install IronPDF into your project.

Install Using NuGet Website

For a detailed overview of IronPDF, including its features, compatibility, and additional download options, visit the IronPDF page on the NuGet website at https://www.nuget.org/packages/IronPdf.

Install Via DLL

Alternatively, you can incorporate IronPDF directly into your project using its dll file. Download the ZIP file containing the DLL from this link. Unzip it, and include the DLL in your project.

Now we shall get all the users and generate a PDF report using HTML string and IronPDF generator

using System.Text.Json;
using System.Text.Json.Serialization;
using RestSharp;
namespace rest_sharp_demo;
class Program
{
    static void Main()
    {
        // Create a RestClient 
        var baseUrl = "https://jsonplaceholder.typicode.com/users";
        RestClientOptions options = new RestClientOptions(baseUrl) { UseDefaultCredentials = true };
        var client = new RestClient(options);
        // Create a RestRequest for the GET method
        var request = new RestRequest();
        // Execute the request and get the response
        var response = client.Get(request);
        // Check if the request was successful
        if (response.IsSuccessful)
        {
            // Deserialize JSON response into a list of User objects
            var users = JsonSerializer.Deserialize<List<User>>(response.Content);
            // Generate Pdf
            var html = GetHtml(users);
            var Renderer = new ChromePdfRenderer();
            var PDF = Renderer.RenderHtmlAsPdf(html);
            PDF.SaveAs("UsersReport.pdf");
        }
        else
        {
            // Handle the error
            Console.WriteLine($"Error: {response.ErrorMessage}");
        }
    }
    private static string GetHtml(List<User>? users)
    {
        string header = $@"
<html>
<head><title>Users List</title></head>
<body>
    ";
        var footer = @"
</body>
</html>";
        var htmlContent = header;
        foreach (var user in users)
        {
            htmlContent += $@"
    <h1>{user.Name}</h1>
    <p>Username: {user.Username}</p>
    <p>Email: {user.Email}</p>
    <p>Company: {user.Company}</p>
    <p>Phone: {user.Phone}</p>
    <p>Website: {user.Website}</p>
    <p>Suite: {user.Address.Suite}</p>
    <p>Street: {user.Address.Street}</p>
    <p>City: {user.Address.City}</p>
    <p>Zipcode: {user.Address.Zipcode}</p>
";
        }
        htmlContent += footer;
        return htmlContent;
    }
}
using System.Text.Json;
using System.Text.Json.Serialization;
using RestSharp;
namespace rest_sharp_demo;
class Program
{
    static void Main()
    {
        // Create a RestClient 
        var baseUrl = "https://jsonplaceholder.typicode.com/users";
        RestClientOptions options = new RestClientOptions(baseUrl) { UseDefaultCredentials = true };
        var client = new RestClient(options);
        // Create a RestRequest for the GET method
        var request = new RestRequest();
        // Execute the request and get the response
        var response = client.Get(request);
        // Check if the request was successful
        if (response.IsSuccessful)
        {
            // Deserialize JSON response into a list of User objects
            var users = JsonSerializer.Deserialize<List<User>>(response.Content);
            // Generate Pdf
            var html = GetHtml(users);
            var Renderer = new ChromePdfRenderer();
            var PDF = Renderer.RenderHtmlAsPdf(html);
            PDF.SaveAs("UsersReport.pdf");
        }
        else
        {
            // Handle the error
            Console.WriteLine($"Error: {response.ErrorMessage}");
        }
    }
    private static string GetHtml(List<User>? users)
    {
        string header = $@"
<html>
<head><title>Users List</title></head>
<body>
    ";
        var footer = @"
</body>
</html>";
        var htmlContent = header;
        foreach (var user in users)
        {
            htmlContent += $@"
    <h1>{user.Name}</h1>
    <p>Username: {user.Username}</p>
    <p>Email: {user.Email}</p>
    <p>Company: {user.Company}</p>
    <p>Phone: {user.Phone}</p>
    <p>Website: {user.Website}</p>
    <p>Suite: {user.Address.Suite}</p>
    <p>Street: {user.Address.Street}</p>
    <p>City: {user.Address.City}</p>
    <p>Zipcode: {user.Address.Zipcode}</p>
";
        }
        htmlContent += footer;
        return htmlContent;
    }
}
Imports System.Text.Json
Imports System.Text.Json.Serialization
Imports RestSharp
Namespace rest_sharp_demo
	Friend Class Program
		Shared Sub Main()
			' Create a RestClient 
			Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
			Dim options As New RestClientOptions(baseUrl) With {.UseDefaultCredentials = True}
			Dim client = New RestClient(options)
			' Create a RestRequest for the GET method
			Dim request = New RestRequest()
			' Execute the request and get the response
			Dim response = client.Get(request)
			' Check if the request was successful
			If response.IsSuccessful Then
				' Deserialize JSON response into a list of User objects
				Dim users = JsonSerializer.Deserialize(Of List(Of User))(response.Content)
				' Generate Pdf
				Dim html = GetHtml(users)
				Dim Renderer = New ChromePdfRenderer()
				Dim PDF = Renderer.RenderHtmlAsPdf(html)
				PDF.SaveAs("UsersReport.pdf")
			Else
				' Handle the error
				Console.WriteLine($"Error: {response.ErrorMessage}")
			End If
		End Sub
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: private static string GetHtml(List<User>? users)
		Private Shared Function GetHtml(ByVal users As List(Of User)) As String
			Dim header As String = $"
<html>
<head><title>Users List</title></head>
<body>
    "
	ignore ignore ignore ignore var footer = "
</body>
</html>"
	ignore ignore var htmlContent = header
			For Each user In users
				htmlContent += $"
    <h1>{user.Name}</h1>
    <p>Username: {user.Username}</p>
    <p>Email: {user.Email}</p>
    <p>Company: {user.Company}</p>
    <p>Phone: {user.Phone}</p>
    <p>Website: {user.Website}</p>
    <p>Suite: {user.Address.Suite}</p>
    <p>Street: {user.Address.Street}</p>
    <p>City: {user.Address.City}</p>
    <p>Zipcode: {user.Address.Zipcode}</p>
"
	ignore ignore ignore ignore ignore ignore ignore ignore ignore ignore ignore
			Next user
			htmlContent += footer
			Return htmlContent
		End Function
	End Class
End Namespace
VB   C#

The entire code can be found in Git here.

Here we are first generating an HTML string from users list with all the formatting required for the reports. Then we use IronPDF to generate a PDF document. We use the "RenderHtmlAsPdf" method to convert HTML string to PDF document. The generated document is as below:

RestSharp C# (How It Works For Developer): Figure 4 - Output PDF

The document has a small watermark for trial licenses and can be removed using a valid license.

Licensing (Free Trial Available)

For the above code to work, a license key is required. This key needs to be placed in appsettings.json

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

A trial license is available for developers up on registering here and yes, no credit card is required for a trial license. One can provide the email ID and register for a free trial.

Conclusion

RestSharp library simplifies the process of working with RESTful APIs in C#, providing a clean and efficient way to make HTTP requests and handle responses. Whether you're retrieving data with GET requests or sending data with POST requests, RestSharp intuitive API and convenient features make it a valuable tool for developers building applications that interact with web services.

IronPDF provides a flexible and easy-to-use solution to generate PDFs. For additional information about various IronPDF features, please visit the documentation page.

IronPDF's perpetual license which will help you improve your coding skills and achieve modern application requirements.

Knowing both RestSharp and IronPDF adds great skills and developers can create modern applications.