AgentSkillsCN

rest-api-design

REST API 设计原则、约定和模式。 适用场景:设计 API、选择状态码、错误处理、缓存、认证模式。 不适用于:框架特定实现(使用 fastapi、axum 技能)。 工作流程:本技能(设计)→ fastapi/axum(实现)。

SKILL.md
--- frontmatter
name: rest-api-design
description: |
  REST API design principles, conventions, and patterns.
  Use when: designing APIs, choosing status codes, error handling, caching, auth patterns.
  Do not use for: framework-specific implementation (use fastapi, axum skills).
  Workflow: This skill (design) → fastapi/axum (implementation).
references:
  - examples.md    # Full request/response examples
  - https://www.speakeasy.com/api-design/responses
  - https://strapi.io/blog/rest-api-design-best-practices

API Design

Resource Naming

Rule: Model nouns, not verbs. HTTP methods express actions.

code
# ❌ Verbs in URL
POST /createUser
GET /getUsers

# ✅ RESTful
POST /users
GET /users
DELETE /users/123
PatternExample
Collection/users
Single resource/users/{id}
Nested (shallow)/users/{id}/orders
Filter via query/orders?userId=123

Rule: Plural nouns, lowercase, max 2 levels deep.

code
# ❌ Too deep
/companies/{id}/departments/{id}/users/{id}/orders

# ✅ Flatten
/orders?userId=123

HTTP Methods

MethodActionIdempotentSuccess Code
GETRead200
POSTCreate201
PUTReplace200
PATCHPartial update200
DELETERemove204

Rule: Idempotent = safe to retry. POST creates duplicates on retry.


Status Codes

Success (2xx)

CodeWhen
200 OKGeneric success
201 CreatedResource created + Location header
202 AcceptedAsync processing started
204 No ContentSuccess, no body (DELETE)

Client Error (4xx)

CodeWhen
400 Bad RequestMalformed syntax
401 UnauthorizedNo/invalid auth
403 ForbiddenNo permission
404 Not FoundResource doesn't exist
409 ConflictDuplicate, state conflict
410 GonePermanently deleted
422 UnprocessableValidation failed
429 Too Many RequestsRate limited

Server Error (5xx)

CodeWhen
500 Internal Server ErrorUnexpected failure
502 Bad GatewayUpstream down
503 Service UnavailableTemporarily unavailable

Rule: 4xx = client's fault. 5xx = server's fault (retry later).


Response Format

Success

json
{
  "data": { "id": 123, "name": "Ada" },
  "meta": { "requestId": "abc123" }
}

Error (RFC 9457 Problem Details)

json
{
  "type": "https://api.example.com/errors/validation-failed",
  "title": "Validation Failed",
  "status": 422,
  "detail": "Email is required",
  "errors": [{ "field": "email", "code": "required" }]
}

Rule: Use Content-Type: application/problem+json for errors.

See examples.md for full request/response examples.


Request/Response Consistency

Rule: Request shape should match response shape.

Response may have read-only fields (id, createdAt), but structure must be identical. Never change field types or nesting between request/response.


Pagination

TypeUse forExample
Cursor-basedFeeds, timelines, large data?cursor=xyz&limit=20
Offset-basedAdmin panels, small data?page=2&limit=20

Rule: Prefer cursor-based. Offset has performance issues at scale.


Filtering & Sorting

code
GET /users?role=admin&status=active
GET /users?sort=-createdAt
GET /users?fields=id,name,email

Rule: Filters in query string, not URL path.


Caching

HeaderPurpose
ETagVersion for conditional requests
Cache-Controlpublic, private, no-store
Last-ModifiedTimestamp

Rule: Cache public data. private, no-store for user-specific.


Security

ItemRecommended
Password hashingargon2id (64MB, 3 iter, 4 parallel)
JWT algorithmES256 or EdDSA
JWT access token15-30 minutes
JWT refresh token (web)90 days
JWT refresh token (mobile)1 year
TLS1.3+ only
CORSExplicit origins only
Rate limit (auth)5/min
Rate limit (API)100/min baseline
API TypeAuth Pattern
User-facingJWT
Public APIAPI keys, OAuth 2.0
Service-to-servicemTLS
WebhooksHMAC signature

Rate limit headers:

http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
Retry-After: 30

Rule: Stateless auth enables horizontal scaling. Return Retry-After with 429.


Versioning

code
/v1/users
/v2/users

Rule: Version in URL. Only for breaking changes. Use Sunset header for deprecation.


Quick Checklist

URL Design

  • Plural nouns, no verbs
  • Max 2 levels nesting
  • Filters in query string

HTTP

  • Correct methods and status codes
  • 201 + Location for create
  • 204 for delete

Response

  • Consistent envelope (data, meta)
  • RFC 9457 for errors
  • Request/response shapes match

Performance

  • Pagination on collections
  • Cache headers
  • Field selection

Security

  • HTTPS only
  • Stateless auth
  • Rate limiting