OpenAPI 规范(OAS)最精简、最实用基础教程
(2025 年主流版本:OpenAPI 3.0.3 和 3.1.0,重点掌握 3.1,兼容 3.0)
一、一句话记住 OpenAPI 文件的本质
一个 OpenAPI 文件(YAML 或 JSON)就是用标准格式描述“我这个服务有哪些接口、参数怎么传、返回什么、要不要登录”的一份“接口合同”。
二、最小可运行的 OpenAPI 3.1 示例(直接复制就能用)
openapi: 3.1.0 # 必须写版本,推荐 3.1.0
info:
title: 我的商城 API
version: 1.0.0
description: 一个简单电商示例
contact:
name: 张三
email: zhangsan@example.com
servers: # 环境地址(可多个)
- url: https://api.myshop.com/v1
description: 生产环境
- url: http://localhost:8080
description: 本地开发
paths: # 所有接口路径
/users/{id}: # 路径参数用 { }
get: # HTTP 方法
summary: 根据ID查询用户
operationId: getUserById # 唯一ID,生成代码时有用
parameters:
- name: id # 路径参数
in: path
required: true
schema:
type: integer
- name: detail # 查询参数
in: query
schema:
type: boolean
default: false
responses:
'200': # 状态码
description: 成功返回用户
content:
application/json:
schema:
$ref: '#/components/schemas/User' # 引用下面定义的模型
'404':
description: 用户不存在
components:
schemas: # 数据模型(相当于 Java 的 DTO)
User:
type: object
required: # 必填字段
- id
- username
properties:
id:
type: integer
example: 1001
username:
type: string
example: xiaoming
email:
type: string
format: email
nullable: true # 允许为 null(3.1 新特性)
createdAt:
type: string
format: date-time
把上面内容保存为 openapi.yaml → 打开 https://editor.swagger.io 粘贴 → 立刻看到美观的交互文档。
三、OpenAPI 核心结构速记(背会这 7 行)
openapi: 3.1.0
info: → 标题、版本、描述、联系人
servers: → 多个环境地址
paths: → 所有接口(/users、/orders/{id} ...)
components:
schemas: → 数据模型(User、Order、PageResult...)
parameters: → 可复用的参数
responses: → 可复用的响应
securitySchemes: → 认证方式(Bearer、ApiKey等)
security: → 全局默认认证(可被单个接口覆盖)
四、最常用的 8 个关键字段(90% 的场景都靠它们)
| 位置 | 字段 | 含义 & 常用写法 |
|---|---|---|
| 根 | openapi | 3.0.3 或 3.1.0 |
| info | title / version | 文档标题和版本 |
| paths | /xxx/{id} | 路径参数用 {} |
| parameters | in: path/query/header | 参数位置 |
| parameters.schema | type / format | string、integer、boolean、date-time、email |
| requestBody | content.application/json.schema | 请求体结构 |
| responses.’200′ | content.application/json.schema | 返回结构 |
| components.schemas | type: object + properties + required | DTO 模型 |
五、认证方式最常用写法(2025 主流)
components:
securitySchemes:
bearerAuth: # 名字随便取
type: http
scheme: bearer
bearerFormat: JWT # 可选,说明是JWT
apiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
# 全局开启(整个API都需要登录)
security:
- bearerAuth: []
六、3.1 vs 3.0 最大区别(2025 必知)
| 特性 | OpenAPI 3.0 | OpenAPI 3.1(2025 主推) |
|---|---|---|
| JSON Schema 版本 | 基于 draft-05 | 完整支持 JSON Schema 2020-12 |
| nullable | 要写 nullable: true | 直接 type: string + nullable: true |
| oneOf / anyOf / allOf | 支持但不完整 | 完整支持,类型更强大 |
| 路径参数支持正则 | 不支持 | 支持 pattern |
七、推荐学习资源(直接点开就能用)
- 官方规范(中文)
https://spec.openapis.org/zh-CN/ - 在线编辑器(每天必开)
https://editor.swagger.io - 3.1 完整模板(收藏)
https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.1/non-oauth-petstore.yaml
记住了上面这份“最小可运行示例 + 7 大结构 + 8 个关键字段”,你就已经掌握了 OpenAPI 规范 80% 的日常使用,后面所有高级用法都是在这上面扩展的。需要我发你一个包含分页、上传文件、多种认证的完整 3.1 模板吗?