NSwag.ApiDescription.Client generates a typed C# client from an OpenAPI description. It turns endpoint metadata into request methods and serialization code, reducing the need to construct URLs or handle JSON manually. section 11.4.1 section 11.4.3
A typical Visual Studio setup follows these steps:
- Add an OpenAPI service reference and provide the description URL, namespace, and generated class name. section 11.4.1
- Confirm the project contains an OpenApiReference using the NSwagCSharp code generator. section 11.4.1
- Update NSwag.ApiDescription.Client and Microsoft.Extensions.ApiDescription.Client when Visual Studio adds outdated package versions. section 11.4.1
- Build the project to generate the client, typically under the obj folder. section 11.4.3
Calling a generated client
Create FruitClient with the API base address and an HttpClient, then call generated methods such as FruitPOSTAsync and FruitGETAsync. The generated implementation supplies endpoint paths and serializes requests and responses. Improve awkward method names by assigning endpoint names with WithName(), which becomes the OpenAPI OperationId. section 11.4.3
Listing 11.6 Calling the API from listing 11.2 using a generated client
using Fruit; #1
var client = new FruitClient( #2
"https://localhost:7186", #3
new HttpClient()); #4
Fruit.Fruit created = await client.FruitPOSTAsync("123", #5
new Fruit.Fruit { Name = "Banana", Stock = 100 }); #6
Console.WriteLine($"Created {created.Name}");
Fruit.Fruit fetched = await client.FruitGETAsync("123"); #7
Console.WriteLine($"Fetched {fetched.Name}");
Shows the complete generated-client call flow, including construction, creating a fruit, fetching it, and printing results. section 11.4.3
