什么是 OpenAPI 规范?
OpenAPI 规范(原 Swagger 规范)是一种用于描述 RESTful API 的开放标准。 它允许开发者以机器可读的格式定义 API 的路径、参数、请求/响应结构、认证方式等, 从而自动生成交互式文档、客户端 SDK、测试用例等。
核心优势
- 提升前后端协作效率
- 自动生成 API 文档(如 Swagger UI)
- 支持代码生成(多种语言)
- 便于自动化测试与 Mock 服务
- 促进 API 标准化与一致性
基本结构示例(OpenAPI 3.0)
openapi: 3.0.3
info:
title: 用户管理 API
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: 获取用户列表
responses:
'200':
description: 成功返回用户数组
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
最佳实践建议
- 使用语义化的 HTTP 方法(GET/POST/PUT/DELETE)
- 统一错误响应格式
- 为所有端点提供清晰的 summary 和 description
- 合理使用 tags 对接口分组
- 版本控制 API(如 /v1/users)