RESTApiDesign
完整的 REST API 设计指南
专业 REST API 设计原则、历史和最佳实践的综合指南。
本文档总结了 RESTful 架构背后的关键思想以及如何设计干净、可扩展且对开发人员友好的 API。
概述
API设计是后端工程师最关键的技能之一。
好的 API 不仅仅是功能 - 它们是关于创建其他开发人员可以轻松理解和集成的清晰、直观和标准化的界面。
本指南重点介绍使用 REST(表述性状态传输) 架构风格设计 API。
网络简史
1990 年 — 网络的诞生
蒂姆·伯纳斯·李在 CERN 工作期间发明了 万维网。
他介绍了当今网络的三项基本技术:
1.URI(统一资源标识符)
URI 标识互联网上的资源。
例子:
1 | https://api.example.com/users/10 |
这里:
/users→ 资源集合/10→ 特定资源
这代表 ID = 10 的用户。
2. HTTP(超文本传输协议)
HTTP 定义客户端和服务器如何通过网络进行通信。
常见的HTTP方法:
| 方法 | 目的 |
|---|---|
| 获取 | 检索数据 |
| 发布 | 创建数据 |
| 放置 | 替换数据 |
| 补丁 | 更新部分数据 |
| 删除 | 删除数据 |
3. HTML
HTML 定义了信息在浏览器中的显示方式。
但是,API 通常返回 JSON 而不是 HTML。
JSON 响应示例:
1 | { |
HTTP 1.1 改进
后来,Roy Fielding 和 Tim Berners-Lee 致力于改进 HTTP。
重要改进包括:
持久连接
更好的缓存支持
提高可扩展性
这些改进使得构建大型分布式系统和现代 API 成为可能。
REST — 2000 年引入
2000 年,Roy Fielding 发表了他的博士论文,在论文中他定义了 REST 架构风格。
REST 鼓励开发人员从资源而不是操作的角度进行思考。
糟糕的设计(基于操作的 API)
1 | /createUser |
这种方法将 API 端点视为函数
良好的 REST 设计(基于资源)
1 | POST /users |
用户就是资源
HTTP 方法定义操作
6 个 REST 约束
Roy Fielding 定义了使系统 RESTful 的六个约束。
1. 客户端-服务器架构
客户端和服务器必须是单独的系统。
|组件| 角色|
|客户| 前端/移动应用/浏览器|
|服务器| 后端/数据库/业务逻辑|
这种分离提高了可扩展性和灵活性。
2.无状态
每个请求必须包含处理它所需的所有信息。
服务器不存储请求之间的会话状态。
1 | GET /users |
3. 可缓存
响应应表明它们是否可以被缓存。
缓存通过减少不必要的服务器请求来提高性能。
示例标题:
1 | Cache-Control: max-age=3600 |
含义:
响应可以缓存 1 小时。
4. 统一接口
这是最重要的 REST 约束。
API 必须遵循一致的规则和可预测的模式。
示例:
|操作| 端点|
|获取所有用户| 获取/用户|
|获取一名用户| 获取 /users/{id}|
|创建用户| 发布/用户|
|更新用户| PUT /用户/ {id} |
|删除用户| 删除 /users/{id}|
5.分层系统
客户不应该知道他们是否正在与:
实际服务器
负载均衡器
代理
API网关
一个微服务
这种抽象提高了安全性和可扩展性。
6. 按需编码(可选)
服务器可以向客户端发送可执行代码。
示例:
JavaScript 发送到浏览器
但是,大多数 API 不使用此约束,因此它被认为是可选的。
典型的 url 是如何制作的:-
1 | https://sriniously.xyz/blog/zist/?q=something#header |
https:
传输协议.完整形式:安全超文本传输协议
它定义了浏览器如何与服务器通信。
使用 TLS/SSL 加密来保护数据。
sriniously.xyz : 域名
这是服务器的人类可读地址。
它使用 DNS 映射到 IP 地址。
1 | sriniously.xyz |
/blog/zist/ :资源路径
这告诉服务器我们想要哪个资源/页面。
?q=某事 :
查询参数将额外的数据发送到服务器。
用法示例:
搜索查询
过滤器
分页
#标题:
片段不会发送到服务器。
它告诉浏览器滚动到页面中的特定部分。
HTML 示例
1 | <h1 id="header">Title</h1> |
|组件|价值|
|传输协议| https |
|域名 | sriniously.xyz |
|资源路径| /博客/zist/ |
|查询参数| q=某物|
|片段| #标题|
核心设计原则
端点的命名方式决定了 API 的可预测性。
- 使用复数名词: 集合时始终使用复数。
- ✅
/users - ❌
/user
- ✅
当我们想要访问单个用户时,我们仍然使用 /users,因为我们正在从用户资源中检索特定文档。
为了访问特定文档,我们通常使用 ID 或 slug。
slug 是一种 URL 友好的标识符,以可读格式表示资源。
Slug 通常以小写形式书写,如果存在多个单词,则用下划线分隔它们。
1 | /api/v1/book/harry_potter |
在这里,harry_potter 是唯一标识这本书的 slug。
- 避免缩写: 保持字段直观且可读。
- ✅
description,category_id
*❌desc, `cat_id
- ✅
2. HTTP Methods (Verbs)
| Method | Action | Use Case | Idempotency/Non-Idempptency |
|---|---|---|---|
| GET | Read | Fetch a resource or collection. | Idempotent |
| POST | Create | Create a new resource. | Non-Idempotent |
| PUT | Replace | Update a resource entirely. | Idempotent |
| PATCH | Modify | Update specific fields of a resource. | Idempotent |
| DELETE | Remove | Delete a resource. | Idempotent |
Steps to design a api
- Design the UI :- The first step in API design is to design the user interface using tools such as Figma, Adobe XD, or any wireframing tool.
Designing the UI helps us understand:
What data the frontend needs
How the data will be displayed
What user interactions will occur (forms, buttons, filters, etc.)
- Identify the Resources from the Frontend Design :- Once the UI and frontend flows are designed, we can analyze them to determine the resources required by the application.
A resource represents a key entity in the system, such as:
users
books
orders
payments
products
By studying the frontend screens, we can identify:
What resources exist
What operations need to be performed on them (create, read, update, delete)
How the frontend will request the data
Task to do while developing apis :-
1. Design-First Documentation
Before writing a single line of code, design your API interface. Use interactive documentation tools like Swagger (OpenAPI) or Postman.
- Goal: Create a “contract” that frontend and backend teams can agree upon.
- Benefit: Allows for mocking and testing the interface logic without waiting for the full implementation.
2. Intuitive & Consistent Design
An API is a product. If it’s consistent, it becomes predictable and easy to learn.
- Plural Nouns: Use
/usersinstead of/user. - Standard Verbs: Stick to HTTP methods strictly (
GET,POST,PUT,PATCH__INLINE_ CODE_9__DELETE). - Consistency: If you use
camelCasefor one JSON response, use it for all of them.
3. Provide Sane Defaults
Don’t force the client to provide every single detail if the server can make a logical assumption.
- Example: * If a user creates a profile and leaves the
statusblank, default it toactive.- If a search request omits
limit, default it to10__INLI NE_CODE_15__20instead of returning 0 or 1,000,000 records.
- If a search request omits
4. Avoid Abbreviations
Prioritize readability over brevity. Short names save bytes but cost developer time in confusion.
- ✅ Do:
description,transaction_id,created_at - ❌ Don’t:
desc__INLINE_COD E_20__txn_id,ca_dt
📊 Summary of Implementation
| Task | Action Item | Example |
|---|---|---|
| Documentation | Use Swagger/OpenAPI | http://api.yoursite.com/docs |
| Consistency | Use Plural Nouns | /organizations |
| Logic | Set Default Values | status: “待处理” by default |
| Clarity | Full Descriptive Names | is_authenticated vs is_auth |