generating-dotnet-sdks
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGenerating .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模式
- 通过实现Server-Sent Events (SSE)流
application/x-ndjson - 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 --prereleasebash
dotnet tool install --global autosdk.cli --prereleaseStep 2: Obtain the OpenAPI specification
步骤2:获取OpenAPI规范
Either download it or point to a local file:
bash
undefined可以下载规范文件或使用本地文件:
bash
undefinedDownload from URL
从URL下载
curl -o openapi.yaml https://example.com/api/openapi.yaml
curl -o openapi.yaml https://example.com/api/openapi.yaml
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 GeneratedThis creates a directory containing all C# source files.
Generated/bash
rm -rf Generated
autosdk generate openapi.yaml \
--namespace MyCompany.MyApi \
--clientClassName MyApiClient \
--targetFramework net8.0 \
--output Generated此命令会创建一个目录,包含所有C#源文件。
Generated/Step 4: Build and verify
步骤4:构建并验证
bash
dotnet buildThe generated code compiles as part of any .NET project that includes the directory.
Generated/bash
dotnet build生成的代码会作为包含目录的任何.NET项目的一部分进行编译。
Generated/CLI Commands
CLI命令
autosdk generate <input>
autosdk generate <input>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-operationsKey options:
| Option | Alias | Default | Description |
|---|---|---|---|
| | | Output directory for generated files |
| | | Target framework (e.g., |
| | Derived from filename | C# namespace for generated code |
| | Derived from filename | Name of the generated client class |
| | | How method names are derived |
| | | Output all code in a single .cs file |
| | | Skip deprecated API operations |
| | Continue generation despite spec errors | |
| | Generate model validation methods | |
| | Compute discriminators for polymorphic models | |
| | Generate a CLI wrapper for the client | |
| (none) | Inject auth scheme as | |
| (none) | Server base URL to inject for specs missing |
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关键选项:
| 选项 | 别名 | 默认值 | 描述 |
|---|---|---|---|
| | | 生成文件的输出目录 |
| | | 目标框架(例如: |
| | 从文件名派生 | 生成代码的C#命名空间 |
| | 从文件名派生 | 生成的客户端类名称 |
| | | 方法名称的派生规则 |
| | | 将所有代码输出到单个.cs文件 |
| | | 跳过已废弃的API操作 |
| | 即使规范存在错误也继续生成 | |
| | 生成模型验证方法 | |
| | 为多态模型计算鉴别器 | |
| | 为客户端生成CLI包装器 | |
| 无 | 注入认证方案,格式为 | |
| 无 | 为缺少 |
完整选项参考请查看CLI-REFERENCE.md。
autosdk init <solution-name> <client-name> <openapi-spec> <company>
autosdk init <solution-name> <client-name> <openapi-spec> <company>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 MyCompanyThis 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
- regeneration script
generate.sh - ,
README.md,LICENSE.gitignore
Options: / , / (default: true), / (default: true).
--output-o--add-mkdocs-m--add-tests-t搭建完整的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
选项: / 、 / (默认值:true)、 / (默认值:true)。
--output-o--add-mkdocs-m--add-tests-tautosdk http <input>
autosdk http <input>autosdk http <input>
autosdk http <input>Generates files from an OpenAPI spec for API testing.
.httpbash
autosdk http openapi.yaml --output Testing从OpenAPI规范生成文件用于API测试。
.httpbash
autosdk http openapi.yaml --output TestingProject 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.ymlCritical rule: Never manually edit files in directories. They are overwritten on regeneration. Place customizations in partial classes outside .
Generated/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 script that automates the full regeneration pipeline. Here is a real-world example (from the Anthropic SDK):
generate.shbash
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-operationsThe pipeline: install CLI -> download spec -> optionally patch the spec inline in -> generate.
generate.shIf the spec lacks authentication definitions (no ), use instead of patching the spec manually:
securitySchemes--security-schemebash
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 field, use to inject the base URL:
servers--base-urlbash
autosdk generate openapi.yaml \
--namespace ElevenLabs \
--clientClassName ElevenLabsClient \
--targetFramework net8.0 \
--output Generated \
--base-url "https://api.elevenlabs.io"每个SDK都包含一个脚本,用于自动化完整的重新生成流程。以下是一个真实场景的示例(来自Anthropic SDK):
generate.shbash
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.shjqyqsedperl如果规范缺少认证定义(无),请使用代替手动修改规范:
securitySchemes--security-schemebash
autosdk generate openapi.yaml \
--namespace Anthropic \
--clientClassName AnthropicClient \
--targetFramework net8.0 \
--output Generated \
--security-scheme "ApiKey:Header:x-api-key"如果规范缺少字段,请使用注入基础URL:
servers--base-urlbash
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 (not inside it):
Generated/- -- SSE/streaming extensions
MyApiClient.Streaming.cs - -- extra constructor overloads
MyApiClient.AdditionalConstructors.cs - -- extra types for JSON source gen
JsonSerializerContextTypes.AdditionalTypes.cs - -- helper extension methods
Extensions/
See CUSTOMIZATION-PATTERNS.md for detailed patterns.
将手写代码放在目录旁边(而非内部):
Generated/- -- SSE/流扩展
MyApiClient.Streaming.cs - -- 额外的构造函数重载
MyApiClient.AdditionalConstructors.cs - -- JSON源代码生成的额外类型
JsonSerializerContextTypes.AdditionalTypes.cs - -- 辅助扩展方法
Extensions/
详细模式请查看CUSTOMIZATION-PATTERNS.md。
Configuration Options
配置选项
The command's most important configuration flags:
generate| Flag | Purpose | When to use |
|---|---|---|
| Set target framework | Always set explicitly for your project |
| Set C# namespace | Always set to match your project namespace |
| Set client class name | Always set to a descriptive name |
| Skip deprecated endpoints | Most production SDKs |
| Tolerate spec issues | Specs with minor validation errors |
| One output file | Smaller APIs or embedding in existing projects |
| Polymorphic model support | APIs with oneOf/anyOf discriminators |
| Model validation methods | When input validation is needed |
| Generate CLI wrapper | When you want a CLI for the API |
| Method name style | |
| Inject auth for specs missing | |
generate| 标志 | 用途 | 使用场景 |
|---|---|---|
| 设置目标框架 | 始终为你的项目显式设置 |
| 设置C#命名空间 | 始终设置为与项目命名空间匹配 |
| 设置客户端类名称 | 始终设置为描述性名称 |
| 跳过已废弃的端点 | 大多数生产SDK |
| 容忍规范问题 | 存在轻微验证错误的规范 |
| 单个输出文件 | 较小的API或嵌入现有项目 |
| 多态模型支持 | 包含oneOf/anyOf鉴别器的API |
| 模型验证方法 | 需要输入验证时 |
| 生成CLI包装器 | 需要为API创建CLI时 |
| 方法名称风格 | |
| 为缺少 | |
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 with
generate.sh,jq,yq, orsedbefore generationperl - Missing operations -- Check that operationIds exist in the spec; use if needed
--ignore-openapi-errors - Naming collisions -- AutoSDK resolves these automatically via suffixes
- No auth constructors generated -- Spec is missing ; use
securitySchemesto inject auth--security-scheme "ApiKey:Header:x-api-key"
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。