URL Design Specifications

Resource-Oriented URL Design

RESTful API URLs should represent "resources" rather than "actions."

Think of a URL as a library shelf label; it tells you where to find what resources.

Good Design ✅

GET /api/users          # 获取所有用户
GET /api/users/123      # 获取 ID 为 123 的用户
POST /api/users         # 创建新用户
PUT /api/users/123      # 更新用户 123
DELETE /api/users/123   # 删除用户 123

Bad Design ❌

GET /api/getUsers       # 动词出现在 URL 中
POST /api/createUser    # 动作导向而非资源导向
GET /api/user/delete/123 # 混乱的结构

URL Naming Conventions

Use nouns instead of verbs

  • ✅ GET /api/books
  • ❌ GET /api/getBooks

Use plural forms

  • ✅ GET /api/users
  • ❌ GET /api/user

Use lowercase letters

  • ✅ GET /api/user-orders

  • ❌ GET /api/UserOrders

Use hyphens to separate words

  • ✅ GET /api/user-profiles

  • ❌ GET /api/user_profiles

  • ❌ GET /api/userProfiles

Nested Resources

When resources have hierarchical relationships, nested URLs can be used:

// 获取用户 123 的所有订单
GET /api/users/123/orders

// 获取用户 123 的订单 456
GET /api/users/123/orders/456

// 为用户 123 创建新订单
POST /api/users/123/orders

Nested Hierarchy Recommendations

Query Parameters

Used for filtering, sorting, and pagination:

javascript// 分页
GET /api/users?page=1&limit=10

// 过滤
GET /api/users?status=active&city=beijing

// 排序
GET /api/users?sort=created_at&order=desc

// 搜索
GET /api/users?search=张三

API Versioning

To maintain backward compatibility, APIs need versioning:

URL Path Versioning

GET /api/v1/users
GET /api/v2/users

Request Header Versioning

GET /api/users
Accept: application/vnd.api+json;version=1
Other Extensions