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:
- Define an interface for your rest service.
public interface IGeoApi { [Get("/regions")] Task<IEnumerable<Region>> GetRegionsAsync(); }
- 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))); }
- 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); } }
- 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")); }
- 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"); ... } }