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.
Basic Usage
Section titled “Basic Usage”The simplest usage takes an input spec and writes the generated code to a file:
openapi-codegen <input> -o <output>From a Local File
Section titled “From a Local File”openapi-codegen petstore.yaml -o Models.csFrom a URL
Section titled “From a URL”The tool can fetch specs directly from URLs — useful for always generating from the latest version:
openapi-codegen https://petstore3.swagger.io/api/v3/openapi.json -o PetStore.csTo stdout
Section titled “To stdout”Omit the output flag to write to stdout. This is useful for piping or previewing:
openapi-codegen spec.yamlSetting the Namespace
Section titled “Setting the Namespace”By default, generated code uses the GeneratedModels namespace. Override it with -n:
openapi-codegen spec.yaml -o Models.cs -n MyApp.Api.ModelsDisabling Features
Section titled “Disabling Features”Toggle individual features off with --no-* flags:
# No XML doc commentsopenapi-codegen spec.yaml -o Models.cs --no-doc-comments
# No auto-generated file headeropenapi-codegen spec.yaml -o Models.cs --no-headerCombine multiple flags:
openapi-codegen spec.yaml -o Models.cs --no-doc-comments --no-headerMutable Collections
Section titled “Mutable Collections”By default, arrays and dictionaries use immutable interfaces. Use mutable types instead:
# 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-dictionariesBuild Integration
Section titled “Build Integration”MSBuild Target
Section titled “MSBuild Target”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>CI/CD Pipeline
Section titled “CI/CD Pipeline”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.ModelsError Handling
Section titled “Error Handling”The tool returns exit code 0 on success and 1 on failure. Error messages are written to stderr:
openapi-codegen nonexistent.yaml -o Models.cs# Error: Input file not found: nonexistent.yamlIf the OpenAPI spec has parsing errors but still contains valid schemas, the tool will generate code from the available schemas and proceed.
Full Reference
Section titled “Full Reference”See the CLI Reference for a complete list of all flags and options.