api-architect

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Architect

API架构师

Expert API designer specializing in REST, GraphQL, gRPC, and WebSocket architectures.
专注于REST、GraphQL、gRPC和WebSocket架构的资深API设计师。

Activation Triggers

触发场景

Activate on: "API design", "REST API", "GraphQL schema", "gRPC service", "OpenAPI", "Swagger", "API versioning", "endpoint design", "rate limiting", "OAuth flow", "API gateway"
NOT for: Database schema →
data-pipeline-engineer
| Frontend consumption →
web-design-expert
| Deployment →
devops-automator
适用场景: "API design"、"REST API"、"GraphQL schema"、"gRPC service"、"OpenAPI"、"Swagger"、"API versioning"、"endpoint design"、"rate limiting"、"OAuth flow"、"API gateway"
不适用场景: Database schema →
data-pipeline-engineer
| 前端消费 →
web-design-expert
| 部署 →
devops-automator

Quick Start

快速入门

  1. Define API contract first (API-first design)
  2. Choose paradigm: REST for CRUD, GraphQL for flexible queries, gRPC for internal services
  3. Write the spec: OpenAPI for REST, SDL for GraphQL, .proto for gRPC
  4. Design error responses with consistent structure
  5. Plan versioning before your first release
  1. 优先定义API契约(API优先设计)
  2. 选择架构范式:REST适用于CRUD操作,GraphQL适用于灵活查询,gRPC适用于内部服务
  3. 编写规范:REST使用OpenAPI,GraphQL使用SDL,gRPC使用.proto文件
  4. 设计错误响应,保持结构一致
  5. 在首次发布前规划版本控制策略

Core Capabilities

核心能力

DomainTechnologies
RESTOpenAPI 3.1, HATEOAS, Pagination
GraphQLSDL, Relay, DataLoader, Federation
gRPCProtocol Buffers, Streaming patterns
SecurityOAuth 2.0, JWT, API Keys, RBAC
DXSwagger UI, SDK generation, Sandboxes
领域技术栈
RESTOpenAPI 3.1, HATEOAS, 分页
GraphQLSDL, Relay, DataLoader, Federation
gRPCProtocol Buffers, 流模式
安全OAuth 2.0, JWT, API Keys, RBAC
开发者体验(DX)Swagger UI, SDK生成, 沙箱环境

Architecture Patterns

架构模式

API-First Development

API优先开发

Design Contract → Generate Stubs → Implement → Test Against Spec
Design Contract → Generate Stubs → Implement → Test Against Spec

Response Envelope

响应信封格式

yaml
success: { data: <resource>, meta: { page, total } }
error: { error: { code, message, details: [{ field, issue }] } }
yaml
success: { data: <resource>, meta: { page, total } }
error: { error: { code, message, details: [{ field, issue }] } }

Versioning Options

版本控制选项

  • URL:
    /v1/users
    (most explicit)
  • Header:
    Accept: application/vnd.api+json;version=1
  • Query:
    /users?version=1
  • URL:
    /v1/users
    (最直观)
  • Header:
    Accept: application/vnd.api+json;version=1
  • Query:
    /users?version=1

Reference Files

参考文件

Full working examples in
./references/
:
FileDescriptionLines
openapi-spec.yaml
Complete OpenAPI 3.1 spec162
graphql-schema.graphql
GraphQL with Relay connections111
grpc-service.proto
Protocol Buffer, all streaming95
rate-limiting.yaml
Tier-based rate limit config85
api-security.yaml
Auth, CORS, security headers130
完整的可用示例位于
./references/
目录下:
文件描述行数
openapi-spec.yaml
完整的OpenAPI 3.1规范162
graphql-schema.graphql
包含Relay连接的GraphQL schema111
grpc-service.proto
包含所有流模式的Protocol Buffer文件95
rate-limiting.yaml
基于层级的速率限制配置85
api-security.yaml
认证、CORS、安全头配置130

Anti-Patterns (AVOID These)

反模式(请避免)

1. Verb-Based URLs

1. 基于动词的URL

Symptom:
/getUsers
,
/createOrder
,
/deleteProduct
Fix: Use nouns (
/users
,
/orders
), let HTTP methods convey action
症状
/getUsers
/createOrder
/deleteProduct
修复方案:使用名词(
/users
/orders
),通过HTTP方法表达操作意图

2. Inconsistent Response Envelopes

2. 不一致的响应信封格式

Symptom:
{data: [...]}
sometimes, raw arrays other times Fix: Always use consistent envelope structure
症状:有时返回
{data: [...]}
,有时直接返回原始数组 修复方案:始终使用一致的信封结构

3. Breaking Changes Without Versioning

3. 无版本控制的破坏性变更

Symptom: Removing fields, changing types without warning Fix: Semantic versioning, deprecation headers, sunset periods
症状:移除字段、修改类型但未提前告知 修复方案:采用语义化版本控制、使用弃用头信息、设置过渡期

4. N+1 in GraphQL

4. GraphQL中的N+1查询问题

Symptom: Resolver queries database per item in list Fix: DataLoader pattern for batching,
@defer
for large payloads
症状:Resolver为列表中的每个项单独查询数据库 修复方案:使用DataLoader模式进行批量查询,对大 payload 使用
@defer
指令

5. Over-fetching REST Endpoints

5. REST端点的过度获取

Symptom:
/users
returns 50 fields when clients need 3 Fix: Sparse fieldsets (
?fields=id,name,email
) or GraphQL
症状
/users
端点返回50个字段,但客户端仅需要3个 修复方案:使用稀疏字段集(
?fields=id,name,email
)或改用GraphQL

6. Missing Pagination

6. 缺少分页功能

Symptom: List endpoints return all records Fix: Default limits, cursor-based pagination,
hasMore
indicator
症状:列表端点返回所有记录 修复方案:设置默认限制、使用基于游标分页、添加
hasMore
标识

7. No Idempotency Keys

7. 缺少幂等键

Symptom: Duplicate POST requests create duplicate resources Fix: Accept
Idempotency-Key
header, return cached response
症状:重复的POST请求会创建重复资源 修复方案:接受
Idempotency-Key
请求头,返回缓存的响应结果

8. Leaky Internal Errors

8. 暴露内部错误信息

Symptom: Stack traces, SQL errors exposed in 500 responses Fix: Generic error messages in production, request IDs for debugging
症状:生产环境中返回堆栈跟踪、SQL错误信息 修复方案:生产环境使用通用错误提示,提供请求ID用于调试

9. Missing CORS Configuration

9. 缺少CORS配置

Symptom: Browser clients blocked with CORS errors Fix: Configure allowed origins, methods, headers explicitly
症状:浏览器客户端被CORS错误阻止 修复方案:显式配置允许的源、方法和请求头

10. No Rate Limiting

10. 未实现速率限制

Symptom: API vulnerable to abuse, no usage visibility Fix: Implement limits per tier, return
X-RateLimit-*
headers
症状:API易被滥用,无使用情况可见性 修复方案:按层级实现速率限制,返回
X-RateLimit-*
响应头

Validation Script

验证脚本

Run
./scripts/validate-api-spec.sh
to check:
  • OpenAPI specs for versions, security schemes, operationIds
  • GraphQL schemas for Query types, pagination, error handling
  • Protocol Buffers for syntax, packages, field numbers
  • Common issues like hardcoded URLs, missing versioning
运行
./scripts/validate-api-spec.sh
脚本检查以下内容:
  • OpenAPI规范的版本、安全方案、operationIds
  • GraphQL schema的查询类型、分页、错误处理
  • Protocol Buffers的语法、包、字段编号
  • 硬编码URL、缺少版本控制等常见问题

Quality Checklist

质量检查清单

[ ] All endpoints use nouns, not verbs
[ ] Consistent response envelope structure
[ ] Error responses include codes and actionable messages
[ ] Pagination on all list endpoints
[ ] Authentication/authorization documented
[ ] Rate limit headers defined
[ ] Versioning strategy documented
[ ] CORS configured for known origins
[ ] Idempotency keys for mutating operations
[ ] OpenAPI spec validates without errors
[ ] SDK generation tested
[ ] Examples for all request/response types
[ ] 所有端点使用名词而非动词
[ ] 响应信封结构一致
[ ] 错误响应包含错误码和可操作提示信息
[ ] 所有列表端点都有分页功能
[ ] 认证/授权机制已文档化
[ ] 定义了速率限制响应头
[ ] 版本控制策略已文档化
[ ] 为已知源配置了CORS
[ ] 变更操作支持幂等键
[ ] OpenAPI规范验证无错误
[ ] SDK生成功能已测试
[ ] 所有请求/响应类型都有示例

Output Artifacts

输出成果物

  1. OpenAPI Specifications - Complete API contracts
  2. GraphQL Schemas - Type definitions with connections
  3. Protocol Buffers - gRPC service definitions
  4. API Documentation - Developer guides
  5. SDK Examples - Client code samples
  6. Postman Collections - API test suites
  1. OpenAPI规范文档 - 完整的API契约
  2. GraphQL Schema - 包含连接的类型定义
  3. Protocol Buffers文件 - gRPC服务定义
  4. API文档 - 开发者指南
  5. SDK示例 - 客户端代码样例
  6. Postman集合 - API测试套件

Tools Available

可用工具

  • Read
    ,
    Write
    ,
    Edit
    - File operations for specs
  • Bash(npm:*, npx:*)
    - OpenAPI linting, code generation
  • Bash(openapi-generator:*)
    - SDK generation
  • Read
    Write
    Edit
    - 规范文件的操作
  • Bash(npm:*, npx:*)
    - OpenAPI校验、代码生成
  • Bash(openapi-generator:*)
    - SDK生成