liveBook · Manning

Generated client

As explained in ASP.NET Core in Action, 3e

Client code generation is the automatic production of source code for calling an API from an API description.

A generated client is source code produced from an API description for calling that API. Given an OpenAPI document, NSwag can generate a C# client and the types needed to exchange data with the API. The generated code handles paths, parameter substitution, serialization, deserialization, and error status checks, reducing the boilerplate callers must write. section 11.4.3 section 11.7

The quality of the OpenAPI description affects the client. For example, an endpoint’s OperationID becomes its generated method name. If it is missing, NSwag chooses a name that may be awkward; calling WithName() on the endpoint supplies an OperationID. section 11.4.3 section 11.7

To add a generated C# client to a project:

  • Run the API and find the URL of its OpenAPI JSON document. section 11.4.1
  • In Visual Studio, choose Add > Service Reference on the client project, select OpenAPI, and enter the document URL, namespace, and client class name. Alternatively, use the .NET OpenAPI tool to add the URL and set the namespace and class name in the project’s OpenApiReference element. section 11.4.1 section 11.4.2
  • Update the added packages as needed, then build the project. NSwag reads the downloaded description and generates the client; the generated file is typically in the project’s obj folder. section 11.4.1 section 11.4.3

Call an API

For a fruit API, create FruitClient with the API base address and an HttpClient. Call FruitPOSTAsync to create a fruit and FruitGETAsync to fetch it. The generated methods handle the HTTP details and return the generated fruit type. 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}");

See the client construction and create-and-fetch calls in C#. section 11.4.3

Customize generation with an Options element inside OpenApiReference. Options can select System.Text.Json instead of the default Newtonsoft.Json, generate an interface for test substitutes, or use HttpClient.BaseAddress instead of a separate base-address constructor argument. The generated class is also partial, so additional behavior can live in a separate partial class. section 11.4.4

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.

See the project settings for these three generator options. section 11.4.4

When the API description changes, refresh the downloaded document through Visual Studio or the .NET OpenAPI tool, then rebuild. The regenerated client reflects changes such as new operation IDs. section 11.4.5

How ASP.NET Core in Action, 3e covers it

How deep it goes
Walks through setup, generated code use, customization, and regeneration after description changes.
Examples
Uses a fruit API to demonstrate creating and fetching a fruit with a generated C# client.
What it assumes
Requires a client project and an accessible OpenAPI document from a running API for the demonstrated setup.
What you can do after
Apply it via NSwag to generate, customize, use, and refresh a C# API client.
How it connects
Connects client generation to OpenAPI, endpoint metadata, serialization, dependency injection, and interfaces for testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.