lecaillon / Restack

Restack is an easy to declare and inject, autogenerated proxy for an HTTP service.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Restack

Restack is an easy to declare and inject, autogenerated proxy for an HTTP service. The idea is to make a full featured resilient HTTP client. It's inspired by the David Fowler's project RestSample and forked from Ryan Nowak work on Kickr.

Its implementation is based on:

Example of the refit / Polly support

  1. Define an interface for your rest service.
    public interface IGeoApi
    {
        [Get("/regions")]
        Task<IEnumerable<Region>> GetRegionsAsync();
    }
  2. Configure the URL for your service and add some http request headers and policies.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        
        services.AddRestack() // configure Restack HttpClientFactory
                .AddPolly();  // configure Polly
    
        services.AddRestackGlobalHeaders(o => o.Headers.Add("user-agent", "myagent"));
    
        services.AddRestClient<IGeoApi>("https://geo.api.gouv.fr")
                .AddRestackHeaders<IGeoApi>(o => o.Headers.Add("api-key", "xxxxx-xxx-xxxxxxxx"))
                .AddRestackPolicy<IGeoApi>(b => b.RetryAsync())
                .AddRestackPolicy<IGeoApi>(b => b.CircuitBreakerAsync(1, TimeSpan.FromSeconds(5)));
    }
  3. Consume the interface via RestClient<T>.
    public class HomeController : Controller
    {
        private readonly IGeoApi _geoApi;
    
        public HomeController(IRestClient<IGeoApi> geoApiClient)
        {
            _geoApi = geoApiClient.Client;
        }
    
        [HttpGet("/")]
        public async Task<IActionResult> Get()
        {
            var regions = await _geoApi.GetRegionsAsync();
    
            return Ok(regions);
        }
    }

Example of the ASP.NET MVC HttpClient param binding support

  1. Configure some http request headers for the "github" named http client".
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddRestackModelBinder(); // configure Restack MVC
        
        services.AddRestack(); // configure Restack HttpClientFactory
    
        services.AddRestackGlobalHeaders(o => o.Headers.Add("user-agent", "myagent"));
        services.AddRestackHeaders("github", o => o.Headers.Add("Accept", "application/vnd.github.v3+json"));
    }
  2. Consume the HttpClient.
    public class HomeController : Controller
    {
        public async Task<IActionResult> Index([HttpClientName("github")]HttpClient client)
        {
            var response = await client.GetAsync("https://api.github.com/users/lecaillon");
            ...
        }
    }

About

Restack is an easy to declare and inject, autogenerated proxy for an HTTP service.


Languages

Language:C# 100.0%