Faactory.RestClient 0.3.2

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

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

REST Client for .NET

This projects contains the implementation for a REST Client for .NET. It's built on top of the original HttpClient and fully supports IHttpClientFactory for dependency injection.

Getting started

Install the package.

$ dotnet add package Faactory.RestClient

To create a client instance using dependency injection

IServiceCollection services = new ServiceCollection()
    ...
    .AddRestClient( "jsonplaceholder", "https://jsonplaceholder.typicode.com" )
    ...

This will give you access to an IRestClientFactory interface. Then, wherever you need a client

public class MyClass
{
    private readonly IRestClient client;

    public MyClass( IRestClientFactory clientFactory )
    {
        client = clientFactory.CreateClient( "jsonplaceholder" );
    }
    ...
}

If you rather create a client instance manually, an HttpClient instance needs to be passed into the constructor

var httpClient = ...
var restClient = new RestClient( httpClient, "https://jsonplaceholder.typicode.com" );

Using

All request operations respond with a RestResponse, containing the response's status code, headers and content, if any.

var response = await restClient.GetAsync( "todos/1" );

if ( response.IsOk() )
{
    // do something with the content only if response is a 200 OK
}

Configuring per request

It is possible to customize a request's configuration, such as headers or query parameters. We do that by invoking Configure and a configuration method, which returns a new instance.

var response = await restClient.Configure( options =>
{
    options.QueryParameters.Add( "address.city", "Bartholomebury" );
})
.GetAsync( "users" );

The instance returned by the Configure method is not the same as the original. It's also worth noting that the new instance is reusable and multiple operations can be performed with it. Here's an example

var request = restClient.Configure( options =>
{
    options.Headers.Add( "X-Custom-Header", "custom header value" );
} );

var ids = new int[] { 1, 2, 3 };

var getTasks = ids.Select( id => request.GetAsync( $"users/{id}" ) )
    .ToArray();

var responses = await Task.WhenAll( getTasks );

Working with JSON

The client includes extensions to serialize and deserialize JSON content. This can be done by manually deserializing a RestResponse instance

var response = await restClient.GetAsync( "todos/1" );

var todo = response.Deserialize<Todo>();

Or directly with the request extension, which returns the deserialized instance instead; be aware that this method will only deserialize the content if the response's status code is a 200 (Ok), otherwise it will return default<T>. Something else to consider is that this method doesn't give us access to the response's status code and headers.

var todo = await restClient.GetJsonAsync<Todo>( "todos/1" );

For the other request operations, the serialization process is applied the other way around and the response is always a RestResponse. For example, a POST request

Todo todo = ...;

var response = await restClient.PostJsonAsync( "todos", todo );

By default, JSON serializer is configured with the following options

new System.Text.Json.JsonSerializerOptions
{
    PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
    PropertyNameCaseInsensitive = true
};

This can be changed by calling ConfigureJsonSerializer from the builder instance

IServiceCollection services = new ServiceCollection()
...
services.AddRestClient( "jsonplaceholder", "https://jsonplaceholder.typicode.com" )
    .ConfigureJsonSerializer( jsonOptions =>
    {
        // ...
    } );

Alternatively you can configure directly JsonSerializerOptions, which is what happens behind the scenes with the previous method.

services.Configure<JsonSerializerOptions>( jsonOptions =>
{
    // ...
} );

Polymorphic JSON Serialization

By default, the client uses Microsoft's JSON serializer, therefore, there is limited support for polymorphic serialization and deserialization is not supported at all. You can find more information in this article where you will also find a few workarounds, including writing a custom converter.

Custom serializer

As said before, the client uses Microsoft's JSON serializer by default. If you rather use Newtonsoft's Json.NET (or any other), you can easilly write a custom serializer. Here's an example for Newtonsoft's

public class NewtonsoftJsonSerializer : ISerializer
{
    public byte[] SerializeObject<T>( T value )
    {
        var json = JsonConvert.SerializeObject( value );

        return Encoding.UTF8.GetBytes( json );
    }
    
    public T DeserializeObject<T>( byte[] content )
    {
        var json = Encoding.UTF8.GetString( content );

        return JsonConvert.DeserializeObject<T>( json );
    }
}

If you are using dependency injection, you can add the serializer by injecting it into the container services.

IServiceCollection services = new ServiceCollection()
...
services.AddRestClient( "jsonplaceholder", "https://jsonplaceholder.typicode.com" )
    .AddSerializer<NewtonsoftJsonSerializer>();

// alternatively you can do this
//services.AddTransient<ISerializer, NewtonsoftJsonSerializer>();

If you are not using dependency injection, just pass it into the constructor.

var httpClient = ...
var restClient = new RestClient( 
    httpClient,
    "https://jsonplaceholder.typicode.com",
    new NewtonsoftJsonSerializer() );

You can also pass a custom serializer when deserializing from a RestResponse instance

var customSerializer = new NewtonsoftJsonSerializer();

var response = await restClient.GetAsync( "todos/1" );

var todo = response.Deserialize<Todo>( customSerializer );

Authorization header

You can use extension methods to configure the Authorization header. Currently, the supported schemes are

  • Basic authentication
  • Bearer token

This can be applied to the entire client, when configuring the underlying HttpClient instance with dependency injection

IServiceCollection services = new ServiceCollection()
    ...
    .AddRestClient( "jsonplaceholder", "https://jsonplaceholder.typicode.com", httpClient =>
    {
        httpClient.AddBasicAuthentication( "username", "password" );
    } )
    ...

when manually creating the client instance, by accessing the underlying client extensions

var httpClient = ...

httpClient.AddBasicAuthentication( "username", "password" );

var restClient = new RestClient( httpClient, "https://jsonplaceholder.typicode.com" );

// accessing the underlying client instance works the same
// restClient.HttpClient.AddBasicAuthentication( "username", "password" );

or when customizing/scoping a request

var response = await restClient.Configure( "users", options =>
{
    options.AddBasicAuthentication( "username", "password" );
})
.GetAsync();

Note: These extensions require adding the namespace Faactory.RestClient

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  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 was computed.  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. 
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 Faactory.RestClient:

Package Downloads
Fonix.Extensions.ApiClient

Fonix APIs RestClient Extensions

Faactory.DbContext.RestSql

DbContext RestSql provider

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.4.0-preview-1 106 7/26/2023
0.3.2 236 7/10/2023
0.3.1 154 5/4/2023
0.3.0 601 8/9/2022
0.3.0-preview-6 115 8/9/2022
0.3.0-preview-5 146 8/9/2022
0.3.0-preview-4 111 8/8/2022
0.3.0-preview-2 113 8/5/2022
0.3.0-preview-1 114 8/5/2022
0.2.1 652 3/28/2022
0.1.8 604 11/3/2021
0.1.7 269 10/7/2021
0.1.6 302 8/12/2021
0.1.5 270 8/12/2021
0.1.4 319 8/3/2021
0.1.3 351 7/29/2021
0.1.2 373 7/27/2021
0.1.1 276 7/21/2021
0.1.0 284 7/21/2021