Combining Refit and "Have I been Pwned".
Refit is an amazing library and is my preferred way of communicating with API's where I can't generate the client from OpenAPI specifications (via NSwag).
My team and I needed to connect to a few API where we didn't have a specification, so this is an ideal example for them to look at.
Here's a simplified example of a client:
public interface IBreachClient
{
[Get("/api/v3/breachedaccount/{account}")]
Task<BreachDetail[]> GetAllBreachesForAccount(string account,
bool truncateResponse = false,
string domain = null,
bool includeUnverified = false);
[Get("/api/v3/breaches")]
Task<BreachDetail[]> GetBreaches(string domain = default);
}
See full source for IBreachClient
Delegating handlers are used to provide the HIBP token and user agent to each request. Although you could use similar attributes inside your interface (as per the example below), I prefer the handler approach.
[Headers("User-Agent: HaveIBeenRefitted Client")]
public interface IBreachClient
{
[Get("/api/v3/breaches")]
Task<BreachDetail[]> GetBreaches(string domain = default);
}
See full source for UserAgentDelegatingHandler or TokenProviderDelegatingHandler.
Simply initialize the service via the provided service extension method:
var services = builder.Services.AddHaveIBeenRefitted(
o =>
{
o.UserAgent = "Have I Been Refitted";
o.BaseUrl = "https://haveibeenpwned.com";
});
I have included a minimal API that should hopefully explain everything!