RESTful API 实践

分页、过滤、排序、错误码、重试、限流与安全这些上线前必须定好的约定。

Intermediate
Key Points上线前把分页方式、错误码表、重试与限流策略固定下来,客户端才能稳定对接。

分页:offset 还是 cursor

OffsetCursor
Request?page=3&size=20?cursor=eyJpZCI6OTAwMX0
Jump to pageYesNo
Deep page costO(n) — the DB scans and discardsO(1) — seek by key
Stable while data changesNo — rows shift between pagesYes
Use forAdmin tables with page numbersFeeds, infinite scroll, exports
JSON
// cursor 分页的响应
{"items": [ ... ], "nextCursor": "eyJpZCI6ODgwMX0", "hasMore": true}

过滤与排序

Text
?status=paid                   等值过滤
?status=paid,shipped           多值(IN)
?minTotal=100&maxTotal=500     区间
?createdAtFrom=2026-01-01      时间范围
?sort=-createdAt,total         减号表示倒序,多个字段用逗号

Whitelist sortable fields. Otherwise you expose column names and invite slow-query abuse.

错误码表

HTTPcodeMeaning
400BAD_REQUESTMalformed request
401UNAUTHORIZEDMissing/invalid token
403FORBIDDENNo permission
404NOT_FOUNDResource missing
409CONFLICTUnique constraint hit
422VALIDATION_FAILEDField-level invalid
429RATE_LIMITEDToo many requests

重试与超时

  • 只对幂等方法(GET/PUT/DELETE)自动重试,POST 靠幂等键
  • 指数退避 + 抖动:1s、2s、4s… 上限 30s
  • 只重试 5xx 与 429;4xx(除 429)重试没有意义
  • 客户端超时要小于网关超时,否则重试会叠加

限流

Text
HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1761883200

安全清单

  • 强制 HTTPS,禁止把 token 放查询参数
  • 用 OAuth2 / JWT,短期 access token + 可撤销 refresh token
  • 按资源做鉴权(越权是最常见漏洞),不要只校验「登录了」
  • 限制请求体大小,校验 Content-Type
  • 日志脱敏:手机号、身份证、token 一律打码

Friends & Partners