RestSharp
3 minute read
is one of the most popular and widely-used REST client libraries in the .NET ecosystem.
| Info | Link | 
|---|---|
| License | |
| Downloads | |
| Latest Version | |
| Issues | |
| Contributors | 
RestSharp is a lightweight yet powerful HTTP client library designed specifically for consuming REST APIs in .NET applications. The library provides a simple, fluent interface for making HTTP requests while handling common REST tasks like serialization/deserialization, authentication, and parameter handling.\
Unlike code-generation approaches, RestSharp follows a manual, request-building pattern that gives developers fine-grained control over their API interactions. Its programming model strikes a balance between the low-level flexibility of HttpClient and the convenience of specialized REST operations.
Key Features
- Simple and intuitive API: Easy to learn and use with minimal boilerplate code
- Automatic serialization/deserialization: Supports JSON, XML, and custom formatters
- Authentication support: Handles OAuth, Basic, JWT, and custom authentication schemes
- Request/response interception: Customize request/response processing with middleware-like handlers
- Parametrized requests: Supports URL parameters, query strings, headers, and request body
- Configurable defaults: Set timeout, user agent, headers and other settings at the client level
- File uploads/downloads: Built-in support for multipart form data and file operations
- Retry policies: Automatic retries with configurable backoff strategies
Basic Usage Sample
// Create options
RestClientOptions options = new RestClientOptions("https://api.example.com")
{
    ThrowOnAnyError = true,
    Timeout = 30
};
// Create client
RestClient client = new RestClient(options);
// Get single task
{
    RestRequest request = new RestRequest("tasks/1234");
    TaskApiModel? task = await client.GetAsync<TaskApiModel>(request, cancellationToken);
}
// Get all tasks
{
    RestRequest request = new RestRequest("tasks");
    TaskApiModel[]? tasks = await client.GetAsync<TaskApiModel[]>(request, cancellationToken);
}
// Add new task
{    TaskApiCreateModel newTask = new TaskApiCreateModel { Title = "Buy flowers" };
    RestRequest request = new RestRequest("tasks").AddJsonBody(newTask);
    TaskApiModel? createdTask = await client.PostAsync<TaskApiModel?>(request, cancellationToken);
}
API Client Pattern
While RestSharp is easy to use directly, it’s considered a best practice to encapsulate RestSharp calls within a dedicated API client class. This abstraction provides several benefits:
- Centralized configuration: Manage base URL, authentication, and default headers in one place
- Domain-specific methods: Create methods that map directly to your business operations
- Consistent error handling: Implement standardized error processing across all API calls
- Testability: Easily mock the API client in unit tests
- Implementation hiding: Shield application code from HTTP-specific details
/*** Wrapper Sample ***/
public class MyTaskApiClient
{
    private readonly RestClient _client;
    public MyTaskApiClient(string baseUrl)
    {
        _client = new RestClient(baseUrl);
    }
    public Task<TaskApiModel?> GetTask(int id, CancellationToken cancellationToken = default)
        => _client.GetAsync<TaskApiModel>(new RestRequest($"task/{id}"), cancellationToken);
    public Task<List<TaskApiModel>?> GetAllTasks(CancellationToken cancellationToken = default) =>
        _client.GetAsync<List<TaskApiModel>>(new RestRequest("tasks"), cancellationToken);    public Task<TaskApiModel?> AddTask(string title, CancellationToken cancellationToken = default)
    {
        TaskApiCreateModel newTask = new TaskApiCreateModel { Title = title };
        RestRequest request = new RestRequest("tasks").AddJsonBody(newTask);
        return _client.PostAsync<TaskApiModel>(request, cancellationToken);
    }
    public Task<bool> DeleteTask(int id, CancellationToken cancellationToken = default)
    {
        RestRequest request = new RestRequest($"tasks/{id}");
        return _client.DeleteAsync(request, cancellationToken)
            .ContinueWith(t => t.IsCompletedSuccessfully, cancellationToken);
    }
}
Advanced Features
Authentication
// Basic authentication
client.Authenticator = new HttpBasicAuthenticator("username", "password");
// OAuth2 bearer token
client.Authenticator = new JwtAuthenticator("your-access-token");
// API key in header
client.AddDefaultHeader("X-API-Key", "your-api-key");
Request Configuration
var request = new RestRequest("resource")
    .AddQueryParameter("page", "1")
    .AddQueryParameter("sort", "desc")
    .AddHeader("Accept-Language", "en-US")
    .AddJsonBody(new { name = "value" });
File Uploads
var request = new RestRequest("upload");
request.AddFile("file", "/path/to/file.pdf", "application/pdf");
await client.PostAsync(request);
Comparison
- Mature, well-tested library with active community support
- Intuitive API with excellent documentation
- Flexible serialization options with minimal configuration
- Works well with simple to moderately complex API integrations
- No code generation required - ideal for quick prototyping
- Higher memory allocation compared to more optimized HTTP clients
- API client wrapper implementation required for production applications
- Limited support for advanced API scenarios (e.g., GraphQL, streaming)
- No built-in request caching mechanism
Full Sample
See the full sample on GitHub: https://github.com/BenjaminAbt/dotnet.rest-samples