Spoleto.RestClient 1.0.8

There is a newer version of this package available.
See the version list below for details.
dotnet add package Spoleto.RestClient --version 1.0.8                
NuGet\Install-Package Spoleto.RestClient -Version 1.0.8                
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="Spoleto.RestClient" Version="1.0.8" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Spoleto.RestClient --version 1.0.8                
#r "nuget: Spoleto.RestClient, 1.0.8"                
#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.
// Install Spoleto.RestClient as a Cake Addin
#addin nuget:?package=Spoleto.RestClient&version=1.0.8

// Install Spoleto.RestClient as a Cake Tool
#tool nuget:?package=Spoleto.RestClient&version=1.0.8                

Spoleto.RestClient

alternate text is missing from this package README image alternate text is missing from this package README image Build

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;
    }
}

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.

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 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. 
.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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 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

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.14 282 11/12/2024
1.0.12 66 11/12/2024
1.0.11 2,535 9/28/2024
1.0.10 86 9/20/2024
1.0.9 1,645 9/6/2024
1.0.8 221 8/2/2024
1.0.7 85 7/12/2024
1.0.6 345 6/27/2024
1.0.5 101 6/27/2024
1.0.4 100 6/26/2024
1.0.3 421 6/12/2024