generating-dotnet-sdks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Generating .NET SDKs from OpenAPI Specs with AutoSDK

使用AutoSDK从OpenAPI规范生成.NET SDK

Overview

概述

AutoSDK is a .NET CLI tool and Roslyn source generator that produces production-quality C# SDKs from OpenAPI specifications. Generated SDKs include:
  • Fully typed C# clients with async methods and CancellationToken support
  • System.Text.Json serialization (no reflection, NativeAOT/trimming compatible)
  • Nullable reference types enabled
  • Support for OneOf/AnyOf/AllOf schemas
  • Server-Sent Events (SSE) streaming via
    application/x-ndjson
  • Enum serialization for System.Text.Json
  • Polyfills for .NET Framework / .NET Standard targets
  • Strong-named assemblies
AutoSDK is used in 30+ real SDKs (OpenAI, Anthropic, Ollama, HuggingFace, etc.) and tested against OpenAPI specs up to 220k lines.
AutoSDK是一款.NET CLI工具和Roslyn源代码生成器,可从OpenAPI规范生成生产级别的C# SDK。生成的SDK包含以下特性:
  • 带有异步方法和CancellationToken支持的完全类型化C#客户端
  • System.Text.Json序列化(无反射,兼容NativeAOT/代码裁剪)
  • 启用可为空引用类型
  • 支持OneOf/AnyOf/AllOf模式
  • 通过
    application/x-ndjson
    实现Server-Sent Events (SSE)流
  • System.Text.Json的枚举序列化
  • .NET Framework/.NET Standard目标的兼容补丁
  • 强名称程序集
AutoSDK已应用于30多个真实SDK(如OpenAI、Anthropic、Ollama、HuggingFace等),并针对多达22万行的OpenAPI规范进行了测试。

Quick Start Workflow

快速开始流程

Step 1: Install the CLI tool

步骤1:安装CLI工具

bash
dotnet tool install --global autosdk.cli --prerelease
bash
dotnet tool install --global autosdk.cli --prerelease

Step 2: Obtain the OpenAPI specification

步骤2:获取OpenAPI规范

Either download it or point to a local file:
bash
undefined
可以下载规范文件或使用本地文件:
bash
undefined

Download from URL

从URL下载

Or use a local file

或使用本地文件

ls openapi.yaml

AutoSDK accepts both YAML and JSON formats. It supports OpenAPI 3.0 and 3.1 specs (3.1 is internally converted to 3.0).
ls openapi.yaml

AutoSDK支持YAML和JSON格式,兼容OpenAPI 3.0和3.1规范(3.1会在内部转换为3.0)。

Step 3: Generate the SDK

步骤3:生成SDK

bash
rm -rf Generated
autosdk generate openapi.yaml \
  --namespace MyCompany.MyApi \
  --clientClassName MyApiClient \
  --targetFramework net8.0 \
  --output Generated
This creates a
Generated/
directory containing all C# source files.
bash
rm -rf Generated
autosdk generate openapi.yaml \
  --namespace MyCompany.MyApi \
  --clientClassName MyApiClient \
  --targetFramework net8.0 \
  --output Generated
此命令会创建一个
Generated/
目录,包含所有C#源文件。

Step 4: Build and verify

步骤4:构建并验证

bash
dotnet build
The generated code compiles as part of any .NET project that includes the
Generated/
directory.
bash
dotnet build
生成的代码会作为包含
Generated/
目录的任何.NET项目的一部分进行编译。

CLI Commands

CLI命令

autosdk generate <input>

autosdk generate <input>

Main command. Generates a C# SDK from an OpenAPI spec file or URL.
bash
autosdk generate openapi.yaml \
  --namespace Anthropic \
  --clientClassName AnthropicClient \
  --targetFramework net8.0 \
  --output Generated \
  --exclude-deprecated-operations
Key options:
OptionAliasDefaultDescription
--output
-o
Generated
Output directory for generated files
--targetFramework
-t
net10.0
Target framework (e.g.,
net8.0
,
netstandard2.0
)
--namespace
-n
Derived from filenameC# namespace for generated code
--clientClassName
-c
Derived from filenameName of the generated client class
--methodNamingConvention
-m
SimpleOperationId
How method names are derived
--single-file
-s
false
Output all code in a single .cs file
--exclude-deprecated-operations
-e
false
Skip deprecated API operations
--ignore-openapi-errors
true
Continue generation despite spec errors
--validation
false
Generate model validation methods
--compute-discriminators
false
Compute discriminators for polymorphic models
--generate-cli
false
Generate a CLI wrapper for the client
--security-scheme
(none)Inject auth scheme as
Type:Location:Name
(repeatable)
--base-url
(none)Server base URL to inject for specs missing
servers
See CLI-REFERENCE.md for the complete option reference.
主命令,从OpenAPI规范文件或URL生成C# SDK。
bash
autosdk generate openapi.yaml \
  --namespace Anthropic \
  --clientClassName AnthropicClient \
  --targetFramework net8.0 \
  --output Generated \
  --exclude-deprecated-operations
关键选项:
选项别名默认值描述
--output
-o
Generated
生成文件的输出目录
--targetFramework
-t
net10.0
目标框架(例如:
net8.0
netstandard2.0
--namespace
-n
从文件名派生生成代码的C#命名空间
--clientClassName
-c
从文件名派生生成的客户端类名称
--methodNamingConvention
-m
SimpleOperationId
方法名称的派生规则
--single-file
-s
false
将所有代码输出到单个.cs文件
--exclude-deprecated-operations
-e
false
跳过已废弃的API操作
--ignore-openapi-errors
true
即使规范存在错误也继续生成
--validation
false
生成模型验证方法
--compute-discriminators
false
为多态模型计算鉴别器
--generate-cli
false
为客户端生成CLI包装器
--security-scheme
注入认证方案,格式为
Type:Location:Name
(可重复使用)
--base-url
为缺少
servers
字段的规范注入服务器基础URL
完整选项参考请查看CLI-REFERENCE.md

autosdk init <solution-name> <client-name> <openapi-spec> <company>

autosdk init <solution-name> <client-name> <openapi-spec> <company>

Scaffolds a complete SDK project with solution file, CI workflows, tests, and docs.
bash
autosdk init MyApi MyApiClient https://example.com/openapi.yaml MyCompany
This creates a full project structure including:
  • Solution file (
    .slnx
    )
  • GitHub Actions workflows (CI, auto-update, auto-merge, MkDocs)
  • Integration test project
  • TrimmingHelper for NativeAOT validation
  • generate.sh
    regeneration script
  • README.md
    ,
    LICENSE
    ,
    .gitignore
Options:
--output
/
-o
,
--add-mkdocs
/
-m
(default: true),
--add-tests
/
-t
(default: true).
搭建完整的SDK项目,包含解决方案文件、CI工作流、测试和文档。
bash
autosdk init MyApi MyApiClient https://example.com/openapi.yaml MyCompany
此命令会创建完整的项目结构,包括:
  • 解决方案文件(
    .slnx
  • GitHub Actions工作流(CI、自动更新、自动合并、MkDocs)
  • 集成测试项目
  • 用于NativeAOT验证的TrimmingHelper
  • 重新生成脚本
    generate.sh
  • README.md
    LICENSE
    .gitignore
选项:
--output
/
-o
--add-mkdocs
/
-m
(默认值:true)、
--add-tests
/
-t
(默认值:true)。

autosdk http <input>

autosdk http <input>

Generates
.http
files from an OpenAPI spec for API testing.
bash
autosdk http openapi.yaml --output Testing
从OpenAPI规范生成
.http
文件用于API测试。
bash
autosdk http openapi.yaml --output Testing

Project Structure Convention

项目结构约定

AutoSDK-based SDK projects follow a standard layout:
MyApi/
├── MyApi.sln
├── src/
│   ├── libs/MyApi/
│   │   ├── MyApi.csproj
│   │   ├── openapi.yaml              # Source OpenAPI spec
│   │   ├── generate.sh               # Regeneration script
│   │   ├── Generated/                # AUTO-GENERATED -- never edit
│   │   │   ├── MyApiClient.g.cs
│   │   │   ├── Models/*.g.cs
│   │   │   └── ...
│   │   └── *.cs                      # Hand-written extensions
│   ├── tests/IntegrationTests/
│   └── helpers/
│       ├── GenerateDocs/              # Doc generation
│       └── TrimmingHelper/            # NativeAOT validation
└── .github/workflows/
    └── auto-update.yml
Critical rule: Never manually edit files in
Generated/
directories. They are overwritten on regeneration. Place customizations in partial classes outside
Generated/
.
基于AutoSDK的SDK项目遵循标准布局:
MyApi/
├── MyApi.sln
├── src/
│   ├── libs/MyApi/
│   │   ├── MyApi.csproj
│   │   ├── openapi.yaml              # 源OpenAPI规范
│   │   ├── generate.sh               # 重新生成脚本
│   │   ├── Generated/                # 自动生成 -- 请勿手动编辑
│   │   │   ├── MyApiClient.g.cs
│   │   │   ├── Models/*.g.cs
│   │   │   └── ...
│   │   └── *.cs                      # 手写扩展代码
│   ├── tests/IntegrationTests/
│   └── helpers/
│       ├── GenerateDocs/              # 文档生成
│       └── TrimmingHelper/            # NativeAOT验证
└── .github/workflows/
    └── auto-update.yml
重要规则: 请勿手动编辑
Generated/
目录下的文件,它们会在重新生成时被覆盖。将自定义代码放在
Generated/
目录外的分部类中。

The generate.sh Pattern

generate.sh模式

Every SDK includes a
generate.sh
script that automates the full regeneration pipeline. Here is a real-world example (from the Anthropic SDK):
bash
dotnet tool install --global autosdk.cli --prerelease
rm -rf Generated
curl -o openapi.yaml https://example.com/openapi.yaml
autosdk generate openapi.yaml \
  --namespace Anthropic \
  --clientClassName AnthropicClient \
  --targetFramework net8.0 \
  --output Generated \
  --exclude-deprecated-operations
The pipeline: install CLI -> download spec -> optionally patch the spec inline in
generate.sh
-> generate.
If the spec lacks authentication definitions (no
securitySchemes
), use
--security-scheme
instead of patching the spec manually:
bash
autosdk generate openapi.yaml \
  --namespace Anthropic \
  --clientClassName AnthropicClient \
  --targetFramework net8.0 \
  --output Generated \
  --security-scheme "ApiKey:Header:x-api-key"
If the spec is missing a
servers
field, use
--base-url
to inject the base URL:
bash
autosdk generate openapi.yaml \
  --namespace ElevenLabs \
  --clientClassName ElevenLabsClient \
  --targetFramework net8.0 \
  --output Generated \
  --base-url "https://api.elevenlabs.io"
每个SDK都包含一个
generate.sh
脚本,用于自动化完整的重新生成流程。以下是一个真实场景的示例(来自Anthropic SDK):
bash
dotnet tool install --global autosdk.cli --prerelease
rm -rf Generated
curl -o openapi.yaml https://example.com/openapi.yaml
autosdk generate openapi.yaml \
  --namespace Anthropic \
  --clientClassName AnthropicClient \
  --targetFramework net8.0 \
  --output Generated \
  --exclude-deprecated-operations
流程:安装CLI -> 下载规范 -> 可选地在
generate.sh
中使用
jq
yq
sed
perl
在线修改规范 -> 生成。
如果规范缺少认证定义(无
securitySchemes
),请使用
--security-scheme
代替手动修改规范:
bash
autosdk generate openapi.yaml \
  --namespace Anthropic \
  --clientClassName AnthropicClient \
  --targetFramework net8.0 \
  --output Generated \
  --security-scheme "ApiKey:Header:x-api-key"
如果规范缺少
servers
字段,请使用
--base-url
注入基础URL:
bash
autosdk generate openapi.yaml \
  --namespace ElevenLabs \
  --clientClassName ElevenLabsClient \
  --targetFramework net8.0 \
  --output Generated \
  --base-url "https://api.elevenlabs.io"

Post-Generation Customization

生成后自定义

Generated clients are partial classes, enabling extension without modifying generated code:
生成的客户端是分部类,无需修改生成代码即可进行扩展:

Client Hooks

客户端钩子

Generated clients expose partial method hooks you can override:
csharp
public partial class MyApiClient
{
    partial void PrepareArguments(/* modify parameters before request */);
    partial void PrepareRequest(HttpClient client, HttpRequestMessage request);
    partial void ProcessResponse(HttpClient client, HttpResponseMessage response);
    partial void ProcessResponseContent(HttpClient client, HttpResponseMessage response, ref string content);
}
生成的客户端公开了可重写的分部方法钩子:
csharp
public partial class MyApiClient
{
    partial void PrepareArguments(/* 在请求前修改参数 */);
    partial void PrepareRequest(HttpClient client, HttpRequestMessage request);
    partial void ProcessResponse(HttpClient client, HttpResponseMessage response);
    partial void ProcessResponseContent(HttpClient client, HttpResponseMessage response, ref string content);
}

Extension Files

扩展文件

Place hand-written code alongside
Generated/
(not inside it):
  • MyApiClient.Streaming.cs
    -- SSE/streaming extensions
  • MyApiClient.AdditionalConstructors.cs
    -- extra constructor overloads
  • JsonSerializerContextTypes.AdditionalTypes.cs
    -- extra types for JSON source gen
  • Extensions/
    -- helper extension methods
See CUSTOMIZATION-PATTERNS.md for detailed patterns.
将手写代码放在
Generated/
目录旁边(而非内部):
  • MyApiClient.Streaming.cs
    -- SSE/流扩展
  • MyApiClient.AdditionalConstructors.cs
    -- 额外的构造函数重载
  • JsonSerializerContextTypes.AdditionalTypes.cs
    -- JSON源代码生成的额外类型
  • Extensions/
    -- 辅助扩展方法
详细模式请查看CUSTOMIZATION-PATTERNS.md

Configuration Options

配置选项

The
generate
command's most important configuration flags:
FlagPurposeWhen to use
--targetFramework net8.0
Set target frameworkAlways set explicitly for your project
--namespace X
Set C# namespaceAlways set to match your project namespace
--clientClassName X
Set client class nameAlways set to a descriptive name
--exclude-deprecated-operations
Skip deprecated endpointsMost production SDKs
--ignore-openapi-errors
Tolerate spec issuesSpecs with minor validation errors
--single-file
One output fileSmaller APIs or embedding in existing projects
--compute-discriminators
Polymorphic model supportAPIs with oneOf/anyOf discriminators
--validation
Model validation methodsWhen input validation is needed
--generate-cli
Generate CLI wrapperWhen you want a CLI for the API
--methodNamingConvention
Method name style
SimpleOperationId
(default),
MethodAndPath
,
OperationIdWithDots
--security-scheme
Inject auth for specs missing
securitySchemes
ApiKey:Header:x-api-key
,
Http:Header:Bearer
(repeatable)
generate
命令最重要的配置标志:
标志用途使用场景
--targetFramework net8.0
设置目标框架始终为你的项目显式设置
--namespace X
设置C#命名空间始终设置为与项目命名空间匹配
--clientClassName X
设置客户端类名称始终设置为描述性名称
--exclude-deprecated-operations
跳过已废弃的端点大多数生产SDK
--ignore-openapi-errors
容忍规范问题存在轻微验证错误的规范
--single-file
单个输出文件较小的API或嵌入现有项目
--compute-discriminators
多态模型支持包含oneOf/anyOf鉴别器的API
--validation
模型验证方法需要输入验证时
--generate-cli
生成CLI包装器需要为API创建CLI时
--methodNamingConvention
方法名称风格
SimpleOperationId
(默认)、
MethodAndPath
OperationIdWithDots
--security-scheme
为缺少
securitySchemes
的规范注入认证
ApiKey:Header:x-api-key
Http:Header:Bearer
(可重复使用)

Troubleshooting

故障排除

Common issues and solutions:
  • "Could not find part of the path" -- Enable Windows long paths in registry
  • Malformed or incomplete specs -- Patch the downloaded spec inline in
    generate.sh
    with
    jq
    ,
    yq
    ,
    sed
    , or
    perl
    before generation
  • Missing operations -- Check that operationIds exist in the spec; use
    --ignore-openapi-errors
    if needed
  • Naming collisions -- AutoSDK resolves these automatically via suffixes
  • No auth constructors generated -- Spec is missing
    securitySchemes
    ; use
    --security-scheme "ApiKey:Header:x-api-key"
    to inject auth
See TROUBLESHOOTING.md for the complete troubleshooting guide.
常见问题及解决方案:
  • "找不到路径的一部分" -- 在注册表中启用Windows长路径
  • 格式错误或不完整的规范 -- 在
    generate.sh
    中使用
    jq
    yq
    sed
    perl
    在生成前在线修改下载的规范
  • 缺少操作 -- 检查规范中是否存在operationIds;必要时使用
    --ignore-openapi-errors
  • 命名冲突 -- AutoSDK会自动通过后缀解决冲突
  • 未生成认证构造函数 -- 规范缺少
    securitySchemes
    ;使用
    --security-scheme "ApiKey:Header:x-api-key"
    注入认证
完整故障排除指南请查看TROUBLESHOOTING.md