rest-conventions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

REST Conventions

REST 规范

Overview

概述

Use HTTP methods correctly. GET for reads. POST for creates. PUT/PATCH for updates. DELETE for deletes.
REST conventions exist for caching, bookmarking, and semantic clarity. Violating them breaks HTTP infrastructure.
正确使用HTTP方法:GET用于读取,POST用于创建,PUT/PATCH用于更新,DELETE用于删除。
REST规范的存在是为了实现缓存、书签功能以及语义清晰性。违反这些规范会破坏HTTP基础设施。

When to Use

适用场景

  • Designing any HTTP API endpoint
  • Asked to use POST for fetching data
  • Naming endpoints with verbs
  • Unsure which HTTP method to use
  • 设计任何HTTP API端点时
  • 被要求使用POST获取数据时
  • 用动词命名端点时
  • 不确定应使用哪种HTTP方法时

The Iron Rule

铁律

NEVER use POST for read operations. NEVER put verbs in URLs.
No exceptions:
  • Not for "it's simpler"
  • Not for "we need a body"
  • Not for "that's how we do it"
  • Not for "GET URLs are limited"
NEVER use POST for read operations. NEVER put verbs in URLs.
无例外:
  • 不要以“实现更简单”为借口
  • 不要以“我们需要请求体”为借口
  • 不要以“我们一直这么做”为借口
  • 不要以“GET URL长度有限”为借口

Detection: REST Violation Smell

检测:REST规范违规迹象

If endpoints have verbs or wrong methods, STOP:
typescript
// ❌ VIOLATIONS
POST /getOrders              // POST for read
POST /users/create           // Verb in URL
GET /deleteUser?id=123       // GET for delete
POST /api/fetchProducts      // Verb + wrong method
如果端点包含动词或使用了错误的方法,请立即停止:
typescript
// ❌ 违规示例
POST /getOrders              // 用POST执行读取操作
POST /users/create           // URL中包含动词
GET /deleteUser?id=123       // 用GET执行删除操作
POST /api/fetchProducts      // 包含动词且使用错误方法

The Correct Pattern: RESTful Endpoints

正确范式:RESTful端点

typescript
// ✅ CORRECT: RESTful design

// Collections: plural nouns
GET    /users          // List users
POST   /users          // Create user
GET    /users/:id      // Get one user
PUT    /users/:id      // Replace user
PATCH  /users/:id      // Update user partially
DELETE /users/:id      // Delete user

// Nested resources
GET    /users/:id/orders     // User's orders
POST   /users/:id/orders     // Create order for user
GET    /orders/:id           // Get specific order

// Filtering via query params
GET    /orders?status=pending&userId=123
GET    /products?category=electronics&limit=20
typescript
// ✅ 正确示例:RESTful设计

// 集合使用复数名词
GET    /users          // 列出所有用户
POST   /users          // 创建用户
GET    /users/:id      // 获取单个用户
PUT    /users/:id      // 替换用户信息
PATCH  /users/:id      // 部分更新用户信息
DELETE /users/:id      // 删除用户

// 嵌套资源
GET    /users/:id/orders     // 获取指定用户的订单
POST   /users/:id/orders     // 为指定用户创建订单
GET    /orders/:id           // 获取指定订单

// 通过查询参数过滤
GET    /orders?status=pending&userId=123
GET    /products?category=electronics&limit=20

HTTP Methods Semantics

HTTP方法语义

MethodUse ForIdempotentSafe
GETRead/fetchYesYes
POSTCreateNoNo
PUTReplace entirelyYesNo
PATCHPartial updateYesNo
DELETERemoveYesNo
Safe: Doesn't modify state Idempotent: Same result if called multiple times
方法适用场景幂等安全
GET读取/获取
POST创建
PUT完全替换
PATCH部分更新
DELETE删除
安全:不会修改系统状态 幂等:多次调用可得到相同结果

Common Patterns

常见范式

Filtering

过滤

typescript
GET /orders?status=pending
GET /products?minPrice=10&maxPrice=100
GET /users?role=admin&active=true
typescript
GET /orders?status=pending
GET /products?minPrice=10&maxPrice=100
GET /users?role=admin&active=true

Pagination

分页

typescript
GET /orders?page=2&limit=20
GET /orders?cursor=abc123&limit=20
typescript
GET /orders?page=2&limit=20
GET /orders?cursor=abc123&limit=20

Sorting

排序

typescript
GET /products?sort=price:asc
GET /users?sort=createdAt:desc
typescript
GET /products?sort=price:asc
GET /users?sort=createdAt:desc

Actions on Resources

资源操作

For actions that don't fit CRUD, use sub-resources:
typescript
POST /orders/:id/cancel     // Action on order
POST /users/:id/verify      // Action on user
POST /payments/:id/refund   // Action on payment
对于不适合CRUD的操作,使用子资源:
typescript
POST /orders/:id/cancel     // 取消订单操作
POST /users/:id/verify      // 验证用户操作
POST /payments/:id/refund   // 退款操作

Pressure Resistance Protocol

异议应对指南

1. "POST Is Simpler"

1. “POST更简单”

Pressure: "Just use POST for everything"
Response: POST requests aren't cacheable and break HTTP semantics.
Action: Use the correct method. It's the same amount of code.
质疑:“所有请求都用POST就好”
回应:POST请求不可缓存,且会破坏HTTP语义。
行动:使用正确的方法,代码量其实是一样的。

2. "We Need a Request Body"

2. “我们需要请求体”

Pressure: "GET can't have a body, so we use POST"
Response: Use query parameters for filtering. Bodies on GET are non-standard.
Action:
GET /orders?userId=123
instead of
POST /getOrders
质疑:“GET不能带请求体,所以我们用POST”
回应:使用查询参数进行过滤。GET请求带请求体不符合标准。
行动:使用
GET /orders?userId=123
替代
POST /getOrders

3. "GET URLs Are Limited"

3. “GET URL长度有限”

Pressure: "Query string might get too long"
Response: If your query is that complex, you might need a search endpoint. Or paginate.
Action: For complex searches,
POST /search
is acceptable as an exception.
质疑:“查询字符串可能太长”
回应:如果查询逻辑真的这么复杂,你可能需要一个搜索端点,或者进行分页处理。
行动:对于复杂搜索,
POST /search
可作为例外情况。

4. "That's How We Do It"

4. “我们一直这么做”

Pressure: "Our existing API uses POST for reads"
Response: New endpoints should follow conventions. Migrate old ones gradually.
Action: Follow REST for new endpoints. Document inconsistencies.
质疑:“我们现有的API都是用POST执行读取操作”
回应:新端点应遵循规范,逐步迁移旧端点。
行动:新端点遵循REST规范,记录不一致之处。

Red Flags - STOP and Reconsider

警示信号 - 立即停止并重新考虑

  • Verbs in URLs (
    /getUser
    ,
    /createOrder
    )
  • POST for fetching data
  • GET for mutations
  • Action names instead of resources
  • Inconsistent URL structure
All of these mean: Redesign the endpoint.
  • URL中包含动词(
    /getUser
    ,
    /createOrder
  • 用POST获取数据
  • 用GET执行修改操作
  • 使用操作名称而非资源名称
  • URL结构不一致
出现以上任何一种情况:重新设计端点。

Quick Reference

速查表

BadGood
POST /getOrders
GET /orders
POST /createUser
POST /users
GET /deleteUser/123
DELETE /users/123
POST /updateProduct
PATCH /products/:id
POST /fetchByFilter
GET /items?filter=x
错误示例正确示例
POST /getOrders
GET /orders
POST /createUser
POST /users
GET /deleteUser/123
DELETE /users/123
POST /updateProduct
PATCH /products/:id
POST /fetchByFilter
GET /items?filter=x

Common Rationalizations (All Invalid)

常见借口(均不成立)

ExcuseReality
"POST is simpler"Same code, better semantics.
"Need request body"Use query parameters.
"GET URLs too long"Paginate or use search endpoint.
"That's how we do it"New code should be correct.
"Doesn't matter"Caching, bookmarking, tools all depend on it.
借口实际情况
“POST更简单”代码量相同,但语义更清晰。
“需要请求体”使用查询参数即可。
“GET URL太长”进行分页或使用搜索端点。
“我们一直这么做”新代码应遵循正确规范。
“没关系”缓存、书签、工具都依赖这些规范。

The Bottom Line

核心要点

Nouns in URLs. Correct HTTP methods. Query params for filtering.
GET reads. POST creates. PUT/PATCH updates. DELETE removes. URLs are nouns (resources), not verbs (actions).
URL使用名词,正确使用HTTP方法,用查询参数进行过滤。
GET用于读取,POST用于创建,PUT/PATCH用于更新,DELETE用于删除。URL是名词(资源),而非动词(操作)。