RestSharp Documentation

repository·dev·Indexed 27 days ago

https://github.com/restsharp/restsharp

RestSharp is a lightweight .NET HTTP API client library that wraps HttpClient to provide simplified parameter handling, built-in serialization, and robust authentication support. It supports multiple body formats (JSON, XML, URL-encoded, multipart), various authentication schemes including OAuth1 and OAuth2, and provides specialized serializer packages for Newtonsoft.Json, CsvHelper, and custom XML. Version 107+ introduces a thread-safe RestClient using RestClientOptions and replaces SimpleJson with System.Text.Json.

Tokens
24.7K
Snippets
65
Records
121
Agent score
91%

What's inside RestSharp

  1. Overview of RestSharp

    dev

    RestSharp is a lightweight .NET HTTP API client library that acts as a wrapper around HttpClient. It simplifies common API tasks by providing:

    • Flexible Parameter Management: Add parameters as query strings, URL segments, headers, cookies, or request bodies.
    • Multiple Body Formats: Support for JSON, XML, URL-encoded form data, and multipart form data (with or without files).
    • Built-in Serialization: Native support for JSON, XML, and CSV, with the ability to plug in custom serializers.
    • Authentication: Rich support for various authentication schemes.
  2. Understand the core capabilities of RestSharp

    dev

    RestSharp acts as a wrapper around HttpClient to simplify RESTful API interactions. It provides automated handling for:

    • Default Parameters: Adding parameters (including headers) to the client once for all requests.
    • Request Parameter Management: Adding parameters to requests as query strings, URL segments, form data, attachments, serialized bodies, or headers.
    • Serialization/Deserialization: Automatically serializing payloads to JSON or XML and deserializing responses from JSON or XML.
    • Content Headers: Automatically setting content headers such as Content-Type, Content-Disposition, and Content-Length.
    • Response Handling: Managing the remote endpoint response lifecycle.
  3. Report bugs and issues

    dev

    If you encounter unexpected behavior or crashes, submit an issue on the GitHub repository. To ensure your issue is considered, provide:

    • Expected behavior
    • Actual behavior
    • Reasoning for why it is a bug (not a misunderstanding)
    • Reproduction steps (a repository or a code snippet)
    • Stack trace (if RestSharp throws an exception)
  4. Set authenticators client-wide or per-request

    dev

    You can apply authentication in two ways:

    1. Client-wide: Assign the Authenticator property to RestClientOptions. This applies the authentication to every request made by that RestClient instance.
    2. Per-request: Assign the Authenticator property to a specific RestRequest. This overrides any client-wide settings for that specific request.
    // Client-wide
    var options = new RestClientOptions("https://example.com") {
        Authenticator = new HttpBasicAuthenticator("username", "password")
    };
    var client = new RestClient(options);
    
    // Per-request
    var request = new RestRequest("/api/users/me") {
        Authenticator = new HttpBasicAuthenticator("username", "password")
    };
    var response = await client.ExecuteAsync(request, cancellationToken);
  5. Integrate RestSharp clients with ASP.NET Core Dependency Injection

    dev

    Instead of passing raw credentials to your API client constructor, you can use the ASP.NET Core Options pattern. This allows you to configure your client via the standard IConfiguration system and register it in the dependency injection container.

    1. Define an options record (e.g., TwitterClientOptions).
    2. Inject IOptions<T> into your client constructor.
    3. Use the values from options.Value to configure the OAuth2TokenRequest and RestClientOptions.
    public record TwitterClientOptions(string ApiKey, string ApiSecret);
    
    public class TwitterClient : ITwitterClient, IDisposable {
        readonly RestClient _client;
    
        public TwitterClient(IOptions<TwitterClientOptions> options) {
            var tokenRequest = new OAuth2TokenRequest(
                "https://api.twitter.com/oauth2/token",
                options.Value.ApiKey,
                options.Value.ApiSecret
            );
            var opt = new RestClientOptions("https://api.twitter.com/2") {
                Authenticator = new OAuth2ClientCredentialsAuthenticator(tokenRequest)
            };
            _client = new RestClient(opt);
        }
        // ... implementation
    }
  6. Install RestSharp and Serializer Packages

    dev

    The core functionality is contained in the RestSharp package. Depending on your serialization needs, you may want to install additional specialized packages:

    • RestSharp: Core library (includes System.Text.Json and basic XML support).
    • RestSharp.Serializers.NewtonsoftJson: For using Newtonsoft.Json as your JSON serializer.
    • RestSharp.Serializers.Xml: For using the custom RestSharp XML serializer.
    • RestSharp.Serializers.CsvHelper: For using CsvHelper as a CSV serializer.
  7. Register and use named RestClients

    dev

    To manage multiple clients with different configurations, register named clients using AddRestClient(string name, Action<RestClientOptions> configure). To retrieve a specific named client, inject IRestClientFactory and use its CreateClient(string name) method.

    // Registration
    services.AddRestClient("my-client", options => 
    {
        options.BaseUrl = new Uri("https://example.com");
        options.Timeout = TimeSpan.FromSeconds(30);
    }); 
    
    // Usage via IRestClientFactory
    public class MyClass(IRestClientFactory restClientFactory)
    {
        IRestClient client = restClientFactory.CreateClient("my-client");
    
        // Use the client in your code
    }
  8. Use Newtonsoft.Json as the RestSharp serializer

    dev

    By default, RestSharp uses System.Text.Json for serialization. To use Newtonsoft.Json instead, you must install the RestSharp.Serializers.NewtonsoftJson package and configure the RestClient during initialization using the UseNewtonsoftJson() extension method within the configureSerialization delegate.

    var client = new RestClient(
        options, 
        configureSerialization: s => s.UseNewtonsoftJson()
    );
  9. Implement a typed API client with RestSharp

    dev
    For best practices when calling external HTTP APIs, you should create a typed client. This pattern encapsulates all RestClient calls within a specific class, preventing the RestClient instance from being exposed publicly in your application logic.
  10. Run the RestSharp documentation website in local development mode

    dev

    To start a local development server for the documentation website, use the yarn start command. This will open a browser window and support live reloading for most changes.

    $ yarn start
  11. Implement a typed API client with RestSharp

    dev

    RestSharp is best used as the foundation for a proxy class for your specific API. Instead of using RestClient directly throughout your application, create a dedicated API client class and an interface. This provides isolation between different RestClient instances (which may require different settings) and makes your code more testable.

    To implement a typed client, follow these steps:

    1. Define an Interface: Create an interface representing the API functions (e.g., ITwitterClient).
    2. Define Data Models: Create DTOs (Data Transfer Objects) using class or record to represent request and response bodies.
    3. Implement the Client: Create a class that wraps a RestClient instance, pre-configured with the API's base URI and necessary authenticators.
    public interface ITwitterClient {
        Task<TwitterUser> GetUser(string user);
    }
    
    public record TwitterUser(string Id, string Name, string Username);
    
    public class TwitterClient : ITwitterClient, IDisposable {
        readonly RestClient _client;
    
        public TwitterClient(string apiKey, string apiKeySecret) {
            var tokenRequest = new OAuth2TokenRequest(
                "https://api.twitter.com/oauth2/token",
                apiKey,
                apiKeySecret
            );
            var options = new RestClientOptions("https://api.twitter.com/2") {
                Authenticator = new OAuth2ClientCredentialsAuthenticator(tokenRequest)
            };
            _client = new RestClient(options);
        }
    
        public async Task<TwitterUser> GetUser(string user) {
            var response = await _client.GetAsync<TwitterSingleObject<TwitterUser>>(
                "users/by/username/{user}",
                new { user }
            );
            return response!.Data;
        }
    
        record TwitterSingleObject<T>(T Data);
    
        public void Dispose() {
            _client?.Dispose();
            GC.SuppressFinalize(this);
        }
    }