Skip to content

API接口文档 ​

API接口文档描述了系统对外提供的接口规范,是前后端协作的基础。掌握API接口文档的编写方法和规范,能够提高团队协作效率。

📋 文档类型 ​

1. Swagger/OpenAPI 文档 ​

Swagger/OpenAPI 是目前最流行的API文档标准,支持代码自动生成和在线测试。

文档分类:

2. RESTful API 文档 ​

RESTful API 遵循 REST 架构风格,使用标准的 HTTP 方法。

参考资源:

📝 Swagger/OpenAPI 文档示例 ​

1. OpenAPI 3.0 基础示例 ​

yaml
openapi: 3.0.0
info:
  title: 用户服务 API
  version: 1.0.0
  description: 用户服务接口文档
  contact:
    name: API 支持
    email: api@example.com
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html

servers:
  - url: https://api.example.com/v1
    description: 生产环境
  - url: https://api-dev.example.com/v1
    description: 开发环境
  - url: http://localhost:8080/v1
    description: 本地环境

paths:
  /users:
    get:
      summary: 获取用户列表
      description: 分页查询用户列表,支持按姓名和邮箱搜索
      operationId: getUsers
      tags:
        - 用户管理
      parameters:
        - name: page
          in: query
          description: 页码,从1开始
          required: false
          schema:
            type: integer
            default: 1
            minimum: 1
        - name: size
          in: query
          description: 每页数量
          required: false
          schema:
            type: integer
            default: 20
            minimum: 1
            maximum: 100
        - name: name
          in: query
          description: 用户姓名(模糊搜索)
          required: false
          schema:
            type: string
        - name: email
          in: query
          description: 用户邮箱(精确搜索)
          required: false
          schema:
            type: string
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserListResponse'
              examples:
                success:
                  value:
                    code: 200
                    message: success
                    data:
                      items:
                        - id: 1
                          name: 张三
                          email: zhangsan@example.com
                      total: 100
                      page: 1
                      size: 20
        '400':
          description: 请求参数错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: 服务器错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
    
    post:
      summary: 创建用户
      description: 创建新用户,邮箱必须唯一
      operationId: createUser
      tags:
        - 用户管理
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
            examples:
              example1:
                value:
                  name: 张三
                  email: zhangsan@example.com
                  phone: 13800138000
      responses:
        '201':
          description: 创建成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: 请求参数错误或邮箱已存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /users/{id}:
    get:
      summary: 获取用户详情
      description: 根据用户ID获取用户详细信息
      operationId: getUserById
      tags:
        - 用户管理
      parameters:
        - name: id
          in: path
          description: 用户ID
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: 用户不存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

    put:
      summary: 更新用户信息
      description: 完整更新用户信息
      operationId: updateUser
      tags:
        - 用户管理
      parameters:
        - name: id
          in: path
          description: 用户ID
          required: true
          schema:
            type: integer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateUserRequest'
      responses:
        '200':
          description: 更新成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: 用户不存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

    delete:
      summary: 删除用户
      description: 根据用户ID删除用户
      operationId: deleteUser
      tags:
        - 用户管理
      parameters:
        - name: id
          in: path
          description: 用户ID
          required: true
          schema:
            type: integer
      responses:
        '204':
          description: 删除成功
        '404':
          description: 用户不存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

components:
  schemas:
    User:
      type: object
      description: 用户信息
      properties:
        id:
          type: integer
          description: 用户ID
          example: 1
        name:
          type: string
          description: 用户名称
          example: 张三
        email:
          type: string
          format: email
          description: 用户邮箱
          example: zhangsan@example.com
        phone:
          type: string
          description: 手机号码
          example: 13800138000
        createdAt:
          type: string
          format: date-time
          description: 创建时间
          example: 2024-01-01T00:00:00Z
        updatedAt:
          type: string
          format: date-time
          description: 更新时间
          example: 2024-01-01T00:00:00Z

    CreateUserRequest:
      type: object
      required:
        - name
        - email
      properties:
        name:
          type: string
          description: 用户名称
          minLength: 1
          maxLength: 100
          example: 张三
        email:
          type: string
          format: email
          description: 用户邮箱
          example: zhangsan@example.com
        phone:
          type: string
          description: 手机号码
          pattern: '^1[3-9]\d{9}$'
          example: 13800138000

    UpdateUserRequest:
      type: object
      properties:
        name:
          type: string
          description: 用户名称
          minLength: 1
          maxLength: 100
        phone:
          type: string
          description: 手机号码
          pattern: '^1[3-9]\d{9}$'

    UserListResponse:
      type: object
      properties:
        code:
          type: integer
          description: 响应码
          example: 200
        message:
          type: string
          description: 响应消息
          example: success
        data:
          type: object
          properties:
            items:
              type: array
              items:
                $ref: '#/components/schemas/User'
            total:
              type: integer
              description: 总记录数
              example: 100
            page:
              type: integer
              description: 当前页码
              example: 1
            size:
              type: integer
              description: 每页数量
              example: 20

    ErrorResponse:
      type: object
      properties:
        code:
          type: integer
          description: 错误码
          example: 400
        message:
          type: string
          description: 错误消息
          example: 请求参数错误
        timestamp:
          type: string
          format: date-time
          description: 错误时间
          example: 2024-01-01T00:00:00Z
        path:
          type: string
          description: 请求路径
          example: /api/v1/users

  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT Token认证

security:
  - BearerAuth: []

2. Spring Boot 集成 Swagger ​

2.1 添加依赖 ​

xml
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>

2.2 配置类 ​

java
@Configuration
@OpenAPIDefinition(
    info = @Info(
        title = "用户服务 API",
        version = "1.0.0",
        description = "用户服务接口文档",
        contact = @Contact(
            name = "API 支持",
            email = "api@example.com"
        )
    ),
    servers = {
        @Server(url = "https://api.example.com/v1", description = "生产环境"),
        @Server(url = "https://api-dev.example.com/v1", description = "开发环境")
    }
)
public class OpenApiConfig {
    
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .components(new Components()
                .addSecuritySchemes("BearerAuth",
                    new SecurityScheme()
                        .type(SecurityScheme.Type.HTTP)
                        .scheme("bearer")
                        .bearerFormat("JWT")
                )
            )
            .addSecurityItem(new SecurityRequirement().addList("BearerAuth"));
    }
}

2.3 Controller 示例 ​

java
@RestController
@RequestMapping("/api/v1/users")
@Tag(name = "用户管理", description = "用户管理相关接口")
@SecurityRequirement(name = "BearerAuth")
public class UserController {
    
    @GetMapping
    @Operation(summary = "获取用户列表", description = "分页查询用户列表")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    public ResponseEntity<UserListResponse> getUsers(
        @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
        @Parameter(description = "每页数量") @RequestParam(defaultValue = "20") Integer size,
        @Parameter(description = "用户姓名") @RequestParam(required = false) String name
    ) {
        // 实现逻辑
        return ResponseEntity.ok(response);
    }
    
    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public ResponseEntity<User> createUser(
        @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "用户信息")
        @Valid @RequestBody CreateUserRequest request
    ) {
        // 实现逻辑
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }
}

3. API 文档工具对比 ​

工具优点缺点适用场景
Swagger UI界面美观、交互友好需要代码注解Java 项目
Postman功能强大、支持测试需要手动维护API 测试
Apifox全流程协作商业软件团队协作
YAPI免费开源界面一般中小团队

参考资源:

📚 API 设计规范 ​

1. URL 设计规范 ​

markdown
## 基本原则

1. **使用名词,不使用动词**
   - ✅ `/users` 获取用户列表
   - ❌ `/getUsers` 

2. **使用复数形式**
   - ✅ `/users`
   - ❌ `/user`

3. **使用小写字母**
   - ✅ `/user-profiles`
   - ❌ `/UserProfiles`

4. **使用连字符分隔单词**
   - ✅ `/user-profiles`
   - ❌ `/user_profiles`

5. **避免深层嵌套**
   - ✅ `/users/{id}/orders`
   - ❌ `/users/{id}/orders/{orderId}/items/{itemId}`

2. HTTP 方法使用 ​

方法用途是否幂等示例
GET查询资源是GET /users
POST创建资源否POST /users
PUT完整更新资源是PUT /users/
PATCH部分更新资源否PATCH /users/
DELETE删除资源是DELETE /users/

3. 状态码规范 ​

markdown
## 常用状态码

- **200 OK**:请求成功
- **201 Created**:创建成功
- **204 No Content**:删除成功,无返回内容
- **400 Bad Request**:请求参数错误
- **401 Unauthorized**:未认证
- **403 Forbidden**:未授权
- **404 Not Found**:资源不存在
- **409 Conflict**:资源冲突(如邮箱已存在)
- **500 Internal Server Error**:服务器错误
- **503 Service Unavailable**:服务不可用

4. 响应格式规范 ​

统一响应格式 ​

json
{
  "code": 200,
  "message": "success",
  "data": {},
  "timestamp": 1640995200000,
  "requestId": "550e8400-e29b-41d4-a716-446655440000"
}

分页响应格式 ​

json
{
  "code": 200,
  "message": "success",
  "data": {
    "items": [],
    "pagination": {
      "page": 1,
      "size": 20,
      "total": 100,
      "totalPages": 5
    }
  }
}

错误响应格式 ​

json
{
  "code": 400,
  "message": "请求参数错误",
  "errors": [
    {
      "field": "email",
      "message": "邮箱格式不正确"
    }
  ],
  "timestamp": 1640995200000,
  "path": "/api/v1/users"
}

📖 学习资源 ​

视频教程 ​

书籍推荐 ​

  • 《RESTful Web APIs》 - Leonard Richardson, Mike Amundsen
  • 《HTTP权威指南》 - David Gourley, Brian Totty
  • 《API设计模式》 - JJ Geewax
  • 《Web API设计》 - Mike Amundsen

网站资源 ​

在线工具 ​

✅ 文档检查清单 ​

  • [ ] API 文档结构完整
  • [ ] 接口描述清晰准确
  • [ ] 请求参数说明详细
  • [ ] 响应格式规范统一
  • [ ] 错误码定义完整
  • [ ] 提供示例代码
  • [ ] 支持在线测试
  • [ ] 版本管理规范
  • [ ] 及时更新维护

上一章节:架构设计文档
下一章节:文档维护规范
返回目录:文档能力