OpenAPI defines a way for web services to clearly define their API for automatic and correct client library generation, and with NSwag, clients for these APIs can be automatically generated for C#. What’s more, rather than generating the source code for these clients manually, a service reference can be added to your .csproj file to generate these clients transparently and automatically at development-time and build-time, —essentially It Just Works! This is truly an amazing (although not specifically unique,) benefit of the .NET tooling ecosystem; any IDE which plugs into the common .NET C# language backend (VS, Code, Rider, you name it) will immediately see and present the generated API client classes and their methods in type suggestions, without anything files having to be compiled or included manually by the developer.
Today I’ll write on how to go about this via a dotnet command-line tool; applicable regardless of the IDE or development platform you use. Whilst Visual Studio users get a simple (and obvious) wizard for adding these API service references, the information regarding the platform-agnostic command-line version seems to be scattered across the ASP.NET Core docs, and personally I felt it was quite obscure and challenging to find. Hopefully this blog post speeds up this process for any other developers going through these same steps for the first time.
Continue reading “Add automatic OpenAPI client code generation to .NET 6 apps using dotnet-openapi, NSwag and service references”