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 nswag openapi2csclient /runtime:net60 '/input:http://localhost:5000/swagger/v1/swagger.json' \
/classname:NSwagClient /namespace:My.Project.Client /output:NSwagClient.cs \
/operationGenerationMode:SingleClientFromOperationId /generateClientInterfaces:true \
/injectHttpClient:true /disposeHttpClient:false /useBaseUrl:false /generateOptionalParameters:true \
'/excludedParameterNames:X-Plinth-Auth'
Documentation for configuration options: https://github.com/RicoSuter/NSwag/wiki/NSwag-Configuration-Document
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>();
}