Cabazure.Client 0.6.2

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

// Install Cabazure.Client as a Cake Tool
#tool nuget:?package=Cabazure.Client&version=0.6.2                

GitHub Actions Workflow Status GitHub Release Date NuGet Version NuGet Downloads

Branch Coverage Line Coverage Method Coverage

Cabazure.Client

The Cabazure.Client is a library for creating .NET Clients for your AspNetCore APIs, using Source Generators directed by attributes.

The main design choices in the Cabazure.Client are:

  • Code is used to describe the API, rather than an api specification
  • Contracts are shared via code used by both Client and Server
  • Endpoints are represented as interfaces, for easy mocking in unit testing
  • Dependencies are limited to AspNetCore defaults, like DependencyInjection and Options
  • Azure.Identity is used for Authentication

Getting started

Ensure your Client project has a reference to the Cabazure.Client package and the contract data types used by your service.

1. Adding an endpoint

Endpoints are added by creating interfaces decorated with attributes, like this:

[ClientEndpoint("CustomerClient")]
public interface IGetCustomerEndpoint
{
    [Get("/v1/customers/{customerId}")]
    public Task<EndpointResponse<Customer>> ExecuteAsync(
      [Path("customerId")] string customerId,
      ClientRequestOptions options,
      CancellationToken cancellationToken);
}

The [ClientEndpoint] attribute declares that this is an endpoint, that should have the implementation generated. The client name ("CustomerClient"), is used for identifying which HttpClient instance name this endpoint should use. The client name should be unique for this Client, and needs to match the client name used when adding the boot strap.

The [Get] attribute declares that the interface method is targeting a GET endpoint on the specified path. The path can have place holders like {customerId} which can be referenced by one of the method parameters using the [Path] attribute.

The following HTTP methods are supported by corresponding attributes: [Get], [Post], [Put] or [Delete].

The return type of Task<EndpointResponse<Customer>>, is a wrapper for the actual contract data type Customer. The following return type wrappers are supported:

Type Description
Task<EndpointResponse> Used when there is no response content
Task<EndpointResponse<T>> Used for endpoints with a response object
Task<PagedResponse<T[]>> Used for endpoints with a paged response

The [Path] attribute on the customerId parameter of the endpoint method, declares that this parameter corresponds to the endpoint path placeholder. Parameters containing data for an endpoint method should have one of the following attributes describing how they are passed to the endpoint: [Path], [Query], [Header] or [Body].

Apart from the data parameters, the following parameter types are supported:

Parameter Type Description
ClientRequestOptions Allowing the caller to specify further request options.
PagedRequestOptions Allowing the caller to specify further request and pagination options.
CancellationToken Allowing the caller to cancel the async call to the endpoint.

2. Adding a bootstrap

To register relevant dependencies for the Client, the generated AddCabazureClient extension method on IServiceCollection needs to be called. This will register all the endpoints for the specified HttpClient instance as singletons in the IServiceCollection.

To make it easy for the user of the Client, it is recommended to do this in a bootstrap method like this:

namespace Microsoft.Extensions.DependencyInjection;

public static class ServiceCollectionExtensions
{
    public static void AddCustomerClient(
        this IServiceCollection services)
        => services.AddCabazureClient(
            "CustomerClient",
            j => j.PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            b => b
              .SetBaseAddress(new Uri("https://customer-api.contoso.com"))
              .AddAuthentication(
                scope: "app://contoso.com/customer-api/.default",
                credential: new DefaultAzureCredential()));
}

The call to AddCabazureClient needs the following:

  • The name of the HttpClient instance (matching the one specified on the endpoints)
  • Configuration of the JsonSerializerOptions used for serialization of the contracts
  • Configuration of the HttpClient (using an IHttpClientBuilder)
Alternative: Configuration using options

When creating a client for multiple environments, it can make sense to configure these using the options framework.

This can be done by creating an options class for your client, and implementing one of the following Cabazure.Client interfaces:

Options Interface Description
ICabazureClientOptions The base options interface used to describe options that can resolve the BaseAddress of the API.
ICabazureAuthClientOptions Options interface used for clients that needs to authenticate. The interface exposes methods for resolving the scope and TokenCredentials to be used.

For the Customer Client the options could look like this:

public class CustomerClientOptions : ICabazureAuthClientOptions
{
    public string? EnvironmentName { get; set; }

    public TokenCredential? Credential { get; set; }

    Uri ICabazureClientOptions.GetBaseAddress()
        => EnvironmentName switch
        {
            "prod" => new Uri("https://customer-api.contoso.com"),
            { } env => new Uri($"https://customer-api.{env}.contoso.com"),
            _ => new Uri("https:localhost:7001"),
        };

    string ICabazureAuthClientOptions.GetScope()
        => string.Concat(
            "app://contoso.com/",
            EnvironmentName ?? "dev",
            "/customer-api/.default");

    TokenCredential ICabazureAuthClientOptions.GetCredential()
        => Credential
        ?? throw new InvalidOperationException(
            "Credential must be set to use the Customer client.");
}

With these options in place the bootstrap, can be simplified like this:

namespace Microsoft.Extensions.DependencyInjection;

public static class ServiceCollectionExtensions
{
    public static void AddCustomerClient(
        this IServiceCollection services,
        Action<CustomerClientOptions>? clientOptions = null)
        => services.AddCabazureClient(
            "CustomerClient",
            j => j.PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            clientOptions);
}

This allows the caller to either specify the CustomerClientOptions inline, or configure them using the options framework, e.g. by implementing IConfigureOptions<CustomerOptions> and then register it with the IServiceCollection.ConfigureOptions<T>() extension method.

3. Using the client

To use the Client library, the bootstrap method should be called during composition of the Hosting app, like this:

builder.Services.AddCustomerClient();

If options are used, these can be specified inline, like this:

builder.Services.AddCustomerClient(o =>
{
    o.EnvironmentName = "dev";
    o.Credential: new DefaultAzureCredential();
});

or they can be configured using an implementation of IConfigureOptions<CustomerClientOptions>, like this:

public class ConfigureCustomerClientOptions
    : IConfigureOptions<CustomerClientOptions>
{
    public void Configure(CustomerClientOptions options)
    {
        options.EnvironmentName = EnvironmentNames.Development;
        options.Credential = new DefaultAzureCredential();
    }
}

which is registered in the IServiceCollection, like this:

builder.Services.ConfigureOptions<ConfigureCustomerClientOptions>();

After the Client is configured the endpoints can be used by adding the endpoint interface to the constructor of the consuming class, like this:

public class CustomerNameProvider(
    IGetCustomerEndpoint endpoint)
{
    public async Task<string?> GetCustomerNameAsync(
        string customerId,
        CancellationToken cancellationToken)
        => await endpoint.ExecuteAsync(
            customerId,
            new ClientRequestOptions(),
            cancellationToken)
        switch
        {
            { OkContent: { } c } => c.Name,
            _ => null,
        };
}
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 was computed.  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. 
.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

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.0.0 163 10/22/2024
1.0.0-preview1 54 10/22/2024
0.9.0 323 10/8/2024
0.8.0 404 8/9/2024
0.7.1 100 8/7/2024
0.7.0 91 8/7/2024
0.7.0-preview1 89 8/7/2024
0.6.2 73 8/6/2024
0.6.1 68 8/6/2024
0.6.0 65 8/6/2024
0.5.1 70 8/5/2024
0.5.0 72 8/5/2024
0.5.0-preview2 104 7/8/2024
0.5.0-preview1 98 7/8/2024
0.4.2 107 7/2/2024
0.4.1 102 6/27/2024
0.4.0 111 6/27/2024
0.3.4 108 6/26/2024