RestHandler 1.2.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package RestHandler --version 1.2.1
                    
NuGet\Install-Package RestHandler -Version 1.2.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RestHandler" Version="1.2.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RestHandler" Version="1.2.1" />
                    
Directory.Packages.props
<PackageReference Include="RestHandler" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RestHandler --version 1.2.1
                    
#r "nuget: RestHandler, 1.2.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RestHandler@1.2.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RestHandler&version=1.2.1
                    
Install as a Cake Addin
#tool nuget:?package=RestHandler&version=1.2.1
                    
Install as a Cake Tool

RestHandler

RestHandler is a lightweight, developer-friendly C# library for crafting and sending RESTful HTTP requests with ease. Built on HttpClient and Newtonsoft.Json, it features a fluent, expressive API that keeps your code clean, readable, and frustration-free. Whether you're calling APIs in a side project or integrating with enterprise systems, RestHandler aims to make networking in C# feel a little more joyful.

Jump to

Features

  • Fluent API for clean and chainable request creation
  • Support for GET, POST, PUT, and DELETE
  • Global base address, headers, and authorization
  • Response parsing into any type with ParseAs<T>() or ParseAsAsync<T>()
  • Built-in success/fail/error callbacks
  • Raw JSON access and error state detection

Installation

Install via NuGet

dotnet add package RestHandler

Or using the NuGet Package Manager:

Install-Package RestHandler

Usage

GET Request

using DarkenSoda.RestHandler;

MyType result = await RestRequest
    .Get("URL")
    .SendAsync()
    .ParseAsAsync<MyType>();

Console.WriteLine(result);

POST Request

RequestResult result = await RestRequest
    .Post("URL")
    .WithContent(new { name = "test", age = 10 })
    .WithAuthorization("Bearer", "your-token")
    .SendAsync();

Console.WriteLine($"Status: {result.State}");

Response Parsing

You can parse the result directly during or after the request:

// Direct parsing
MyType data = await RestRequest
    .Get("URL")
    .SendAsync()
    .ParseAsAsync<MyType>();

// Deferred parsing
RequestResult result = await RestRequest
    .Get("URL")
    .SendAsync();

MyType data2 = result.ParseAs<MyType>();

Get Raw Json String

You can get the response json as a string directly as follow:

string json1 = result.ResponseJson;
string json2 = result.GetRawString();

string json3 = await RestRequest
    .Get("URL")
    .SendAsync()
    .GetRawStringAsync();

Console.WriteLine(json1);
Console.WriteLine(json2);
Console.WriteLine(json3);

Callbacks

Use OnSuccess, OnFail, OnException and OnRetry for granular response handling:

await RestRequest
    .Get("URL")
    .OnSuccess(res => Console.WriteLine("Success: " + res.ResponseJson))
    .OnFail(res => Console.WriteLine("Failed: " + res.ErrorMessage))
    .OnException(ex => Console.WriteLine("Error: " + ex.Message))
    .OnRetry((response, retryCount, elapsedTime) =>
    {
        Console.WriteLine($"Retrying... {retryCount} - Elapsed Time: {elapsedTime.TotalSeconds:f2}s");
    }) // Only works if you set the retries
    .SendAsync();

Setting Timeout

// Setting Default Timeout for all requests
HttpClientManager.SetDefaultTimeout(30); // in seconds
// or using a TimeSpan
HttpClientManager.SetDefaultTimeout(TimeSpan.FromSeconds(30));

// Setting Timeout per request
RestRequest
    .Get("URL")
    .SetTimeout(5); // in seconds
// or using a TimeSpan
RestRequest
    .Get("URL")
    .SetTimeout(TimeSpan.FromSeconds(5));

Setting Retry Policy

await RestRequest
    .Get("URL")
    .SetRetries(3) // 3 retries
    .OnRetry((response, retryCount, elapsedTime) =>
    {
        Console.WriteLine($"Retrying... {retryCount} - Elapsed Time: {elapsedTime.TotalSeconds:f2}s");
    })
    .SendAsync();

// You can set a Backoff strategy as well
// Check Backoff class for more options:
// - Fixed: Fixed backoff with a fixed delay
// - Linear: Linear backoff with an increment value and a maximum delay
// - Exponential: Exponential backoff with a base delay and a maximum delay
// - Jitter: Random backoff with a maximum delay
await RestRequest
    .Get("URL")
    .SetRetries(3, Backoff.Fixed(TimeSpan.FromSeconds(1))) // 3 retries with fixed backoff of 1 second
    .OnRetry((response, retryCount, elapsedTime) =>
    {
        Console.WriteLine($"Retrying... {retryCount} - Elapsed Time: {elapsedTime.TotalSeconds:f2}s");
    })
    .SendAsync(); 

Setting Global Parameters

Use HttpClientManager to configure defaults:

// Must be set before sending any requests
HttpClientManager.SetBaseAddress("https://api.example.com/");

// Default headers
HttpClientManager.AddDefaultHeader("myKey", "myValue");

// Add multiple headers
HttpClientManager.AddDefaultHeaders(new Dictionary<string, string>
{
    { "key1", "value1" },
    { "key2", "value2" }
});

// Authorization
HttpClientManager.AddDefaultAuthorizationHeader("Bearer", "your-token");

You can remove or clear them too:

HttpClientManager.RemoveBaseAddress();  // Must be set before sending any requests

HttpClientManager.RemoveDefaultHeader("myKey");
HttpClientManager.RemoveDefaultHeaders(new List<string>() { "key1", "key2" });
HttpClientManager.ClearDefaultHeaders();

HttpClientManager.RemoveDefaultAuthorizationHeader();

Migrating from Old API

Old ApiRequest methods are now deprecated. Use RestRequest.Get(...).SendAsync() instead for all new development. Here's how to migrate:

Old
var result = await ApiRequest.GetAsync<MyType>("URL");
New
var result = await RestRequest
    .Get("URL")
    .SendAsync()
    .ParseAsAsync<MyType>();

Roadmap

Here is the current roadmap for future updates.

  • ✅ Fluent request syntax (RestRequest.Get(...).SendAsync())
  • ✅ Unified RequestResult type for all outcomes
  • ✅ Type-safe parsing via ParseAs<T>() and ParseAsAsync<T>()
  • ✅ Global and per Request Timeout
  • ✅ Request Retrying with Backoff
  • ✅ Reusable Request Templates
  • ⬜ Support Query Parameter
  • ⬜ Mock Requests for Testing

Contributing

Contributions are welcome! If you'd like to contribute to this project, please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your feature or bugfix (git checkout -b feature-name).
  3. Add your feature or fix and update the CONTRIBUTORS file with your name.
  4. Commit your changes (git commit -m 'Add feature').
  5. Push to the branch (git push origin feature-name).
  6. Open a pull request.

By following these steps, your contribution and name will be recognized once your pull request is merged.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.0 91 4/26/2025
1.2.1 105 4/25/2025
1.2.0 158 4/24/2025
1.1.0 159 4/24/2025
1.0.2 169 4/23/2025
1.0.1 170 4/22/2025
1.0.0 174 4/22/2025