Generate code with NSwag using the OpenAPI Specification

banner
Warning

It appears that the popular Swashbuckle.AspNetCore project isn't being actively maintained anymore, and doesn't support .NET 8. NSwag provides a good and battle-tested alternative, to get started see the Microsoft Guide.

I was always skeptical about code generation tools using the OpenAPI specification. But recently, I decided to give it another go, and surprisingly it was a positive experience!

My use case was an integration with a 3rd party, instead of writing all the DTO models and endpoints manually I resorted to NSwag to generate an HTTP client (including all of its dependencies) for me. You can also use this for code that you own.

NSwag provides different methods for generating code, ranging from a manual operation to an automated way. Besides C# HTTP Clients, it also supports the generation of C# Models/Controllers, as well as TypeScript clients for most front-end technologies, e.g. Angular.

Importing an OpenAPI specification using NSwagStudio

All of these gives you a working C# HTTP Client, including the needed models, interfaces, ... as output.

Tip

There's also the .NET Core Global Tool Microsoft.dotnet-openapi to generate HTTP clients using the OpenAPI specification. Internally it uses NSwag for the generation. From my limited experience with it, it isn't as versatile as the toolkit that NSwag provides, NSwag is also better documented. But, dotnet openapi definitely something to keep an eye out for in the future.

The add will also create an OpenApiReference within the project, which is +/- the same as adding an OpenAPI specification via Visual Studio. Because of this, it can also be interpreted by Visual Studio, and the generated client can be viewed and refreshed via the UI.

Connected services in Visual Studio

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Share this bit on

Twitter LinkedIn