Skip to content

Refit based web api client management, but resilient (retry, connectivity, cache, auth, log, priority, etc...)

License

Notifications You must be signed in to change notification settings

Respawnsive/Apizr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Apizr

Refit based web api client management, but resilient (retry, connectivity, cache, auth, log, priority, etc...)

Read - Documentation Watch - Tutorials

What

The Apizr project was motivated by this 2015 famous blog post about resilient networking.

Its main focus was to address at least everything explained into this article, meanning:

  • Easy access to restful services
  • Work offline with cache management
  • Handle errors with retry pattern and global catching
  • Handle request priority
  • Check connectivity
  • Fast development time
  • Easy maintenance
  • Reuse existing libraries

But also, some more core features like:

  • Trace http traffic
  • Handle authentication

And more integration/extension independent optional features like:

  • Choose cache, log and connectivity providers
  • Register it as an MS DI extension
  • Map model with DTO
  • Use Mediator pattern
  • Use Optional pattern
  • Manage file transfers

The list is not exhaustive, there’s more, but what we wanted was playing with all of it with as less code as we could, not worrying about plumbing things and being sure everything is wired and handled by design or almost.

Inspired by Refit.Insane.PowerPack, we wanted to make it simple to use, mixing attribute decorations and fluent configuration.

How

An api definition with some attributes:

// (Polly) Define a resilience pipeline key
// OR use Microsoft Resilience instead
[assembly:ResiliencePipeline("TransientHttpError")]
namespace Apizr.Sample
{
    // (Apizr) Define your web api base url and ask for cache and logs
    [BaseAddress("https://reqres.in/"), 
    Cache(CacheMode.FetchOrGet, "01:00:00"), 
    Log(HttpMessageParts.AllButBodies)]
    public interface IReqResService
    {
        // (Refit) Define your web api interface methods
        [Get("/api/users")]
        Task<UserList> GetUsersAsync([RequestOptions] IApizrRequestOptions options);

        [Get("/api/users/{userId}")]
        Task<UserDetails> GetUserAsync([CacheKey] int userId, [RequestOptions] IApizrRequestOptions options);

        [Post("/api/users")]
        Task<User> CreateUser(User user, [RequestOptions] IApizrRequestOptions options);
    }
}

Some resilience strategies:

// (Polly) Create a resilience pipeline (if not using Microsoft Resilience)
var resiliencePipelineBuilder = new ResiliencePipelineBuilder<HttpResponseMessage>()
    .AddRetry(
        new RetryStrategyOptions<HttpResponseMessage>
        {
            ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
                .Handle<HttpRequestException>()
                .HandleResult(response =>
                    response.StatusCode is >= HttpStatusCode.InternalServerError
                        or HttpStatusCode.RequestTimeout),
            Delay = TimeSpan.FromSeconds(1),
            MaxRetryAttempts = 3,
            UseJitter = true,
            BackoffType = DelayBackoffType.Exponential
        });

An instance of this managed api:

Relies on IServiceCollection extension methods approach.

// (Logger) Configure logging the way you want, like
services.AddLogging(loggingBuilder => loggingBuilder.AddDebug());

// (Apizr) Add an Apizr manager for the defined api to your container
services.AddApizrManagerFor<IReqResService>(
    options => options
        // With a cache handler
        .WithAkavacheCacheHandler()
        // If using Microsoft Resilience
        .ConfigureHttpClientBuilder(builder => builder
            .AddStandardResilienceHandler()));

// (Polly) Add the resilience pipeline (if not using Microsoft Resilience)
services.AddResiliencePipeline<string, HttpResponseMessage>("TransientHttpError",
    builder => builder.AddPipeline(resiliencePipelineBuilder.Build()));
...

// (Apizr) Get your manager instance the way you want, like
var reqResManager = serviceProvider.GetRequiredService<IApizrManager<IReqResService>>();

Relies on static builder instantiation approach.

// (Polly) Add the resilience pipeline with its key to a registry
var resiliencePipelineRegistry = new ResiliencePipelineRegistry<string>();
resiliencePipelineRegistry.TryAddBuilder<HttpResponseMessage>("TransientHttpError", 
    (builder, _) => builder.AddPipeline(resiliencePipelineBuilder.Build()));

// (Apizr) Get your manager instance
var reqResManager = ApizrBuilder.Current.CreateManagerFor<IReqResService>(
    options => options
        // With a logger
        .WithLoggerFactory(LoggerFactory.Create(loggingBuilder =>
            loggingBuilder.Debug()))
        // With the defined resilience pipeline registry
        .WithResiliencePipelineRegistry(resiliencePipelineRegistry)
        // And with a cache handler
        .WithAkavacheCacheHandler());

And then you're good to go:

var userList = await reqResManager.ExecuteAsync((api, opt) => api.GetUsersAsync(opt));

This request will be managed with the defined resilience strategies, data cached and all logged.

Apizr has a lot more to offer, just read the doc!

Where

Managing (Core)

Project Current Upcoming
Apizr NuGet NuGet Pre Release
Apizr.Extensions.Microsoft.DependencyInjection NuGet NuGet Pre Release

Caching

Project Current Upcoming
Apizr.Extensions.Microsoft.Caching NuGet NuGet Pre Release
Apizr.Integrations.Akavache NuGet NuGet Pre Release
Apizr.Integrations.MonkeyCache NuGet NuGet Pre Release

Handling

Project Current Upcoming
Apizr.Integrations.Fusillade NuGet NuGet Pre Release
Apizr.Integrations.MediatR NuGet NuGet Pre Release
Apizr.Integrations.Optional NuGet NuGet Pre Release

Mapping

Project Current Upcoming
Apizr.Integrations.AutoMapper NuGet NuGet Pre Release
Apizr.Integrations.Mapster NuGet NuGet Pre Release

Transferring

Project Current Upcoming
Apizr.Integrations.FileTransfer NuGet NuGet Pre Release
Apizr.Extensions.Microsoft.FileTransfer NuGet NuGet Pre Release
Apizr.Integrations.FileTransfer.MediatR NuGet NuGet Pre Release
Apizr.Integrations.FileTransfer.Optional NuGet NuGet Pre Release

Generating

Project Current Upcoming
Refitter NuGet NuGet Pre Release
Refitter.SourceGenerator NuGet NuGet Pre Release

Install the NuGet reference package of your choice:

  • Apizr package comes with the static builder instantiation approach (which you can register in your DI container then)
  • Apizr.Extensions.Microsoft.DependencyInjection package extends your IServiceCollection with AddApizr, AddApizrFor and AddApizrCrudFor registration methods
  • Apizr.Extensions.Microsoft.Caching package brings an ICacheHandler method mapping implementation for MS Extensions Caching
  • Apizr.Integrations.Akavache package brings an ICacheHandler method mapping implementation for Akavache
  • Apizr.Integrations.MonkeyCache package brings an ICacheHandler method mapping implementation for MonkeyCache
  • Apizr.Integrations.Fusillade package enables request priority management using Fusillade
  • Apizr.Integrations.MediatR package enables request auto handling with mediation using MediatR
  • Apizr.Integrations.Optional package enables Optional result from mediation requests (requires MediatR integration) using Optional.Async
  • Apizr.Integrations.AutoMapper package enables data mapping using AutoMapper
  • Apizr.Integrations.Mapster package enables data mapping using Mapster
  • Apizr.Integrations.FileTransfer package enables file transfer management for static registration
  • Apizr.Extensions.Microsoft.FileTransfer package enables file transfer management for extended registration
  • Apizr.Integrations.FileTransfer.MediatR package enables file transfer management for mediation requests (requires MediatR integration and could work with Optional integration) using MediatR
  • Apizr.Integrations.FileTransfer.Optional package enables file transfer management for mediation requests with optional result (requires MediatR integration and could work with Optional integration) using Optional.Async

Choose which generating approach suites to your needs by installing either:

Apizr core package make use of well known nuget packages to make the magic appear:

Package Features
Refit Auto-implement web api interface and deal with HttpClient
Polly.Extensions Apply some policies like Retry, CircuitBreaker, etc...
Microsoft.Extensions.Logging.Abstractions Delegate logging layer to MS Extensions Logging

It also comes with some handling interfaces to let you provide your own services for:

  • Caching with ICacheHandler, which comes with its default VoidCacheHandler (no cache), but also with:
    • InMemoryCacheHandler & DistributedCacheHandler: MS Extensions Caching methods mapping interface (Integration package referenced above), meaning you can provide any compatible caching engine
    • AkavacheCacheHandler: Akavache methods mapping interface (Integration package referenced above)
    • MonkeyCacheHandler: MonkeyCache methods mapping interface (Integration package referenced above)
  • Logging As Apizr relies on official MS ILogger interface, you may want to provide any compatible logging engine (built-in DebugLogger activated by default)
  • Connectivity with IConnectivityHandler, which comes with its default VoidConnectivityHandler (no connectivity check)
  • Mapping with IMappingHandler, which comes with its default VoidMappingHandler (no mapping conversion), but also with:
    • AutoMapperMappingHandler: AutoMapper mapping methods mapping interface (Integration package referenced above)
    • MapsterMappingHandler: Mapster mapping methods mapping interface (Integration package referenced above)