푸터 콘텐츠로 바로가기
.NET 도움말

RestSharp C# (How It Works For Developers)

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()
        {
            // 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);
        }
    }
}
$vbLabelText   $csharpLabel

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}");
}
$vbLabelText   $csharpLabel

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; }
}
$vbLabelText   $csharpLabel

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. 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);
$vbLabelText   $csharpLabel

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;
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}");
            }
        }
    }
}
$vbLabelText   $csharpLabel

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)
};
$vbLabelText   $csharpLabel

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);
$vbLabelText   $csharpLabel

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)
    {
        // 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");
    }
}
$vbLabelText   $csharpLabel

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;
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;
        }
    }
}
$vbLabelText   $csharpLabel

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 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.

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.

자주 묻는 질문

C#에서 HTML을 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 HTML 문자열을 PDF로 변환할 수 있습니다. 또한 RenderHtmlFileAsPdf를 사용하여 HTML 파일을 PDF로 변환할 수도 있습니다.

C#에서 RestSharp란 무엇인가요?

RestSharp는 C#에서 HTTP 요청을 만들기 위한 인기 있는 오픈 소스 .NET 라이브러리입니다. 웹 서비스와 쉽고 유연하게 통신할 수 있는 방법을 제공하여 RESTful API 작업을 간소화합니다.

C# 프로젝트에 RestSharp를 설치하려면 어떻게 해야 하나요?

RestSharp는 C# 프로젝트에 NuGet 패키지로 설치할 수 있습니다. NuGet 패키지 관리자 콘솔에서 Install-Package RestSharp 명령을 사용하거나 Visual Studio NuGet 패키지 관리자 UI를 통해 이 작업을 수행할 수 있습니다.

C#을 사용하여 API 데이터에서 PDF를 생성하려면 어떻게 해야 하나요?

RestSharp를 사용하여 API에서 데이터를 가져오고 IronPDF를 사용하여 해당 데이터를 PDF로 변환할 수 있습니다. 먼저 RestSharp를 사용하여 데이터를 검색한 다음 데이터를 HTML로 포맷한 다음 IronPDF를 사용하여 PDF로 변환할 수 있습니다.

RestSharp에서 오류 처리를 위한 모범 사례는 무엇인가요?

RestSharp는 응답 상태를 확인하고 예외를 처리할 수 있는 오류 처리 메커니즘을 제공합니다. ResponseStatusStatusCode 속성을 검사하여 요청이 성공했는지 또는 오류가 발생했는지 확인할 수 있습니다.

RestSharp 응답에서 JSON 데이터를 처리하려면 어떻게 해야 하나요?

RestSharp는 응답에서 JSON 데이터를 쉽게 처리할 수 있습니다. System.Text.Json 또는 Newtonsoft.Json과 같은 라이브러리를 사용하여 JSON 콘텐츠를 C# 개체로 역직렬화하는 메서드를 제공합니다.

C#에서 URL을 PDF로 변환할 수 있나요?

예, IronPDF를 사용하면 URL의 콘텐츠를 가져와 PDF 문서로 변환하는 RenderUrlAsPdf 메서드를 사용하여 웹 URL을 PDF로 변환할 수 있습니다.

RestSharp를 사용하여 POST 요청으로 데이터를 전송하려면 어떻게 해야 하나요?

RestSharp를 사용하여 POST 요청으로 데이터를 전송하려면 새 개체를 만들고 이를 JSON으로 직렬화한 다음 RestRequestAddJsonBody 메서드를 사용하여 요청 본문에 포함시킵니다. 그런 다음 클라이언트와 함께 POST 요청을 실행합니다.

RestSharp는 인증을 지원하나요?

예, RestSharp는 인증을 통한 요청 전송을 지원합니다. 기본 인증에 HttpBasicAuthenticator를 사용하는 등 RestClientOptions에 인증 매개변수를 포함할 수 있습니다.

PDF 생성을 C# 애플리케이션에 통합하려면 어떻게 해야 하나요?

IronPDF를 사용하여 PDF 생성을 C# 애플리케이션에 통합할 수 있습니다. HTML 콘텐츠, URL 또는 HTML 파일을 PDF로 변환할 수 있으므로 애플리케이션 내에서 직접 보고서, 문서 또는 송장을 생성하는 데 유용합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.