I need to call an external API that requires to send its key as a query string. The API has GET and POST endpoints. In both endpoints, there are no (currently) other parameters in queries
So, an example query should look like
https://example.com/service?key={key value}
I want to not add the query at all places where I call the client and rather configure it on the startup.
Normally, the examples I see put query strings as part of the route to the HTTP client with the question mark in between the route and query.
Is it possible to inject a key as a query string on startup without writing complicated extensions/logic?
I set up the injection like
var settings = configuration.GetSection(nameof(ApiSettings)).Get<ApiSettings>();
services.AddHttpClient<IMyService, MyService>
(client =>
{
client.BaseAddress = new Uri(settings.BaseAddress);
});
and then consume it like
public class MyService : IMyService
{
private readonly IHttpClientFactory _httpClientFactory;
public MyService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
private HttpClient CreateClient() => _httpClientFactory.CreateClient();
public async Task<RouteDetails> GetRouteDetails(ICollection<Point> points)
{
var httpClient = CreateClient();
var response = await httpClient.PostAsync($"/api/poi", new JsonContent(points));
...
}
}
I am looking for something easy to read and not too much extra code. I believe plenty APIs consume their access keys as a query string, so, there should be an out-of-the-box solution that I am missing.
I can also reference Refit if it is easier.