用 JSON 进行 API 设计:版本、错误与分页策略
2025-11-21#API#JSON#Design
API 设计的核心是“稳定与清晰”。以 JSON 为载体时,字段命名与错误模型直接影响调用者成本。本文总结实践经验,帮助你在迭代中保持契约可靠。
字段命名
遵循语义清晰与一致性:使用 snake_case 或 camelCase 统一风格;布尔字段以 is/has 开头;时间统一 ISO 8601 字符串,避免多格式并存。
错误模型
推荐结构:
{ "code": "INVALID_PARAM", "message": "price must be positive", "details": { "field": "price" } }
将可读信息与机器可解析的错误码同时提供,便于日志检索与用户提示。避免隐藏错误,鼓励可恢复的失败。
分页与排序
为列表接口提供 page/size/sort/order,返回总数与下一页标识。大数据量下可采用游标分页并限制上限,减少深度翻页带来的性能问题。
版本化
当破坏性变更不可避免时,引入显式版本:路径版本(/v2/)或头部版本;在过渡期提供兼容层与迁移文档,降低使用者成本。
性能与安全
避免过度包含冗余字段;对敏感信息进行最小披露并脱敏。请求体与响应体应控制大小,必要时引入压缩与增量传输策略。
总结
稳定的 API 源于“明确约定 + 可度量的质量保障”。以 JSON 为载体时,只要契约清晰与演进策略得当,你的接口就能在迭代中保持可控与可靠。
Related articles
Working with Large JSON Files - A Practical Guide
Techniques and tools for handling JSON files that exceed memory limits or browser constraints.
JSON vs XML - Choosing the Right Format for Your Use Case
A comprehensive comparison of JSON and XML to help you make informed format decisions.
JSON Tools Ecosystem - A Comprehensive Overview
Explore the best tools, libraries, and utilities for working with JSON across different platforms and use cases.
JSON Security Best Practices - Protecting Your Applications
Essential security measures for handling JSON data safely and preventing common vulnerabilities.
Understanding JSON Schema - A Complete Guide
Learn how to define and validate JSON structure with JSON Schema, from basics to advanced features.
JSON Performance Optimization Techniques
Speed up JSON parsing, serialization, and processing with these proven optimization strategies.