dotnet tool install --global Microsoft.OpenApi.Kiota
Add this to the API project!
dotnet add package Microsoft.Kiota.Bundle
ref: https://learn.microsoft.com/en-gb/openapi/kiota/quickstarts/dotnet
kiota generate -l CSharp -d 3rdparty-openapi.yaml -c The3rdPartyClient -n MyApp.Api.Infrastructure.The3rdPartyClient -o ./Infrastructure/The3rdPartyClient
-l== destination model Language. We want C Sharp :)-d== location of the openapi spec. can be local (to running the command) or a URI.-c== class name-n== namespace-o== output destination folder for all the generated models
builder.Services.AddHttpClient<The3rdPartyClient>();
builder.Services.AddScoped(sp =>
{
var httpClient = sp.GetRequiredService<IHttpClientFactory>().CreateClient();
httpClient.BaseAddress = new Uri("https://example.com/");
// ANON connection
//var adapter = new HttpClientRequestAdapter(new AnonymousAuthenticationProvider(), httpClient: httpClient);
// AUTH connection
var apiKeyProvider = new ApiKeyAuthenticationProvider(
"YOUR_API_KEY",
"api-header-key",
ApiKeyAuthenticationProvider.KeyLocation.Header
);
var adapter = new HttpClientRequestAdapter(apiKeyProvider, httpClient: httpClient);
return new The3rdPartyClient(adapter);
});
namespace MyApp.Api.Infrastructure;
public class The3rdPartyOptions
{
public const string SectionName = "The3rdParty";
public string BaseUrl { get; init; } = "https://example.com/";
public string? ApiKey { get; init; }
}
{
"The3rdParty": {
"BaseUrl": "https://example.com/",
"ApiKey": ""
}
}
builder.Services.Configure<The3rdPartyOptions>(
builder.Configuration.GetSection(The3rdPartyOptions.SectionName));
builder.Services.AddScoped(sp =>
{
var options = sp.GetRequiredService<IOptions<The3rdPartyOptions>>().Value;
var httpClient = sp.GetRequiredService<IHttpClientFactory>().CreateClient();
httpClient.BaseAddress = new Uri(options.BaseUrl);
IAuthenticationProvider authProvider = string.IsNullOrWhiteSpace(options.ApiKey)
? new AnonymousAuthenticationProvider()
: new ApiKeyAuthenticationProvider(
options.ApiKey,
"api-header-key",
ApiKeyAuthenticationProvider.KeyLocation.Header);
var adapter = new HttpClientRequestAdapter(authProvider, httpClient: httpClient);
return new The3rdPartyClient(adapter);
});