.NET HELP

RestSharp C# (How It Works For Developers)

Published January 14, 2024
Share:

Introduction

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

Why RestSharp?

In modern, multi-tier applications, different services need 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 a NuGet package and can be installed in your C# project. You 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 the 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 user IDs 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 at this link.

Content type

RestSharp supports sending 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, 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 requests 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 client ID 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.

The 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 an exception if any errors occur when making a request or during deserialization.
var restClientOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClientOptions);
var restClientOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClientOptions);
Dim restClientOptions As New RestClientOptions(url) With {.ThrowOnAnyError = True}
Dim client = New RestClient(restClientOptions)
VB   C#

Introducing IronPDF

IronPDF is a C# PDF library from Iron Software that helps to read and generate PDF documents. 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 a URL and then generate PDFs.

A key feature of IronPDF is HTML to PDF conversion, preserving all your layouts and styles. It turns web content into PDFs, making it ideal for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be easily converted to PDFs.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

Install IronPDF Library

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 for IronPDF.
  4. Select IronPDF library from the search results and click the install button.
  5. Accept any license agreement prompt.

If you want to include IronPDF in your project via the 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 IronPDF Downloads. Unzip it and include the DLL in your project.

Now we shall get all the users and generate a PDF report using an 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 at this link.

Here we are first generating an HTML string from the 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 the HTML string to a 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, which 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 upon registering, and no credit card is required for a trial license. One can provide their email ID and register for a free trial.

Conclusion

The 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's 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 for generating PDFs. For additional information about various IronPDF features, please visit the IronPDF documentation page.

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

Knowing both RestSharp and IronPDF adds great skills, enabling developers to create modern applications.

< PREVIOUS
How to Merge PDF Files in .NET
NEXT >
Test Console Application C# (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >