HTTP Api Client framework built on MS HttpClient
$ dotnet add package Plinth.HttpApiClientHTTP Api Client framework built on MS HttpClient
Adds logging and tracing to HttpClient based API clients.
There are two supported approaches to building clients, autogenerated clients and manually built clients.
npm install -g nswag $targetServiceSwaggerUrl = "{url or path to openapi spec}"
$targetServiceName = "{client class name}"
$namespace = "{client namespace}"
$nswagParams = @(
'openapi2csclient',
'/runtime:net70',
"/input:\`"${targetServiceSwaggerUrl}\`"",
"/classname:${targetServiceName}Client",
"/namespace:${namespace}",
"/output:${targetServiceName}Client.cs",
'/operationGenerationMode:SingleClientFromOperationId',
'/generateClientInterfaces:true',
'/injectHttpClient:true',
'/useBaseUrl:false',
'/disposeHttpClient:false',
'/generateOptionalParameters:true'
'/exceptionClass:NSwagException',
'/generateExceptionClasses:true',
'/parameterDateTimeFormat:o',
'/generateNullableReferenceTypes:true',
'/excludedParameterNames:X-Plinth-Auth'
)
nswag @nswagParams | Out-Host
Documentation for configuration options: https://github.com/RicoSuter/NSwag/wiki/NSwag-Configuration-Document
Also available using `nswag help openapi2csclient
Register the client during Startup
services.AddHttpApiHandlerClient<INSwagClient, NSwagClient>(
"NSwagClient",
configureClient: c =>
{
c.BaseAddress = new Uri("http://localhost:5000");
});
Build a manual api client by deriving from BaseHttpApiClient and implementing API methods using HttpRequestMessage extensions. Example below:
public class MyClient : BaseHttpApiClient
{
public MyClient(HttpClient client) : base("MyApi", client)
{
}
public async Task<ModelObject?> GetThing(int parameter)
{
return await HttpGet("/api/values/thing")
.AddQueryParameter("param", parameter)
.ExecuteAsync<ModelObject>();
}
public async Task<ModelObject?> CreateThing(ModelObject modelObject)
{
return await HttpPost("/api/values/thing")
.SetJsonBody(modelObject)
.SetAuthorization("myApiToken")
.ExecuteAsync<ModelObject>();
}