REST 使用标准的 HTTP method 作为作用于资源的动词。到 CRUD(Create、Read、Update、Delete)的常见映射是:
REST 使用标准的 HTTP method 作为作用于资源的动词。到 CRUD(Create、Read、Update、Delete)的常见映射是:
| CRUD | Method | 典型用途 |
|---|
| Create | POST | 向一个 collection 添加新资源 |
| Read | GET | 获取一个资源或列表 |
| Update(完整) | PUT | 整体替换一个资源 |
| Update(部分) | PATCH | 修改部分字段 |
| Delete | DELETE | 移除一个资源 |
POST /users HTTP/1.1
Content-Type: application/json
{ "name": "Ann", "email": "[email protected]" }
HTTP/1.1 201 Created
Location: /users/42
{ "id": 42, "name": "Ann", "email": "[email protected]" }
PUT /users/42 发送整个 representation 并替换它;PATCH /users/42 只发送要修改的字段(例如 { "email": "[email protected]" })。
这是两个不同的属性:
GET、HEAD、OPTIONS 是 safe 的。GET、PUT、DELETE、HEAD 是 idempotent 的。Method Safe? Idempotent?
GET yes yes
HEAD yes yes
PUT no yes (replacing with the same body twice = same result)
DELETE no yes (deleting twice = still deleted)
PATCH no no* (depends on the patch; not guaranteed)
POST no no (posting twice usually creates two resources)
面试官问这个,是想看你是否足够理解 HTTP 语义以构建可靠的 API。safe/idempotent 的区分并非学术性的:它直接决定 client、proxy 和 CDN 被允许做什么。Safe method 可以被自由缓存和预取;idempotent method 可以在网络超时后被自动 retry,而不冒重复副作用的风险——这就是为什么 client 可以安全地 retry 一个 PUT 或 DELETE,但 retry 一个 POST 时必须小心(它可能创建两个 order)。经典错误是用 GET 触发副作用(例如 GET /users/42/delete),这会破坏缓存并让 crawler 意外地修改数据。选对 method——并尊重它的 safe 与 idempotent 契约——正是让一个 API 可预测、可以放心地围绕它构建工具的原因。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠