关于 designing-sdks
为 SDK 架构师和开发者提供客户端库设计指导,涵盖 API 组织、认证、错误处理与版本管理。内容包括 TypeScript、Python 和 Go 的模式及代码示例。
主要功能
- 01资源式与命令式架构
- 02多语言客户端模式
- 03认证与令牌刷新
- 04重试、退避与错误处理
- 05自动及手动分页
- 06流式 API 与版本管理
适用场景
- 01为 REST API 设计客户端库
- 02加入瞬时错误重试和速率限制处理
- 03实现分页、认证和流式数据接口
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ancoleman/ ai-design-components --skill designing-sdks安装后在 Claude Code 中输入/designing-sdks确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
outputs.yamlexamples/go/basic-client.gochannel-pagination.gocontext-client.goexamples/python/async-client.pydual-client.pysync-client.pyexamples/typescript/advanced-client.tsbasic-client.tsresource-based.tsreferences/architecture-patterns.mdauthentication.mderror-handling.mdpagination.mdretry-backoff.mdtesting-sdks.mdversioning.md详细介绍
SDK 设计
通过直观的 API、稳健的错误处理、自动重试以及跨编程语言的一致模式,设计出开发者体验出色的客户端库(SDK)。
何时使用此技能
在构建 REST API 的客户端库、创建内部服务 SDK、实现指数退避重试逻辑、处理身份验证模式、创建类型化错误层级、通过异步迭代器实现分页,或设计用于实时数据的流式 API 时使用。
核心架构模式
客户端 → 资源 → 方法
按层级组织 SDK 代码:
Client (config: API key, base URL, retries, timeout)
├─ Resources (users, payments, posts)
│ ├─ create(), retrieve(), update(), delete()
│ └─ list() (with pagination)
└─ Top-Level Methods (convenience)
基于资源(Stripe 风格):
const client = new APIClient({ apiKey: 'sk_test_...' })
const user = await client.users.create({ email: '[email protected]' })
适用于方法少于 100 个的 API。优先考虑开发者体验。
基于命令(AWS SDK v3):
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'
await client.send(new PutObjectCommand({ Bucket: '...' }))
适用于方法多于 100 个的 API。优先考虑包体积和摇树优化。
如需详细的架构指南,请参阅 references/architecture-patterns.md。
特定语言的模式
TypeScript:仅异步
const user = await client.users.create({ email: '[email protected]' })
所有方法都返回 Promise。避免使用回调。
Python:同步/异步双模式
# Sync
client = APIClient(api_key='sk_test_...')
user = client.users.create(email='[email protected]')
# Async
async_client = AsyncAPIClient(api_key='sk_test_...')
user = await async_client.users.create(email='[email protected]')
提供两种客户端。用户可根据架构选择。
Go:带上下文的同步模式
client := apiclient.New("api_key")
user, err := client.Users().Create(ctx, req)
使用 context.Context 进行超时控制和取消操作。
身份验证
API 密钥(最常见)
const client = new APIClient({ apiKey: process.env.API_KEY })
将密钥存储在环境变量中,绝不要硬编码。
OAuth 令牌刷新
const client = new APIClient({
clientId: 'id',
clientSecret: 'secret',
refreshToken: 'token',
onTokenRefresh: (newToken) => saveToken(newToken)
})
SDK 会在令牌过期前自动刷新令牌。
每个请求使用持有者令牌
await client.users.list({
headers: { Authorization: `Bearer ${userToken}` }
})
适用于多租户应用程序。
OAuth 流程、JWT 处理和凭据提供程序,请参阅 references/authentication.md。
重试与退避
带抖动的指数退避
async function retryWithBackoff<T>(fn: () => Promise<T>, maxRetries: number): Promise<T> {
let attempt = 0
while (attempt <= maxRetries) {
try {
return await fn()
} catch (error) {
attempt++
if (attempt > maxRetries || !isRetryable(error)) throw error
const exponential = Math.min(1000 * Math.pow(2, attempt - 1), 10000)
const jitter = Math.random() * 500
await sleep(exponential + jitter)
}
}
}
function isRetryable(error: any): boolean {
return (
error.code === 'ECONNRESET' ||
error.code === 'ETIMEDOUT' ||
(error.status >= 500 && error.status < 600) ||
error.status === 429
)
}
重试决策矩阵:
| 错误类型 | 重试? | 原因 |
|---|---|---|
| 5xx、429、网络超时 | ✅ 是 | 暂时性错误 |
| 4xx、401、403、404 | ❌ 否 | 客户端错误不会自行修复 |
速率限制处理
if (error.status === 429) {
const retryAfter = parseInt(error.headers['retry-after'] || '60')
await sleep(retryAfter * 1000)
}
对于 429 响应,请遵循 Retry-After 标头。
关于抖动策略、熔断器和幂等键,请参阅 references/retry-backoff.md。
错误处理
类型化错误层级
class APIError extends Error {
constructor(
message: string,
public status: number,
public code: string,
public requestId: string
) {
super(message)
this.name = 'APIError'
}
}
class RateLimitError extends APIError {
constructor(message: string, requestId: string, public retryAfter: number) {
super(message, 429, 'rate_limit_error', requestId)
}
}
class AuthenticationError extends APIError {
constructor(message: string, requestId: string) {
super(message, 401, 'authentication_error', requestId)
}
}
实际错误处理
try {
const user = await client.users.create({ email: 'invalid' })
} catch (error) {
if (error instanceof RateLimitError) {
await sleep(error.retryAfter * 1000)
} else if (error instanceof AuthenticationError) {
console.error('Invalid API key')
} else if (error instanceof APIError) {
console.error(`${error.message} (Request ID: ${error.requestId})`)
}
}
在所有错误中包含请求 ID,以便调试。
关于面向用户的消息、验证错误和调试支持,请参阅 references/error-handling.md。
分页
异步迭代器(推荐)
TypeScript:
for await (const user of client.users.list({ limit: 100 })) {
console.log(user.id, user.email)
}
Python:
async for user in client.users.list(limit=100):
print(user.id, user.email)
SDK 会自动获取下一页。
实现
class UsersResource {
async *list(options?: { limit?: number }): AsyncGenerator<User> {
let cursor: string | undefined = undefined
while (true) {
const response = await this.client.request('GET', '/users', {
query: { limit: String(options?.limit || 100), ...(cursor ? { cursor } : {}) }
})
for (const user of response.data) yield user
if (!response.has_more) break
cursor = response.next_cursor
}
}
}
手动分页
let cursor: string | undefined = undefined
while (true) {
const response = await client.users.list({ limit: 100, cursor })
for (const user of response.data) console.log(user.id)
if (!response.has_more) break
cursor = response.next_cursor
}
同时提供自动和手动选项。
关于游标分页与偏移分页,以及 Go 通道模式,请参阅 references/pagination.md。
流式传输
服务器发送事件
async *stream(path: string, body?: any): AsyncGenerator<any> {
const response = await fetch(url, {
headers: { 'Accept': 'text/event-stream' },
body: JSON.stringify(body)
})
const reader = response.body!.getReader()
const decoder = new TextDecoder()
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value)
for (const line of chunk.split('\n')) {
if (line.startsWith('data: ')) {
const data = line.slice(6)
if (data === '[DONE]') return
yield JSON.parse(data)
}
}
}
}
// Usage
for await (const chunk of client.posts.stream({ prompt: 'Write a story' })) {
process.stdout.write(chunk.content)
}
幂等键
在重试期间防止重复操作:
import { randomUUID } from 'crypto'
if (['POST', 'PATCH', 'PUT'].includes(method)) {
headers['Idempotency-Key'] = options?.idempotencyKey || randomUUID()
}
// Usage
await client.charges.create(
{ amount: 1000 },
{ idempotencyKey: 'charge_unique_123' }
)
服务器会根据键对请求去重。
版本控制
语义化版本控制
1.0.0→1.1.0:新功能(安全)1.1.0→2.0.0:破坏性变更(需审核)1.0.0→1.0.1:错误修复(安全)
弃用警告
function deprecated(message: string, since: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value
descriptor.value = function (...args: any[]) {
console.warn(`[DEPRECATED] ${propertyKey} since ${since}. ${message}`)
return originalMethod.apply(this, args)
}
return descriptor
}
}
@deprecated('Use users.list() instead', 'v2.0.0')
async getAll() { return this.list() }
API 版本固定
const client = new APIClient({
apiKey: 'sk_test_...',
apiVersion: '2025-01-01'
})
关于迁移策略,请参阅 references/versioning.md。
配置最佳实践
interface ClientConfig {
apiKey: string
baseURL?: string
maxRetries?: number
timeout?: number
apiVersion?: string
onTokenRefresh?: (token: string) => void
}
class APIClient {
constructor(config: ClientConfig) {
this.apiKey = config.apiKey
this.baseURL = config.baseURL || 'https://api.example.com'
this.maxRetries = config.maxRetries ?? 3
this.timeout = config.timeout ?? 30000
}
}
提供合理的默认值,仅要求提供 apiKey。
快速参考表
身份验证模式
| 模式 | 使用场景 |
|---|---|
| API 密钥 | 服务间通信 |
| OAuth 刷新 | 基于用户的身份验证 |
| 每个请求使用持有者令牌 | 多租户 |
重试策略
| 策略 | 使用场景 |
|---|---|
| 指数退避 | 默认重试 |
| 速率限制 | 429 响应 |
| 最大重试次数 | 避免无限循环(3-5 次) |
分页选项
| 模式 | 语言 | 使用场景 |
|---|---|---|
| 异步迭代器 | TypeScript、Python | 自动分页 |
| 生成器 | Python | 同步分页 |
| 通道 | Go | 并发迭代 |
| 手动 | 全部 | 显式控制 |
参考文档
架构:
references/architecture-patterns.md- 资源与命令的组织方式
核心模式:
references/authentication.md- OAuth、令牌刷新、凭据提供程序references/retry-backoff.md- 指数退避、抖动、熔断器references/error-handling.md- 错误层次结构、调试支持references/pagination.md- 游标与偏移量、异步迭代器references/versioning.md- SemVer、弃用策略references/testing-sdks.md- 单元测试、模拟、集成测试
代码示例
TypeScript:
examples/typescript/basic-client.ts- 简单的异步 SDKexamples/typescript/advanced-client.ts- 重试、错误、流式处理examples/typescript/resource-based.ts- Stripe 风格的组织方式
Python:
examples/python/sync-client.py- 同步客户端examples/python/async-client.py- 使用 asyncio 的异步客户端examples/python/dual-client.py- 同时支持同步和异步
Go:
examples/go/basic-client.go- 简单的 Go 客户端examples/go/context-client.go- Context 模式examples/go/channel-pagination.go- 基于通道的分页
一流 SDK 示例
研究这些生产级 SDK:
TypeScript/JavaScript:
- AWS SDK v3(
@aws-sdk/client-*):模块化、支持摇树优化、中间件 - Stripe Node(
stripe):基于资源、类型化错误、出色的开发体验 - OpenAI Node(
openai):流式处理、异步迭代器、现代 TypeScript
Python:
- Boto3(
boto3):资源与客户端模式、分页器 - Stripe Python(
stripe):同步/异步双模式、上下文管理器
Go:
- AWS SDK Go v2(
github.com/aws/aws-sdk-go-v2):Context、中间件
常见陷阱
避免以下错误:
- 没有重试逻辑 - 所有 SDK 都需要针对瞬时错误进行自动重试
- 错误消息不完善 - 包含请求 ID、状态码和错误类型
- 没有分页 - 使用异步迭代器实现自动分页
- 凭据硬编码 - 使用环境变量或配置文件
- 缺少幂等性 - 添加幂等键以防止重复操作
- 忽略速率限制 - 对 429 响应遵循
Retry-After标头 - 破坏性变更 - 使用 SemVer,在移除功能前先弃用
与其他技能的集成
- api-design-principles:API 设计与 SDK 设计相辅相成(错误代码 → 错误类)
- building-clis:CLI 封装 SDK,以便通过命令行访问
- testing-strategies:使用模拟 HTTP 和重试场景测试 SDK
后续步骤
查看特定语言的示例,了解实现细节。研究参考文档,深入了解特定模式。参考一流 SDK(Stripe、AWS、OpenAI),汲取灵感。