or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

annotations.mdaspnetcore-integration.mdcli-commands.mdcore-document-model.mdcsharp-client-generation.mddocument-generation.mdindex.mdtypescript-client-generation.md
tile.json

cli-commands.mddocs/

CLI Commands

NSwag provides a comprehensive command-line interface for automating OpenAPI document generation and client code generation. The CLI commands can be used in build scripts, CI/CD pipelines, and development workflows.

Core Command Classes

Base Command Classes

public abstract class OutputCommandBase : IOutputCommand
{
    public string Output { get; set; }
    public virtual Task<object> RunAsync();
}

public abstract class CodeGeneratorCommandBase : OutputCommandBase
{
    public virtual Task<object> RunAsync();
}

public abstract class OpenApiToCSharpCommandBase : CodeGeneratorCommandBase
{
    public string Input { get; set; }
    public CSharpGeneratorSettings Settings { get; set; }
}

Client Generation Commands

OpenApiToCSharpClientCommand

Generates C# client code from an OpenAPI specification.

public class OpenApiToCSharpClientCommand : OpenApiToCSharpCommandBase
{
    public CSharpClientGeneratorSettings Settings { get; set; }
    public string Input { get; set; }
    public string Output { get; set; }
    
    public override async Task<object> RunAsync();
}

Usage Example

# Command line usage
nswag openapi2csclient /input:swagger.json /output:ApiClient.cs /namespace:MyApp.Clients /className:ApiClient

# Configuration file usage
nswag run nswag.json

Configuration File Example

{
  "runtime": "Net60",
  "defaultVariables": null,
  "documentGenerator": {
    "fromDocument": {
      "url": "https://api.example.com/swagger.json",
      "output": null
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": null,
      "configurationClass": null,
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": true,
      "protectedMethods": [],
      "generateExceptionClasses": true,
      "exceptionClass": "ApiException",
      "wrapDtoExceptions": true,
      "useHttpClientCreationMethod": false,
      "httpClientType": "System.Net.Http.HttpClient",
      "useHttpRequestMessageCreationMethod": false,
      "useBaseUrl": true,
      "generateBaseUrlProperty": true,
      "generateSyncMethods": false,
      "generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
      "exposeJsonSerializerSettings": false,
      "clientClassAccessModifier": "public",
      "typeAccessModifier": "public",
      "generateContractsOutput": false,
      "contractsNamespace": null,
      "contractsOutputFilePath": null,
      "parameterDateTimeFormat": "s",
      "parameterDateFormat": "yyyy-MM-dd",
      "generateUpdateJsonSerializerSettingsMethod": true,
      "useRequestAndResponseSerializationAttribute": false,
      "serializeTypeInformation": false,
      "queryNullValue": "",
      "className": "ApiClient",
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "additionalNamespaceUsages": [],
      "additionalContractNamespaceUsages": [],
      "generateOptionalParameters": false,
      "generateJsonMethods": false,
      "enforceFlagEnums": false,
      "parameterArrayType": "System.Collections.Generic.IEnumerable",
      "parameterDictionaryType": "System.Collections.Generic.IDictionary",
      "responseArrayType": "System.Collections.Generic.ICollection",
      "responseDictionaryType": "System.Collections.Generic.IDictionary",
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "namespace": "MyApp.Clients",
      "requiredPropertiesMustBeDefined": true,
      "dateType": "System.DateTimeOffset",
      "jsonConverters": null,
      "anyType": "object",
      "dateTimeType": "System.DateTimeOffset",
      "timeType": "System.TimeSpan",
      "timeSpanType": "System.TimeSpan",
      "arrayType": "System.Collections.Generic.ICollection",
      "arrayInstanceType": "System.Collections.ObjectModel.Collection",
      "dictionaryType": "System.Collections.Generic.IDictionary",
      "dictionaryInstanceType": "System.Collections.Generic.Dictionary",
      "arrayBaseType": "System.Collections.ObjectModel.Collection",
      "dictionaryBaseType": "System.Collections.Generic.Dictionary",
      "classStyle": "Inpc",
      "jsonLibrary": "NewtonsoftJson",
      "generateDefaultValues": true,
      "generateDataAnnotations": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateImmutableArrayProperties": false,
      "generateImmutableDictionaryProperties": false,
      "jsonSerializerSettingsTransformationMethod": null,
      "inlineNamedArrays": false,
      "inlineNamedDictionaries": false,
      "inlineNamedTuples": true,
      "inlineNamedAny": false,
      "generateDtoTypes": true,
      "generateOptionalPropertiesAsNullable": false,
      "generateNullableReferenceTypes": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "ApiClient.cs"
    }
  }
}

OpenApiToCSharpControllerCommand

Generates C# controller code from an OpenAPI specification.

public class OpenApiToCSharpControllerCommand : OpenApiToCSharpCommandBase
{
    public CSharpControllerGeneratorSettings Settings { get; set; }
    public string Input { get; set; }
    public string Output { get; set; }
    
    public override async Task<object> RunAsync();
}

OpenApiToTypeScriptClientCommand

Generates TypeScript client code from an OpenAPI specification.

public class OpenApiToTypeScriptClientCommand : CodeGeneratorCommandBase
{
    public TypeScriptClientGeneratorSettings Settings { get; set; }
    public string Input { get; set; }
    public string Output { get; set; }
    
    public override async Task<object> RunAsync();
}

Command Line Usage

# Generate TypeScript client
nswag openapi2tsclient /input:swagger.json /output:api-client.ts /template:Angular

# With additional options
nswag openapi2tsclient /input:swagger.json /output:api-client.ts /template:Angular /className:ApiClient /generateClientInterfaces:true

Document Generation Commands

AspNetCoreToOpenApiCommand

Generates OpenAPI specification from an ASP.NET Core application.

public class AspNetCoreToOpenApiCommand : OutputCommandBase
{
    public string Project { get; set; }
    public string MSBuildProjectExtensionsPath { get; set; }
    public string Configuration { get; set; }
    public string Runtime { get; set; }
    public string TargetFramework { get; set; }
    public bool NoBuild { get; set; }
    public bool Verbose { get; set; }
    public string WorkingDirectory { get; set; }
    public AspNetCoreOpenApiDocumentGeneratorSettings Settings { get; set; }
    
    public override async Task<object> RunAsync();
}

Usage Example

# Generate OpenAPI from ASP.NET Core project
nswag aspnetcore2openapi --project MyWebApi.csproj --output swagger.json

# With additional settings
nswag aspnetcore2openapi --project MyWebApi.csproj --output swagger.json --configuration Release --verbose

WebApiToOpenApiCommand

Generates OpenAPI specification from an ASP.NET Web API application.

public class WebApiToOpenApiCommand : OutputCommandBase
{
    public string[] AssemblyPaths { get; set; }
    public string[] AssemblyConfig { get; set; }
    public string[] ReferencePaths { get; set; }
    public WebApiOpenApiDocumentGeneratorSettings Settings { get; set; }
    
    public override async Task<object> RunAsync();
}

AssemblyTypeToSwaggerCommand

Generates OpenAPI specification from .NET assembly types.

public class AssemblyTypeToSwaggerCommand : OutputCommandBase
{
    public string AssemblyPath { get; set; }
    public string[] ClassNames { get; set; }
    public string AssemblyConfig { get; set; }
    public string[] ReferencePaths { get; set; }
    
    public override async Task<object> RunAsync();
}

Schema Generation Commands

JsonSchemaToCSharpCommand

Generates C# classes from JSON Schema.

public class JsonSchemaToCSharpCommand : OutputCommandBase
{
    public string Input { get; set; }
    public string Output { get; set; }
    public CSharpGeneratorSettings Settings { get; set; }
    
    public override async Task<object> RunAsync();
}

JsonSchemaToTypeScriptCommand

Generates TypeScript types from JSON Schema.

public class JsonSchemaToTypeScriptCommand : OutputCommandBase
{
    public string Input { get; set; }
    public string Output { get; set; }
    public TypeScriptGeneratorSettings Settings { get; set; }
    
    public override async Task<object> RunAsync();
}

Configuration and Execution

Command Configuration

Commands can be configured through:

  1. Command line arguments
  2. Configuration files (JSON)
  3. Programmatic configuration

Programmatic Configuration Example

var command = new OpenApiToCSharpClientCommand
{
    Input = "https://api.example.com/swagger.json",
    Output = "ApiClient.cs",
    Settings = new CSharpClientGeneratorSettings
    {
        ClassName = "MyApiClient",
        Namespace = "MyApp.Clients",
        GenerateClientInterfaces = true,
        InjectHttpClient = true
    }
};

var result = await command.RunAsync();

Command Execution in Code

// Execute command programmatically
public async Task GenerateClient()
{
    var command = new OpenApiToCSharpClientCommand
    {
        Input = "swagger.json",
        Output = "Generated/ApiClient.cs",
        Settings = new CSharpClientGeneratorSettings
        {
            ClassName = "ApiClient",
            Namespace = "MyApp.Generated",
            GenerateClientInterfaces = true,
            InjectHttpClient = true,
            JsonLibrary = CSharpJsonLibrary.SystemTextJson
        }
    };

    try
    {
        await command.RunAsync();
        Console.WriteLine("Client generated successfully!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Generation failed: {ex.Message}");
    }
}

Build Integration

MSBuild Integration

NSwag commands can be integrated into MSBuild for automatic generation during build.

Project File Configuration

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NSwag.MSBuild" Version="13.20.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <Target Name="NSwag" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Debug'">
    <Exec Command="$(NSwagExe_Net60) run nswag.json" ContinueOnError="true" />
  </Target>

</Project>

CI/CD Integration

GitHub Actions Example

name: Generate API Clients

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  generate-clients:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 6.0.x
        
    - name: Install NSwag CLI
      run: dotnet tool install --global NSwag.ConsoleCore
      
    - name: Generate C# Client
      run: nswag openapi2csclient /input:swagger.json /output:src/ApiClient.cs /namespace:MyApp.Clients
      
    - name: Generate TypeScript Client
      run: nswag openapi2tsclient /input:swagger.json /output:src/api-client.ts /template:Angular
      
    - name: Commit generated files
      uses: stefanzweifel/git-auto-commit-action@v4
      with:
        commit_message: Update generated API clients
        file_pattern: src/ApiClient.cs src/api-client.ts

Azure DevOps Pipeline Example

trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

variables:
  buildConfiguration: 'Release'

steps:
- task: UseDotNet@2
  displayName: 'Use .NET 6.0'
  inputs:
    packageType: 'sdk'
    version: '6.0.x'

- task: DotNetCoreCLI@2
  displayName: 'Install NSwag CLI'
  inputs:
    command: 'custom'
    custom: 'tool'
    arguments: 'install --global NSwag.ConsoleCore'

- script: |
    nswag aspnetcore2openapi --project src/MyWebApi/MyWebApi.csproj --output swagger.json
    nswag openapi2csclient --input swagger.json --output src/MyClient/ApiClient.cs --namespace MyApp.Clients
  displayName: 'Generate API Client'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Generated Files'
  inputs:
    pathToPublish: 'src/MyClient'
    artifactName: 'generated-clients'

Advanced Command Usage

Batch Processing

# Generate multiple clients from the same spec
nswag openapi2csclient /input:swagger.json /output:CSharpClient.cs /namespace:MyApp.CSharp
nswag openapi2tsclient /input:swagger.json /output:TypeScriptClient.ts /template:Angular

# Process multiple OpenAPI specifications
for file in specs/*.json; do
  nswag openapi2csclient /input:"$file" /output:"clients/$(basename "$file" .json)Client.cs"
done

Environment-Specific Generation

# Development environment
nswag run nswag.dev.json

# Production environment  
nswag run nswag.prod.json

# Using environment variables
export API_BASE_URL=https://api.example.com
nswag openapi2csclient /input:${API_BASE_URL}/swagger.json /output:ApiClient.cs

Custom Templates and Processing

Commands support custom templates and post-processing for advanced scenarios:

var command = new OpenApiToCSharpClientCommand
{
    Input = "swagger.json",
    Output = "ApiClient.cs",
    Settings = new CSharpClientGeneratorSettings
    {
        ClassName = "ApiClient",
        Namespace = "MyApp.Clients",
        
        // Custom template directory
        TemplateDirectory = "templates/",
        
        // Post-processing
        CodeGeneratorSettings = 
        {
            PropertyNameGenerator = new CustomPropertyNameGenerator()
        }
    }
};

This comprehensive CLI system enables full automation of OpenAPI workflows, from document generation to client code creation, making it easy to integrate NSwag into any development pipeline or build process.