Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
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.
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
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()
{
// Base URL for the REST API
var baseUrl = "https://jsonplaceholder.typicode.com/users";
// Create a RestClientOptions with default credentials
var 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}");
}
}
// Additional method to log data
public void LogData(string msg)
{
Console.WriteLine(msg);
}
}
}
using RestSharp;
namespace rest_sharp_demo
{
class Program
{
static void Main()
{
// Base URL for the REST API
var baseUrl = "https://jsonplaceholder.typicode.com/users";
// Create a RestClientOptions with default credentials
var 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}");
}
}
// Additional method to log data
public void LogData(string msg)
{
Console.WriteLine(msg);
}
}
}
Imports RestSharp
Namespace rest_sharp_demo
Friend Class Program
Shared Sub Main()
' Base URL for the REST API
Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
' Create a RestClientOptions with default credentials
Dim options = 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
' Additional method to log data
Public Sub LogData(ByVal msg As String)
Console.WriteLine(msg)
End Sub
End Class
End Namespace
RestSharp also supports asynchronous requests and responses using the async API methods.
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
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
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
All the user IDs and names are displayed in the output.
The entire code is available in Git at this link.
RestSharp supports sending XML or JSON body requests. The AddJsonBody
or AddXmlBody
methods of the RestRequest
instance can be used to add JSON or XML body. RestSharp will set the content type automatically. It handles JSON or XML responses automatically.
// 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);
// 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);
' 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)
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;
using System.Text.Json;
namespace rest_sharp_demo
{
class Program
{
static void Main()
{
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);
// Execute the POST request
var response = client.ExecutePost(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Output the response content
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
}
}
using RestSharp;
using System.Text.Json;
namespace rest_sharp_demo
{
class Program
{
static void Main()
{
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);
// Execute the POST request
var response = client.ExecutePost(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Output the response content
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
}
}
Imports RestSharp
Imports System.Text.Json
Namespace rest_sharp_demo
Friend Class Program
Shared Sub Main()
Dim client = New RestClient("https://jsonplaceholder.typicode.com/users")
' New user object
Dim newUser = New User With {
.Name = "John Doe",
.Email = "john.doe@example.com"
}
' Serialize the user object to JSON
Dim jsonBody = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request body
Dim request = (New RestRequest()).AddJsonBody(jsonBody)
' Execute the POST request
Dim response = client.ExecutePost(request)
' Check if the request was successful
If response.IsSuccessful Then
' Output the response content
Console.WriteLine(response.Content)
Else
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
End Sub
End Class
End Namespace
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.
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)}
Here we are using basic client ID secret authentication, which is sent in every request.
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:
ResponseStatus
to Error
accordingly.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)
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)
{
// Create a PDF renderer using Chrome
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)
{
// Create a PDF renderer using Chrome
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)
' Create a PDF renderer using Chrome
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
To integrate IronPDF into your Selenium RestSharp project using the NuGet Package manager, follow these steps:
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.
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.
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;
using IronPdf;
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}");
}
}
// Method to generate HTML from user data
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;
using IronPdf;
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}");
}
}
// Method to generate HTML from user data
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
Imports IronPdf
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
' Method to generate HTML from user data
'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>
"
Dim footer = "
</body>
</html>"
Dim 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>
"
Next user
htmlContent &= footer
Return htmlContent
End Function
End Class
End Namespace
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:
The document has a small watermark for trial licenses, which can be removed using a valid license.
For the above code to work, a license key is required. This key needs to be placed in appsettings.json
as follows:
{
"IronPdf.LicenseKey": "your license key"
}
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.
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.
RestSharp is a popular open-source .NET library for making HTTP requests in C#. It simplifies working with RESTful APIs by providing an easy and flexible way to communicate with web services.
RestSharp can be installed as a NuGet package in your C# project. You can do this using the NuGet Package Manager Console with the command 'Install-Package RestSharp' or through the Visual Studio NuGet Package Manager UI.
To make a simple GET request using RestSharp, create a RestClient object with the API base URL, create a RestRequest for the GET method, and then execute the request using the client's Get method. You can check the response for success and handle the response data accordingly.
Yes, RestSharp can handle JSON data in responses. It provides convenient methods for deserializing JSON response content into C# objects using libraries like System.Text.Json.
IronPDF is a C# PDF library that helps to read and generate PDF documents. It can convert HTML content to PDFs, preserving all layouts and styles, making it useful for creating reports, invoices, and documentation.
To send data with a POST request using RestSharp, create a new object, serialize it to JSON, and include it in the request body using the AddJsonBody method of the RestRequest. You then execute the POST request with the client.
Yes, RestSharp supports sending requests with authentication. You can include authentication parameters in the RestClientOptions, such as using HttpBasicAuthenticator for basic authentication.
IronPDF can be installed in your project using the NuGet Package Manager in Visual Studio, or via the Package Manager Console with the command 'Install-Package IronPdf'. You can also download the DLL from the IronPDF website and include it in your project.
IronPDF can be used with RestSharp to generate PDF reports from data retrieved through RESTful API requests. It enables the conversion of HTML content, including data from API responses, into well-formatted PDF documents.