As web applications become more complex and feature-rich, the need for robust and maintainable APIs has never been greater. In this post, we’ll show you how to use ASP.NET Core and the OpenAPI specification to automatically generate TypeScript clients for your API, making it easier to consume and interact with your API from front-end applications.
Generating OpenAPI spec
For generating the OpenAPI spec file, the dotnet swagger
tool is used. It is necessary to have the Swashbuckle.AspNetCore
NuGet package referenced in the project to output OpenAPI spec for. It is also necessary to have both .AddSwaggerGen()
and .UseSwagger()
in Program.cs
or Startup.cs
.
To automatically generate the OpenAPI spec file on build, the following Target
element can be added to the .csproj
file of the project to generate spec file for.
<Target Name="OpenAPI" AfterTargets="Build" Condition="$(Configuration)=='Debug'">
<Exec Command="dotnet swagger tofile --output open-api-spec.json $(OutputPath)$(AssemblyName).dll v1" WorkingDirectory="$(ProjectDir)" LogStandardErrorAsError="true" />
</Target>
(LogStandardErrorAsError="true"
makes debugging issues much easier)
Generating TypeScript clients
To use that OpenAPI spec file for generating TypeScript clients, another Target
element can be added. This one runs after the OpenAPI one, and uses the openapi-generator-cli
tool to generate TypeScript clients using fetch
:
<Target Name="TypescriptClients" AfterTargets="OpenAPI" Condition="$(Configuration)=='Debug'">
<Exec Command="swagger-codegen-cli generate -i ./open-api-spec.json -l typescript-fetch -o ./typescript-clients" WorkingDirectory="$(ProjectDir)" LogStandardErrorAsError="true" />
</Target>
Using openapi-generator-cli
Instead of installing swagger-codegen-cli
and its dependency java
, it is easier to create a .bat
file that runs the swagger-codegen-cli
command in a Docker container. This .bat
file can be placed in a directory that is included in the Path
environment variable, so that it can be run from the command line or from an IDE. An example of such a .bat
file looks like this:
@echo off
docker run --rm -v %CD%:/data --workdir /data openapitools/openapi-generator-cli %*
Using this .bat
file, it is possible to use the swagger-codegen-cli
command without having to install swagger-codegen-cli
or java
on the local system.
This can be a convenient way to use the swagger-codegen-cli
tool without dealing with the complexities of installation and dependency management. Read more about this approach in my previous post