API 版本管理策略:URL vs Header vs Query

API 版本管理策略:URL vs Header vs Query

API 设计 2026-06-27 10 分钟

API 版本管理策略:URL vs Header vs Query

API 版本管理是后端开发的重要课题。本文介绍三种版本管理策略。

1. URL 版本

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

优点: 简单直观 缺点: URL 变化,需要维护多份路由

2. Header 版本

GET /api/users
Accept: application/vnd.api.v1+json

优点: URL 不变 缺点: 不直观,需要工具支持

3. Query 参数版本

GET /api/users?version=1

优点: 简单 缺点: 不规范

Spring Boot 实现

// URL 版本
@RestController
@RequestMapping("/api/v1/users")
public class UserControllerV1 {}

@RestController
@RequestMapping("/api/v2/users")
public class UserControllerV2 {}

// Header 版本
@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping(headers = "X-API-VERSION=1")
    public UserV1 getUserV1() {}
    
    @GetMapping(headers = "X-API-VERSION=2")
    public UserV2 getUserV2() {}
}

最佳实践

  1. URL 版本最常用:简单直观
  2. 保持向后兼容:新版本兼容旧版本
  3. 文档化:每个版本的变更都要记录
  4. 废弃策略:给用户足够的迁移时间

总结

API 版本管理没有银弹。根据团队和项目选择合适的策略,保持一致性最重要。

📚 相关文章