API Designer by daffy0208/ai-dev-standards
npx skills add https://github.com/daffy0208/ai-dev-standards --skill 'API Designer'设计健壮、可扩展且对开发者友好的 API。
✅ 良好 (名词,复数,层级结构):
GET /users # 列出所有用户
GET /users/123 # 获取特定用户
POST /users # 创建用户
PUT /users/123 # 替换用户
PATCH /users/123 # 更新用户
DELETE /users/123 # 删除用户
GET /users/123/posts # 用户的帖子 (嵌套)
GET /users/123/posts/456 # 特定帖子
❌ 不佳 (动词,不一致,不清晰):
GET /getUsers
POST /createUser
GET /user-list
GET /UserData?id=123
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 方法 | 目的 | 幂等性 | 安全性 | 请求体 | 响应体 |
|---|---|---|---|---|---|
| GET | 检索数据 | 是 | 是 | 否 | 是 |
| POST | 创建资源 | 否 | 否 | 是 | 是 (已创建) |
| PUT | 替换资源 | 是 | 否 | 是 | 是 (可选) |
| PATCH | 部分更新 | 否 | 否 | 是 | 是 (可选) |
| DELETE | 移除资源 | 是 | 否 | 否 | 否 (204) 或 是 |
幂等性 : 多个相同的请求与单个请求具有相同的效果 安全性 : 请求不会修改服务器状态
成功 (2xx) :
200 OK - GET、PUT、PATCH、DELETE 成功201 Created - POST 成功,包含 Location 头204 No Content - 请求成功,无响应体 (常用于 DELETE)客户端错误 (4xx) :
400 Bad Request - 语法无效,验证错误401 Unauthorized - 需要身份验证或验证失败403 Forbidden - 已认证但权限不足404 Not Found - 资源不存在409 Conflict - 请求与当前状态冲突422 Unprocessable Entity - 验证错误 (语义层面)429 Too Many Requests - 超出速率限制服务器错误 (5xx) :
500 Internal Server Error - 通用服务器错误502 Bad Gateway - 上游服务错误503 Service Unavailable - 暂时不可用504 Gateway Timeout - 上游超时成功响应 :
{
"data": {
"id": "123",
"type": "user",
"attributes": {
"name": "John Doe",
"email": "john@example.com",
"created_at": "2025-01-15T10:30:00Z"
}
}
}
错误响应 :
{
"error": {
"code": "VALIDATION_ERROR",
"message": "请求验证失败",
"details": [
{
"field": "email",
"code": "REQUIRED",
"message": "邮箱为必填项"
},
{
"field": "age",
"code": "OUT_OF_RANGE",
"message": "年龄必须在 18 到 120 之间"
}
],
"request_id": "req_abc123",
"documentation_url": "https://api.example.com/docs/errors/validation"
}
}
带分页的列表响应 :
{
"data": [...],
"pagination": {
"cursor": "eyJpZCI6MTIzfQ==",
"has_more": true,
"total_count": 1000
},
"links": {
"next": "/users?cursor=eyJpZCI6MTIzfQ==&limit=20",
"prev": "/users?cursor=eyJpZCI6MTAwfQ==&limit=20"
}
}
基于游标 (推荐) :
GET /users?cursor=abc123&limit=20
优点: 结果一致,高效,能处理实时数据
缺点: 无法跳转到任意页面
使用场景: 大型数据集,实时数据,性能关键
基于偏移量 :
GET /users?page=1&per_page=20
GET /users?offset=0&limit=20
优点: 简单,可以跳转到任意页面
缺点: 在并发写入时不一致,规模扩大时效率低
使用场景: 小型数据集,管理界面,简单用例
过滤 :
GET /users?status=active&role=admin&created_after=2025-01-01
排序 :
GET /users?sort=-created_at,name # 按 created_at 降序,然后按 name 升序
搜索 :
GET /users?q=john&fields=name,email # 在指定字段中搜索
JWT Bearer 令牌 (推荐用于 SPA) :
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
优点: 无状态,包含用户声明,跨域工作
缺点: 到期前无法撤销,载荷较大
API 密钥 (用于服务间通信) :
X-API-Key: sk_live_abc123...
优点: 简单,易于轮换,可按服务设置密钥
缺点: 无用户上下文,必须保密
OAuth 2.0 (用于第三方访问) :
Authorization: Bearer access_token
优点: 委托授权,范围权限,行业标准
缺点: 设置复杂,需要 OAuth 服务器
基本认证 (仅用于内部/管理工具) :
Authorization: Basic base64(username:password)
优点: 简单,HTTP 内置
缺点: 每个请求都包含凭据,必须使用 HTTPS
标准头部 :
X-RateLimit-Limit: 1000 # 每个窗口的最大请求数
X-RateLimit-Remaining: 999 # 剩余请求数
X-RateLimit-Reset: 1640995200 # 限制重置的 Unix 时间戳
Retry-After: 60 # 等待秒数 (在 429 时)
常见策略 :
URL 版本控制 (推荐) :
/v1/users
/v2/users
优点: 明确,易于路由,日志中清晰可见
缺点: URL 污染,增量演进更困难
头部版本控制 :
Accept: application/vnd.myapp.v2+json
API-Version: 2
优点: URL 简洁,遵循 REST 原则
缺点: 可见性较低,在浏览器中测试更困难
最佳实践 :
type User {
id: ID!
name: String!
email: String!
posts(first: Int, after: String): PostConnection!
createdAt: DateTime!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PostEdge {
node: Post!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
type Query {
user(id: ID!): User
users(first: Int, after: String): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}
input CreateUserInput {
name: String!
email: String!
}
type CreateUserPayload {
user: User
errors: [Error!]
}
1. 使用 Relay 连接模式进行分页 :
query {
users(first: 10, after: "cursor") {
edges {
node {
id
name
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
2. 变异的输入类型 :
# ✅ 良好: 输入类型 + 载荷
mutation {
createUser(input: { name: "John", email: "john@example.com" }) {
user {
id
name
}
errors {
field
message
}
}
}
# ❌ 不佳: 扁平参数
mutation {
createUser(name: "John", email: "john@example.com") {
id
name
}
}
3. 错误处理 :
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
type CreateUserPayload {
user: User # 如果有错误则为 null
errors: [Error!] # 字段级错误
}
type Error {
field: String!
code: String!
message: String!
}
使用 REST 当 :
使用 GraphQL 当 :
openapi: 3.0.0
info:
title: 用户管理 API
version: 1.0.0
description: 用于管理用户和帖子的 API
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: 列出用户
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: per_page
in: query
schema:
type: integer
default: 20
maximum: 100
responses:
'200':
description: 成功
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
'401':
$ref: '#/components/responses/Unauthorized'
post:
summary: 创建用户
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserInput'
responses:
'201':
description: 用户已创建
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: string
name:
type: string
email:
type: string
format: email
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
相关技能 :
frontend-builder - 用于从前端消费 APIdeployment-advisor - 用于 API 托管决策performance-optimizer - 用于 API 性能调优相关模式 :
META/DECISION-FRAMEWORK.md - REST 与 GraphQL 决策STANDARDS/architecture-patterns/api-gateway-pattern.md - API 网关架构 (创建时)相关操作手册 :
PLAYBOOKS/deploy-api.md - API 部署流程 (创建时)PLAYBOOKS/version-api.md - API 版本控制工作流 (创建时)每周安装次数
–
代码仓库
GitHub 星标数
21
首次出现
–
安全审计
Design robust, scalable, and developer-friendly APIs.
✅ Good (Nouns, plural, hierarchical):
GET /users # List all users
GET /users/123 # Get specific user
POST /users # Create user
PUT /users/123 # Replace user
PATCH /users/123 # Update user
DELETE /users/123 # Delete user
GET /users/123/posts # User's posts (nested)
GET /users/123/posts/456 # Specific post
❌ Bad (Verbs, inconsistent, unclear):
GET /getUsers
POST /createUser
GET /user-list
GET /UserData?id=123
| Method | Purpose | Idempotent | Safe | Request Body | Response Body |
|---|---|---|---|---|---|
| GET | Retrieve data | Yes | Yes | No | Yes |
| POST | Create resource | No | No | Yes | Yes (created) |
| PUT | Replace resource | Yes | No | Yes | Yes (optional) |
| PATCH | Partial update | No | No | Yes | Yes (optional) |
Idempotent : Multiple identical requests have same effect as single request Safe : Request doesn't modify server state
Success (2xx) :
200 OK - Successful GET, PUT, PATCH, DELETE201 Created - Successful POST, includes Location header204 No Content - Successful request, no response body (often DELETE)Client Errors (4xx) :
400 Bad Request - Invalid syntax, validation error401 Unauthorized - Authentication required or failed403 Forbidden - Authenticated but lacks permission404 Not Found - Resource doesn't exist409 Conflict - Request conflicts with current state422 Unprocessable Entity - Validation error (semantic)429 Too Many Requests - Rate limit exceededServer Errors (5xx) :
500 Internal Server Error - Generic server error502 Bad Gateway - Upstream service error503 Service Unavailable - Temporary unavailability504 Gateway Timeout - Upstream timeoutSuccess Response :
{
"data": {
"id": "123",
"type": "user",
"attributes": {
"name": "John Doe",
"email": "john@example.com",
"created_at": "2025-01-15T10:30:00Z"
}
}
}
Error Response :
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "email",
"code": "REQUIRED",
"message": "Email is required"
},
{
"field": "age",
"code": "OUT_OF_RANGE",
"message": "Age must be between 18 and 120"
}
],
"request_id": "req_abc123",
"documentation_url": "https://api.example.com/docs/errors/validation"
}
}
List Response with Pagination :
{
"data": [...],
"pagination": {
"cursor": "eyJpZCI6MTIzfQ==",
"has_more": true,
"total_count": 1000
},
"links": {
"next": "/users?cursor=eyJpZCI6MTIzfQ==&limit=20",
"prev": "/users?cursor=eyJpZCI6MTAwfQ==&limit=20"
}
}
Cursor-based (Recommended) :
GET /users?cursor=abc123&limit=20
Pros: Consistent results, efficient, handles real-time data
Cons: Can't jump to arbitrary page
Use when: Large datasets, real-time data, performance critical
Offset-based :
GET /users?page=1&per_page=20
GET /users?offset=0&limit=20
Pros: Simple, can jump to any page
Cons: Inconsistent with concurrent writes, inefficient at scale
Use when: Small datasets, admin interfaces, simple use cases
Filtering :
GET /users?status=active&role=admin&created_after=2025-01-01
Sorting :
GET /users?sort=-created_at,name # Descending created_at, then ascending name
Search :
GET /users?q=john&fields=name,email # Search across specified fields
JWT Bearer Token (Recommended for SPAs) :
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Pros: Stateless, includes user claims, works across domains
Cons: Can't revoke until expiry, larger payload
API Keys (for service-to-service) :
X-API-Key: sk_live_abc123...
Pros: Simple, easy to rotate, per-service keys
Cons: No user context, must be kept secret
OAuth 2.0 (for third-party access) :
Authorization: Bearer access_token
Pros: Delegated auth, scoped permissions, industry standard
Cons: Complex setup, requires OAuth server
Basic Auth (only for internal/admin tools) :
Authorization: Basic base64(username:password)
Pros: Simple, built-in to HTTP
Cons: Credentials in every request, must use HTTPS
Standard Headers :
X-RateLimit-Limit: 1000 # Max requests per window
X-RateLimit-Remaining: 999 # Requests left
X-RateLimit-Reset: 1640995200 # Unix timestamp when limit resets
Retry-After: 60 # Seconds to wait (on 429)
Common Strategies :
URL Versioning (Recommended) :
/v1/users
/v2/users
Pros: Explicit, easy to route, clear in logs
Cons: URL pollution, harder to evolve incrementally
Header Versioning :
Accept: application/vnd.myapp.v2+json
API-Version: 2
Pros: Clean URLs, follows REST principles
Cons: Less visible, harder to test in browser
Best Practices :
type User {
id: ID!
name: String!
email: String!
posts(first: Int, after: String): PostConnection!
createdAt: DateTime!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PostEdge {
node: Post!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
type Query {
user(id: ID!): User
users(first: Int, after: String): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}
input CreateUserInput {
name: String!
email: String!
}
type CreateUserPayload {
user: User
errors: [Error!]
}
1. Use Relay Connection Pattern for Pagination :
query {
users(first: 10, after: "cursor") {
edges {
node {
id
name
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
2. Input Types for Mutations :
# ✅ Good: Input type + payload
mutation {
createUser(input: { name: "John", email: "john@example.com" }) {
user {
id
name
}
errors {
field
message
}
}
}
# ❌ Bad: Flat arguments
mutation {
createUser(name: "John", email: "john@example.com") {
id
name
}
}
3. Error Handling :
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
type CreateUserPayload {
user: User # Null if errors
errors: [Error!] # Field-level errors
}
type Error {
field: String!
code: String!
message: String!
}
Use REST when :
Use GraphQL when :
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
description: API for managing users and posts
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: List users
parameters:
- name: page
in: query
schema:
type: integer
default: 1
- name: per_page
in: query
schema:
type: integer
default: 20
maximum: 100
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/UserList'
'401':
$ref: '#/components/responses/Unauthorized'
post:
summary: Create user
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserInput'
responses:
'201':
description: User created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: string
name:
type: string
email:
type: string
format: email
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
Related Skills :
frontend-builder - For consuming APIs from frontenddeployment-advisor - For API hosting decisionsperformance-optimizer - For API performance tuningRelated Patterns :
META/DECISION-FRAMEWORK.md - REST vs GraphQL decisionsSTANDARDS/architecture-patterns/api-gateway-pattern.md - API gateway architecture (when created)Related Playbooks :
PLAYBOOKS/deploy-api.md - API deployment procedure (when created)PLAYBOOKS/version-api.md - API versioning workflow (when created)Weekly Installs
–
Repository
GitHub Stars
21
First Seen
–
Security Audits
Lark Drive API 使用指南:飞书云文档、Wiki、表格 Token 处理与文件管理
23,400 周安装
| Remove resource |
| Yes |
| No |
| No |
| No (204) or Yes |