Generate code with NSwag using the OpenAPI Specification
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...
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.
- NSwagStudio: a Windows Desktop application to import an OpenAPI specification, and configure the parameters to generate the output file. Based on the configuration you can generate a client and/or save the configuration to an NSwag configuration document (
*.nswag.json), which can be used later again with the intent to regenerate the client.
- A CommandLine Tool with commands to generate code based on an NSwag configuration document (which is created with NSwagStudio)
# ๐ created with NSwagStudionswag# There's currently an issue with using Net80
- NSwag.MSBuild to incorporate the generation process during a build (this also uses the NSwag config file)
<PropertyGroup><RunPostBuildEvent></RunPostBuildEvent></PropertyGroup><TargetNameAfterTargetsCondition><ExecWorkingDirectoryEnvironmentVariablesCommand/></Target>
- NSwag.CodeGeneration.CSharp, a NuGet package to generate code using C#. There's also a TypeScript equivalent NSwag.CodeGeneration.TypeScript to generate TypeScript code.
usingNSwag;usingNSwag.CodeGeneration.CSharp;awaitGenerateCSharpClient(,);staticasyncTaskGenerateCSharpClient(stringopenApiLocation,stringclassName){vardocument=await.FromUrlAsync();varsettings=newCSharpClientGeneratorSettings{=false,=,=true,={=,},};vargenerator=newCSharpClientGenerator(,);vargeneratedCode=.GenerateFile();varpath={..}{.};varfile=newFileInfo();..Create();await.WriteAllTextAsync(.,);}
All of these gives you a working C# HTTP Client, including the needed models, interfaces, ... as output.
Generated.cs[System.CodeDom.Compiler.GeneratedCode(,)]publicpartialinterfaceIPetStoreClient{/// <paramname=>A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>/// <summary>/// Add a new pet to the store/// </summary>/// <paramname=>Pet object that needs to be added to the store</param>/// <exceptioncref=>A server side error occurred.</exception>System.Threading.Tasks.TaskAddPetAsync(Petbody,System.Threading.CancellationTokencancellationToken);/// <paramname=>A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>/// <summary>/// Find pet by ID/// </summary>/// <remarks>/// Returns a single pet/// </remarks>/// <paramname=>ID of pet to return</param>/// <returns>successful operation</returns>/// <exceptioncref=>A server side error occurred.</exception>System.Threading.Tasks.Task<Pet>GetPetByIdAsync(longpetId,System.Threading.CancellationTokencancellationToken);}
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.
dotnet--code-generator--output-filedotnet--updateProject
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.
Feel free to update this developer bit on GitHub, thanks in advance!