uid |
---|
Uno.Extensions.Http.HowToKiota |
When working with APIs in your application, having a strongly-typed client can simplify communication and reduce boilerplate code. Kiota is a tool that generates strongly-typed API clients from Swagger/OpenAPI definitions. With Uno.Extensions, you can easily register and use Kiota clients in your Uno Platform app without additional setup.
Important
This guide assumes you used the template wizard or dotnet new unoapp
to create your solution. If not, it is recommended that you follow the Creating an application with Uno.Extensions documentation to create an application from the template.
-
Add
Http
to the<UnoFeatures>
property in the Class Library (.csproj
) file:<UnoFeatures> Material; Extensions; + Http; Toolkit; MVUX; </UnoFeatures>
-
Add the UseHttp method to the
IHostBuilder
:protected override void OnLaunched(LaunchActivatedEventArgs args) { var appBuilder = this.CreateBuilder(args) .Configure(hostBuilder => { hostBuilder.UseHttp(); }); ... }
-
Install the Kiota tool:
dotnet tool install --global Microsoft.OpenApi.Kiota
-
Generate the Client using the OpenAPI specification URL:
kiota generate -l CSharp -c MyApiClient -n MyApp.Client -d PATH_TO_YOUR_API_SPEC.json -o ./Client
This will create a client named
MyApiClient
in the Client folder.
-
Register the generated client in the IHostBuilder using
AddKiotaClient
fromUno.Extensions
:protected override void OnLaunched(LaunchActivatedEventArgs args) { var appBuilder = this.CreateBuilder(args) .Configure(hostBuilder => { hostBuilder.UseHttp((context, services) => services.AddKiotaClient<MyApiClient>( context, options: new EndpointOptions { Url = "https://localhost:5002" } ) ); }); }
- Inject the ChefsApiClient into your view model or service and make API requests:
public class MyViewModel
{
private readonly MyApiClient _apiClient;
public MyViewModel(MyApiClient apiClient)
{
_apiClient = apiClient;
}
public async Task GetAll()
{
var something = await _apiClient.Api.GetAsync();
Console.WriteLine($"Retrieved {something?.Count}.");
}
}
-
With
Uno.Extensions.Authentication
, the HttpClient automatically includes the Authorization header. You don't need to manually handle token injection. The middleware ensures the access token is included in each request. -
Ensure your server is running and the swagger.json file is accessible at the specified URL when generating the Kiota client.
- Overview: What is Kiota?
- Overview: HTTP
- How-To: Consume a web API with HttpClient
- How-To: Register an Endpoint for HTTP Requests