NSwag is a .NET toolset for working with OpenAPI descriptions. It can generate an OpenAPI document for an ASP.NET Core API or turn an existing document into a strongly typed C# client. The client handles API paths, parameters, and request and response serialization, so another C# application needs less hand-written HTTP code. section 11.4 section 11.7
Figure 11.6 Visual Studio or a .NET tool downloads the OpenAPI description locally and installs the code-generation tool from NuGet. When your project builds, the generation tool reads the OpenAPI description and generates a C# class for interacting with the API.
Follow the path from a downloaded OpenAPI JSON file to a generated C# client. The generator runs during a build when the local description file changes. section 11.4
To generate a client with the .NET OpenAPI tool:
- Run an API that exposes an OpenAPI JSON document, and have a C# project ready to call it. section 11.4.2
- Install the tool with `dotnet tool install -g Microsoft.dotnet-openapi`, then use `dotnet openapi add url` to download the document into the client project. section 11.4.2
- Add the required client-generation packages. Check the resulting `<OpenApiReference>` in the project file; it can specify the document, client class name, and namespace. section 11.4.2
Listing 11.7 Customizing NSwag generator options
<OpenApiReference Include="OpenAPIs\fruit.json" SourceUrl="http://localhost:5062/swagger/v1/swagger.json" Namespace="Fruit" ClassName="FruitClient" > <Options>/UseBaseUrl:false /GenerateClientInterfaces:true ➥ /JsonLibrary:SystemTextJson</Options> #1 </OpenApiReference> #2 #1 Customizes the options NSwag uses for code generation #2 Make sure to close the outer XML element to keep the XML valid.
The project-file example puts generator options inside `<OpenApiReference>`: use System.Text.Json, generate a client interface, and take the API base address from HttpClient rather than a constructor argument. section 11.4.4
The generated client is partial, so a separate partial class can add methods or implement request hooks without editing generated code. An optional generated interface makes it easier to substitute a fake client in tests. Client generation is not required: Postman or another HTTP client can also call the API. If a newer OpenAPI feature is missing from an upstream document, NSwag cannot generate a client for that missing detail. section 11.4.4 section 11.4 section 11.6.3
