Skip to content

Generating Web Clients from OpenAPI Specifications

A while back I published a source code generator for C# that scaffolds web APIs from OpenAPI specifications. Since then I’ve realized that the available OpenAPI source generated clients, like Microsoft’s Kiota, seems to suffer similar lack in functionality and type safety as it’s web api scaffolding counterparts. So I decided to open source my own, strongly typed, fully featured, generator for web clients; OpenApi.WebClientGenerator.

The generator is exclusively generating clients in C#, and is, similar to the Web API generator, also an incremental source generator, meaning it generates the clients into an existing assembly.

Getting started:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net10.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Corvus.Json.ExtendedTypes" Version="4.4.2" />
        <PackageReference Include="ParameterStyleParsers.OpenAPI" Version="1.5.0" />
    </ItemGroup>

    <ItemGroup>
        <PackageReference Include="WebClientGenerator.OpenAPI" Version="x.y.z" PrivateAssets="all" />
    </ItemGroup>
    <ItemGroup>
        <WebClientGenerator Include="path/to/openapi.json" ClientName="Foo" Namespace="Example" />
    </ItemGroup>

</Project>

Build, and then use:

using var client = new Example.Foo(Servers.Production);

The generated clients are strongly typed wrappers around HttpClient, so it’s still possible to customize behavior that might not be defined by an OpenAPI specification.

It supports all OpenAPI specifications currently published.

Corvus.JsonSchema

As with the Web API generator, the client generator also generates JSON schema models using Corvus.JsonSchema.

ParameterStyleParsers.OpenAPI

OpenAPI parameters are parsed by ParameterStyleParsers.OpenAPI, same as for the generated Web API.

Published in.netspecification

Be First to Comment

Leave a Reply