微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🔌

REST/GraphQL 接口设计规范

api-design-principles · v0.0.0
可以安装,但有提示 NO_DESCRIPTION
专业技能 安全 S+ 级 作者 wpank 公开目录收录
3.6k 下载 930 安装 14.3k 收藏 45.6k 浏览

简介

基于行业最佳实践的 API 架构设计指南,涵盖 REST 与 GraphQL 双范式,帮助开发者构建高可用、易维护的接口系统,显著提升团队协作与开发效率。

原始描述

Design clear, scalable REST and GraphQL APIs including resource modeling, HTTP methods, pagination, error handling, versioning, and schema best practices.

通过你的 Agent 添加

安装目录:api-design-principles/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/api-design-principles-5110/
Codex CLI~/.codex/skills/api-design-principles-5110/
DeepSeek Harness~/.agents/skills/api-design-principles-5110/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

本技能为开发者提供系统化的 API 设计原则与最佳实践指南,涵盖 REST 和 GraphQL 两大主流范式。核心内容包括资源命名规范(复数名词、避免深层嵌套)、HTTP 语义精确使用(方法选择、状态码定义)、分页策略(偏移式与游标式)、错误响应标准化格式、API 版本控制策略(URL 与 Header 方案对比),以及 GraphQL Schema 设计与 DataLoader 优化模式。技能还提供完整的 FastAPI 实现示例,包含参数校验、分页逻辑、错误处理等生产级代码模板,可直接作为项目开发参考。

显著优点

  1. 决策框架清晰:提供 REST vs GraphQL 的详细对比矩阵,帮助团队根据业务场景(简单 CRUD vs 复杂嵌套查询、缓存需求 vs 带宽优化)做出合理技术选型。

  2. 标准化程度高:定义了完整的 API 设计规范,从 URL 结构、HTTP 方法使用到状态码选择,确保团队输出一致的接口风格,降低维护成本。

  3. 实践导向:包含"NEVER"禁忌清单(如避免动词 URL、避免 POST 用于查询等),以及实施前检查表,帮助团队规避常见设计陷阱。

  4. 代码示例丰富:提供 FastAPI 框架的完整实现示例,涵盖依赖注入、参数校验、异步处理等现代 Python Web 开发最佳实践。

  5. 安全考虑周全:涵盖速率限制实现、查询深度限制(GraphQL)、输入验证等安全机制设计。

潜在缺点与局限性

  1. 纯文档性质:作为设计指南而非自动化工具,无法直接生成 API 代码或自动验证现有 API 合规性,需要开发者手动参照实施。

  2. 来源权威性有限:技能来源于个人开发者(T3 级别),虽内容符合行业标准,但缺乏大型科技公司或标准化组织的官方背书。

  3. 框架局限性:示例代码主要基于 FastAPI/Python 生态,对 Java、Node.js、Go 等其他语言开发者的直接参考价值相对有限。

  4. 业务场景适配:提供的模板代码需要根据具体业务需求调整(如数据库连接、认证机制、CORS 配置等),不能直接用于生产环境。

适合的目标群体

  • 后端开发工程师:需要设计新 API 或重构现有接口的开发者
  • 系统架构师:负责制定团队 API 设计规范和技术标准的技术负责人
  • API 设计师:专注于接口可用性和开发者体验的产品人员
  • 技术团队负责人:需要建立团队开发规范、进行代码审查标准制定的管理者
  • 全栈开发者:需要理解前后端交互契约,设计高效数据获取方案的工程师

使用风险

该技能为纯文档型资产,无代码执行风险,不涉及网络通信或数据收集,使用安全性极高。潜在风险主要在于:模板代码适配风险——提供的 FastAPI 示例仅为参考实现,直接用于生产环境前需进行安全审查(如数据库连接池配置、环境变量管理、敏感信息过滤等);版本兼容性——示例代码基于特定版本的 FastAPI/Pydantic,升级框架版本时可能需要调整语法;过度设计风险——对于简单内部工具,完全遵循企业级 API 规范可能增加不必要的开发复杂度。建议结合项目实际规模选择性采纳设计原则。

技能正文


name: api-design-principles model: reasoning

API Design Principles

WHAT

Design intuitive, scalable REST and GraphQL APIs that developers love. Covers resource modeling, HTTP semantics, pagination, error handling, versioning, and GraphQL schema patterns.

WHEN

  • Designing new REST or GraphQL APIs
  • Reviewing API specifications before implementation
  • Establishing API design standards for teams
  • Refactoring APIs for better usability
  • Migrating between API paradigms

KEYWORDS

REST, GraphQL, API design, HTTP methods, pagination, error handling, versioning, OpenAPI, HATEOAS, schema design


Decision Framework: REST vs GraphQL

Choose REST when... Choose GraphQL when...
Simple CRUD operations Complex nested data requirements
Public APIs with broad audience Mobile apps needing bandwidth optimization
Heavy caching requirements Clients need to specify exact data shape
Team is unfamiliar with GraphQL Aggregating multiple data sources
Simple response structures Rapidly evolving frontend requirements

REST API Design

Resource Naming Rules

✓ Plural nouns for collections
  GET /api/users
  GET /api/orders
  GET /api/products

✗ Avoid verbs (let HTTP methods be the verb)
  POST /api/createUser     ← Wrong
  POST /api/users          ← Correct

✓ Nested resources (max 2 levels)
  GET /api/users/{id}/orders
  
✗ Avoid deep nesting
  GET /api/users/{id}/orders/{orderId}/items/{itemId}/reviews  ← Too deep
  GET /api/order-items/{id}/reviews                            ← Better

HTTP Methods and Status Codes

Method Purpose Success Common Errors
GET Retrieve 200 OK 404 Not Found
POST Create 201 Created 400/422 Validation
PUT Replace 200 OK 404 Not Found
PATCH Partial update 200 OK 404 Not Found
DELETE Remove 204 No Content 404/409 Conflict

Complete Status Code Reference

SUCCESS = {
    200: "OK",           # GET, PUT, PATCH success
    201: "Created",      # POST success
    204: "No Content",   # DELETE success
}

CLIENT_ERROR = {
    400: "Bad Request",           # Malformed syntax
    401: "Unauthorized",          # Missing/invalid auth
    403: "Forbidden",             # Valid auth, no permission
    404: "Not Found",             # Resource doesn't exist
    409: "Conflict",              # State conflict (duplicate email)
    422: "Unprocessable Entity",  # Validation errors
    429: "Too Many Requests",     # Rate limited
}

SERVER_ERROR = {
    500: "Internal Server Error",
    503: "Service Unavailable",   # Temporary downtime
}

Pagination

Offset-Based (Simple)
GET /api/users?page=2&page_size=20

{
  "items": [...],
  "page": 2,
  "page_size": 20,
  "total": 150,
  "pages": 8
}
Cursor-Based (For Large Datasets)
GET /api/users?limit=20&cursor=eyJpZCI6MTIzfQ

{
  "items": [...],
  "next_cursor": "eyJpZCI6MTQzfQ",
  "has_more": true
}

Filtering and Sorting

# Filtering
GET /api/users?status=active&role=admin

# Sorting (- prefix for descending)
GET /api/users?sort=-created_at,name

# Search
GET /api/users?search=john

# Field selection
GET /api/users?fields=id,name,email

Error Response Format

Always use consistent structure:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {"field": "email", "message": "Invalid email format"}
    ],
    "timestamp": "2025-10-16T12:00:00Z"
  }
}

FastAPI Implementation

from fastapi import FastAPI, Query, Path, HTTPException, status
from pydantic import BaseModel, Field, EmailStr
from typing import Optional, List
from datetime import datetime

app = FastAPI(title="API", version="1.0.0")

# Models
class UserCreate(BaseModel):
    email: EmailStr
    name: str = Field(..., min_length=1, max_length=100)

class User(BaseModel):
    id: str
    email: str
    name: str
    created_at: datetime

class PaginatedResponse(BaseModel):
    items: List[User]
    total: int
    page: int
    page_size: int
    pages: int

# Endpoints
@app.get("/api/users", response_model=PaginatedResponse)
async def list_users(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    status: Optional[str] = Query(None),
    search: Optional[str] = Query(None)
):
    """List users with pagination and filtering."""
    total = await count_users(status=status, search=search)
    offset = (page - 1) * page_size
    users = await fetch_users(limit=page_size, offset=offset, status=status, search=search)
    
    return PaginatedResponse(
        items=users,
        total=total,
        page=page,
        page_size=page_size,
        pages=(total + page_size - 1) // page_size
    )

@app.post("/api/users", response_model=User, status_code=status.HTTP_201_CREATED)
async def create_user(user: UserCreate):
    """Create new user."""
    if await user_exists(user.email):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail={"code": "EMAIL_EXISTS", "message": "Email already registered"}
        )
    return await save_user(user)

@app.get("/api/users/{user_id}", response_model=User)
async def get_user(user_id: str = Path(...)):
    """Get user by ID."""
    user = await fetch_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@app.delete("/api/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(user_id: str):
    """Delete user."""
    if not await fetch_user(user_id):
        raise HTTPException(status_code=404, detail="User not found")
    await remove_user(user_id)

GraphQL API Design

Schema Structure

# Types
type User {
  id: ID!
  email: String!
  name: String!
  createdAt: DateTime!
  orders(first: Int = 20, after: String): OrderConnection!
}

# Pagination (Relay-style)
type OrderConnection {
  edges: [OrderEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type OrderEdge {
  node: Order!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

# Queries
type Query {
  user(id: ID!): User
  users(first: Int = 20, after: String, search: String): UserConnection!
}

# Mutations with Input/Payload pattern
input CreateUserInput {
  email: String!
  name: String!
  password: String!
}

type CreateUserPayload {
  user: User
  errors: [Error!]
}

type Error {
  field: String
  message: String!
  code: String!
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

DataLoader (Prevent N+1)

from aiodataloader import DataLoader

class UserLoader(DataLoader):
    async def batch_load_fn(self, user_ids: List[str]) -> List[Optional[dict]]:
        """Load multiple users in single query."""
        users = await fetch_users_by_ids(user_ids)
        user_map = {user["id"]: user for user in users}
        return [user_map.get(uid) for uid in user_ids]

# In resolver
@user_type.field("orders")
async def resolve_orders(user: dict, info):
    loader = info.context["loaders"]["orders_by_user"]
    return await loader.load(user["id"])

Query Protection

# Depth limiting
MAX_QUERY_DEPTH = 5

# Complexity limiting
MAX_QUERY_COMPLEXITY = 100

# Timeout
QUERY_TIMEOUT_SECONDS = 10

Versioning Strategies

URL Versioning (Recommended)

/api/v1/users
/api/v2/users

Pros: Clear, easy to route, cacheable Cons: Multiple URLs for same resource

Header Versioning

GET /api/users
Accept: application/vnd.api+json; version=2

Pros: Clean URLs Cons: Less visible, harder to test

Deprecation Strategy

  1. Add deprecation headers: Deprecation: true
  2. Document migration path
  3. Give 6-12 months notice
  4. Monitor usage before removal

Rate Limiting

Headers

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 742
X-RateLimit-Reset: 1640000000

# When limited:
429 Too Many Requests
Retry-After: 3600

Implementation

from datetime import datetime, timedelta

class RateLimiter:
    def __init__(self, calls: int, period: int):
        self.calls = calls
        self.period = period
        self.cache = {}
    
    def check(self, key: str) -> tuple[bool, dict]:
        now = datetime.now()
        if key not in self.cache:
            self.cache[key] = []
        
        # Remove old requests
        cutoff = now - timedelta(seconds=self.period)
        self.cache[key] = [ts for ts in self.cache[key] if ts > cutoff]
        
        remaining = self.calls - len(self.cache[key])
        
        if remaining <= 0:
            return False, {"limit": self.calls, "remaining": 0}
        
        self.cache[key].append(now)
        return True, {"limit": self.calls, "remaining": remaining - 1}

Pre-Implementation Checklist

Resources

  • Nouns, not verbs
  • Plural for collections
  • Max 2 levels nesting

HTTP

  • Correct method for each action
  • Correct status codes
  • Idempotent operations are idempotent

Data

  • All collections paginated
  • Filtering/sorting supported
  • Error format consistent

Security

  • Authentication defined
  • Rate limiting configured
  • Input validation on all fields
  • HTTPS enforced

Documentation

  • OpenAPI spec generated
  • All endpoints documented
  • Examples provided

NEVER

  • Verbs in URLs: /api/getUser → use /api/users/{id} with GET
  • POST for Retrieval: Use GET for safe, idempotent reads
  • Inconsistent Errors: Always same error format
  • Unbounded Lists: Always paginate collections
  • Secrets in URLs: Query params are logged
  • Breaking Changes Without Versioning: Plan for evolution from day 1
  • Database Schema as API: API should be stable even when schema changes
  • Ignoring HTTP Semantics: Status codes and methods have meaning

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

apibackenddevelopment-engineeringdocs

同类 Skill