Spoleto.RestClient
1.1.0
Prefix Reserved
dotnet add package Spoleto.RestClient --version 1.1.0
NuGet\Install-Package Spoleto.RestClient -Version 1.1.0
<PackageReference Include="Spoleto.RestClient" Version="1.1.0" />
<PackageVersion Include="Spoleto.RestClient" Version="1.1.0" />
<PackageReference Include="Spoleto.RestClient" />
paket add Spoleto.RestClient --version 1.1.0
#r "nuget: Spoleto.RestClient, 1.1.0"
#:package Spoleto.RestClient@1.1.0
#addin nuget:?package=Spoleto.RestClient&version=1.1.0
#tool nuget:?package=Spoleto.RestClient&version=1.1.0
Spoleto.RestClient
Overview
Spoleto.RestClient is a flexible and easy-to-use wrapper around HttpClient designed to simplify making HTTP requests and handling responses in various formats: JSON, XML and Binary in .NET applications.
The client also supports authentication and provides the ability for flexible customization and overriding of base classes.
It supports various .NET versions, including .NET 7, .NET 8, and NetStandard 2.0.
This library aims to provide a comfortable, convenient, and powerful way to interact with HTTP-based APIs.
https://github.com/spoleto-software/Spoleto.RestClient
Features
- Flexible and Customizable: Easily configure and extend to meet your specific needs.
- User-Friendly: Intuitive API design that simplifies making HTTP requests.
- Supports Authentication: Built-in support for both static and dynamic request authentication.
- Multi-Targeting: Compatible with .NET 7, .NET 8, and NetStandard 2.0.
Quick setup
Begin by installing the package through the NuGet package manager with the command:
dotnet add package Spoleto.RestClient
Usage
Creating a RestClient
To create an instance of RestHttpClient, use the RestClientFactory:
var restClient = new RestClientFactory()
.WithHttpClient(new HttpClient())
.WithAuthenticator(new StaticAuthenticator("Bearer", "your-static-token"))
.Build();
Authentication
Static Authenticator
For static tokens:
var authenticator = new StaticAuthenticator("Bearer", "your-static-token");
Dynamic Authenticator
For dynamic tokens, extend the DynamicAuthenticator class, e.g.:
public class MyAuthenticator : DynamicAuthenticator
{
public const string TokenTypeName = "Bearer";
private readonly AuthCredentials _authCredentials;
public MyAuthenticator(AuthCredentials authCredentials) : base(TokenTypeName)
{
_authCredentials = authCredentials;
}
protected override async Task<string> GetAuthenticationToken(IRestClient client)
{
var restRequest = new RestRequestFactory(RestHttpMethod.Post, "oauth/token")
.WithFormUrlEncodedContent(_authCredentials)
.Build();
var authResponseModel = await client.ExecuteAsync<AuthToken>(restRequest).ConfigureAwait(false);
return authResponseModel.AccessToken;
}
}
How the dynamic authenticator works:
- The token is requested before the first request and is kept until the server rejects it.
- When the server answers
401 Unauthorized, the client gets a new token and sends the request again, once. If the second answer is also401, the client throws an exception instead of requesting tokens again and again. - Requests that
GetAuthenticationTokensends through the same client go without a token. Other requests wait for the token instead of going without it. - If getting the token fails, the next request tries again.
Creating Requests
The RestRequestFactory makes it easy to build requests:
- With Query String:
.WithQueryString(new { param1 = "value1", param2 = "value2" });
// or
.WithQueryString("arg1=va1&arg2=val2");
// or
var model = GetModel();
.WithQueryString(model);
- With JSON Content:
.WithJsonContent(new { property = "value" });
// or
var model = GetModel();
.WithJsonContent(model);
- With application/x-www-form-urlencoded:
Dictionary<string, string> data = GetData();
.WithFormUrlEncodedContent(data);
// or
var model = GetModel();
.WithFormUrlEncodedContent(model);
- With Headers:
.WithHeader("Custom-Header", "HeaderValue");
- With Bearer Token:
.WithBearerToken("your-token");
Examples how to send requests
GET Request with Query Parameters
public async Task<List<City>> GetCitiesAsync(CityRequest cityRequest)
{
var restRequest = new RestRequestFactory(RestHttpMethod.Get, "cities")
.WithQueryString(cityRequest)
.Build();
var cityList = await _restClient.ExecuteAsync<List<City>>(restRequest).ConfigureAwait(false);
return cityList;
}
POST Request with JSON Content
public async Task<Order> CreateOrderAsync(OrderRequest orderRequest)
{
var restRequest = new RestRequestFactory(RestHttpMethod.Post, "orders")
.WithJsonContent(orderRequest)
.Build();
var deliveryOrder = await _restClient.ExecuteAsync<DeliveryOrder>(restRequest).ConfigureAwait(false);
return deliveryOrder;
}
IRestClient Interface
The base interface for making requests:
public interface IRestClient : IDisposable
{
Task<TextRestResponse> ExecuteAsStringAsync(RestRequest request, CancellationToken cancellationToken = default);
Task<BinaryRestResponse> ExecuteAsBytesAsync(RestRequest request, CancellationToken cancellationToken = default);
Task<T> ExecuteAsync<T>(RestRequest request, CancellationToken cancellationToken = default) where T : class;
}
Creating Custom RestClient
Spoleto.RestClient is designed to be easily extensible, allowing you to create your own custom RestClient to fit specific needs.
Below is an example of how you can create a custom RestClient by inheriting from RestHttpClient:
public class MyClient : RestHttpClient
{
private readonly MyOptions _myOptions;
public MyClient(MyOptions myOptions, AuthCredentials authCredentials)
: this(myOptions, CreateNewClient(myOptions), CreateAuthenticator(authCredentials), RestClientOptions.Default, true)
{
}
public MyClient(MyOptions myOptions, HttpClient httpClient, IAuthenticator? authenticator = null, RestClientOptions? options = null, bool disposeHttpClient = false)
: base(httpClient, authenticator, options, disposeHttpClient)
{
_myOptions = myOptions;
}
private static HttpClient CreateNewClient(MyOptions myOptions)
{
// It's up to you to use Polly here in HttpMessageHandler:
var httpClient = new HttpClient { BaseAddress = new Uri(myOptions.ServiceUrl) };
return httpClient;
}
private static IAuthenticator CreateAuthenticator(AuthCredentials authCredentials)
{
var authenticator = new MyAuthenticator(authCredentials);
return authenticator;
}
}
In this example, MyClient is a custom RestHttpClient that can be configured with specific options and authentication credentials. This allows you to tailor the HTTP client to your particular needs, such as integrating with specific services or adding custom authentication mechanisms.
Error Handling
For an unsuccessful response the client throws HttpRequestException:
- the message is the status code and the reason phrase, e.g.
400 Bad Request; - the response body, if any, is the inner exception;
StatusCodeholds the status code (.NET 5 and later);DataholdsStatusCode,ReasonPhraseandRequestUri.
The body stays out of the message on purpose: an error page of IIS or a proxy is a whole HTML document.
To read the service's own error model, override CreateException in a custom RestHttpClient. The client adds StatusCode, ReasonPhrase and RequestUri to Data of whatever exception it returns:
public class MyClient : RestHttpClient
{
// ...
protected override Exception CreateException(IRestResponse restResponse, string? content)
{
var error = content != null && restResponse.ContentType == ContentTypes.ApplicationJson
? SerializationManager.Deserialize<MyError>(content)
: null;
return new HttpRequestException(error?.Message ?? $"{(int)restResponse.StatusCode} {restResponse.ReasonPhrase}", null, restResponse.StatusCode);
}
}
To handle errors yourself, build the request with .ThrowIfHttpError(false) and check IsSuccessStatusCode of the response from ExecuteAsStringAsync or ExecuteAsBytesAsync.
404 Not Found is not an error by default: ExecuteAsync<T> returns null, and ExecuteAsStringAsync and ExecuteAsBytesAsync return the response. Set RestClientOptions.ThrowExceptionIfNotFound to throw instead.
Response Headers
Headers of a response holds the response headers together with the content headers (Content-Type, Content-Disposition and others). Header names are case-insensitive:
var response = await restClient.ExecuteAsBytesAsync(restRequest);
var fileName = ContentDispositionHeaderValue.Parse(response.Headers["Content-Disposition"].First()).FileName;
Serialization and Deserialization
All serialization and deserialization in Spoleto.RestClient are handled by the SerializationManager.
The default JSON serializer is based on System.Text.Json, the defaul XML serializer is based on System.Xml.Serialization.XmlSerializer and you can easily adjust the serializers to fit your needs.
SerializationManager
Methods of SerializationManager:
public static T Deserialize<T>(IRestResponse restResponse) where T : class;
public static T Deserialize<T>(string raw);
public static string? Serialize<T>(DataFomat dataFormat, T? value) where T : class;
Adjusting SerializationManager
You can easily customize the SerializationManager by modifying the Serializers property:
public static SerializerCollection Serializers { get; }
Example: Replacing the Default JSON Serializer
By default, SerializationManager uses a JSON serializer based on System.Text.Json. If you want to replace it with a different JSON serializer, such as Newtonsoft.Json, you can do so by modifying the Serializers collection:
SerializationManager.Serializers.RemoveType<JsonSerializer>();
SerializationManager.Serializers.Add(new NewtonsoftJsonSerializer());
Here's an example of what a custom serializer might look like:
public class NewtonsoftJsonSerializer : IJsonSerializer
{
public bool CanDeserialize(IRestResponse response)
{
return response.ContentType.Contains("application/json");
}
public bool CanDeserialize(string raw)
{
// Implement a check to see if the raw string is JSON
}
public T Deserialize<T>(IRestResponse response) where T : class
{
return JsonConvert.DeserializeObject<T>(response.Content);
}
public T Deserialize<T>(string raw) where T : class
{
return JsonConvert.DeserializeObject<T>(raw);
}
public string Serialize<T>(T value) where T : class
{
return JsonConvert.SerializeObject(value);
}
}
Conclusion
Spoleto.RestClient simplifies HTTP requests in .NET by providing a user-friendly and flexible wrapper around HttpClient. Whether you need to perform simple GET requests or complex POST requests with authentication, Spoleto.RestClient offers a clean and easy-to-use API to get the job done.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. 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. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Spoleto.Common (>= 3.6.28.1701)
-
net7.0
- Spoleto.Common (>= 3.6.28.1701)
-
net8.0
- Spoleto.Common (>= 3.6.28.1701)
NuGet packages (6)
Showing the top 5 NuGet packages that depend on Spoleto.RestClient:
| Package | Downloads |
|---|---|
|
Spoleto.Delivery.MasterPost
MasterPost provider for Spoleto.Delivery |
|
|
Spoleto.Delivery.Cdek
CDEK provider for Spoleto.Delivery |
|
|
Spoleto.Marking.TsPiot
.NET client for integrating with TS PIOT (ESM) to validate product marking codes via gRPC or REST. |
|
|
Spoleto.TrueApi.Auth
TrueApi auth provider for CRPT |
|
|
Spoleto.Taxcom
SDK для работы с API сервиса Taxcom |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.1.0 | 772 | 11/2/2026 |
| 1.0.17 | 2,298 | 2/14/2026 |
| 1.0.16 | 3,158 | 7/2/2025 |
| 1.0.15 | 748 | 4/29/2025 |
| 1.0.14 | 2,028 | 11/12/2024 |
| 1.0.12 | 213 | 11/12/2024 |
| 1.0.11 | 4,296 | 9/28/2024 |
| 1.0.10 | 241 | 9/20/2024 |
| 1.0.9 | 2,715 | 9/6/2024 |
| 1.0.8 | 436 | 8/2/2024 |
| 1.0.7 | 254 | 7/12/2024 |
| 1.0.6 | 477 | 6/27/2024 |
| 1.0.5 | 262 | 6/27/2024 |
| 1.0.4 | 242 | 6/26/2024 |
| 1.0.3 | 690 | 6/12/2024 |