Skip to content

CLI Usage

The openapi-codegen CLI is the primary way to generate C# code from OpenAPI specifications. This guide covers common usage patterns and workflows.

The simplest usage takes an input spec and writes the generated code to a file:

Terminal window
openapi-codegen <input> -o <output>
Terminal window
openapi-codegen petstore.yaml -o Models.cs

The tool can fetch specs directly from URLs — useful for always generating from the latest version:

Terminal window
openapi-codegen https://petstore3.swagger.io/api/v3/openapi.json -o PetStore.cs

Omit the output flag to write to stdout. This is useful for piping or previewing:

Terminal window
openapi-codegen spec.yaml

By default, generated code uses the GeneratedModels namespace. Override it with -n:

Terminal window
openapi-codegen spec.yaml -o Models.cs -n MyApp.Api.Models

Toggle individual features off with --no-* flags:

Terminal window
# No XML doc comments
openapi-codegen spec.yaml -o Models.cs --no-doc-comments
# No auto-generated file header
openapi-codegen spec.yaml -o Models.cs --no-header

Combine multiple flags:

Terminal window
openapi-codegen spec.yaml -o Models.cs --no-doc-comments --no-header

By default, arrays and dictionaries use immutable interfaces. Use mutable types instead:

Terminal window
# List<T> instead of IReadOnlyList<T>
openapi-codegen spec.yaml -o Models.cs --mutable-arrays
# Dictionary<string, T> instead of IReadOnlyDictionary<string, T>
openapi-codegen spec.yaml -o Models.cs --mutable-dictionaries

Add code generation as a pre-build step in your .csproj:

<Target Name="GenerateApiModels" BeforeTargets="BeforeBuild">
<Exec Command="openapi-codegen $(ProjectDir)specs/api.yaml -o $(ProjectDir)Generated/Models.cs -n $(RootNamespace).Models" />
</Target>

Example for GitHub Actions:

- name: Install OpenAPI Code Generator
run: dotnet tool install --global Nikcio.OpenApiCodeGen
- name: Generate API Models
run: openapi-codegen specs/api.yaml -o src/Models.cs -n MyApp.Models

The tool returns exit code 0 on success and 1 on failure. Error messages are written to stderr:

Terminal window
openapi-codegen nonexistent.yaml -o Models.cs
# Error: Input file not found: nonexistent.yaml

If the OpenAPI spec has parsing errors but still contains valid schemas, the tool will generate code from the available schemas and proceed.

See the CLI Reference for a complete list of all flags and options.