API 接口设计:RESTful 的 10 条黄金法则
API Design — 10 Golden Rules of RESTful APIs
| iDev Team | 2026-08-12T01:35:02
好的 API 像好的产品一样直觉。这 10 条法则帮你设计出前端爱用、文档好写、扩展不痛的 API。
A good API is as intuitive as a good product. These 10 rules help you design APIs that frontends love, docs write easily, and extensions don't hurt.
1. URL 用名词复数/api/articles 而不是 /api/article 或 /api/getArticles。资源是集合概念。2. 用 HTTP 方法语义化GET 只读不改,POST 创建,PUT 全量更新,PATCH 部分更新,DELETE 删除。不要用 POST 做所有事。3. 返回有意义的状态码200 成功,201 创建成功,400 参数错误,401 未认证,403 无权限,404 不存在,500 服务端错误。4. 统一响应格式所有接口返回相同结构 {code, msg, data},前端一套逻辑处理所有响应。5. 分页用 page + size不要用 offset + limit(容易算错),用 page + size 更直觉。返回 total 让前端知道总页数。6. 嵌套资源用 URL 层级/api/articles/1/comments 获取文章 1 的评论,而不是 /api/comments?articleId=1。7. 过滤排序用 Query 参数/api/articles?status=1&sort=created_at&order=desc,保持 URL 简洁。8. 版本控制URL 里加版本号 /api/v1/articles,方便后续不兼容升级时新老版本并存。9. 错误信息要有用{"msg": "标题不能为空"} 比 {"msg": "Bad Request"} 有用 100 倍。10. 写文档接口没有文档等于不存在。用 Swagger/OpenAPI 自动生成,保持文档和代码同步。
1. Plural Noun URLs/api/articles not /api/article or /api/getArticles. Resources are collections.2. Semantic HTTP MethodsGET is read-only, POST creates, PUT fully updates, PATCH partially updates, DELETE removes. Don't use POST for everything.3. Meaningful Status Codes200 success, 201 created, 400 bad request, 401 unauthorized, 403 forbidden, 404 not found, 500 server error.4. Unified Response FormatAll endpoints return the same structure {code, msg, data} — frontend uses one handler for all responses.5. Use page + size for PaginationDon't use offset + limit (easy to miscalculate). page + size is more intuitive. Return total so frontend knows the page count.6. Nested Resources via URL Hierarchy/api/articles/1/comments for article 1's comments, not /api/comments?articleId=1.7. Filter & Sort via Query Params/api/articles?status=1&sort=created_at&order=desc — keep URLs clean.8. Version ControlAdd version to URL /api/v1/articles for smooth backward-incompatible upgrades.9. Useful Error Messages{"msg": "Title cannot be empty"} is 100x more useful than {"msg": "Bad Request"}.10. Write DocumentationAn API without docs might as well not exist. Use Swagger/OpenAPI for auto-generation and keep docs in sync with code.