Swagger 第一个文档
从零写一份能跑起来的用户接口规范,并在 Swagger Editor 里验证。
Key Points先写 info + servers + 一个 GET 路径,再补 schema;每改一次就看 Editor 右侧的实时预览有没有报错。
第一步:最小可运行
YAML
openapi: 3.0.3
info:
title: User API
version: 1.0.0
description: 一个用来练手的用户服务
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: 用户列表
responses:
'200':
description: 成功
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string第二步:补请求参数
YAML
get:
summary: 用户列表
parameters:
- name: page
in: query
description: 页码,从 1 开始
schema:
type: integer
minimum: 1
default: 1
- name: size
in: query
description: 每页条数
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: 成功第三步:抽出 schema
YAML
components:
schemas:
User:
type: object
required: [id, name]
properties:
id:
type: integer
format: int64
name:
type: string
example: Alice
email:
type: string
format: email
example: alice@example.com
UserList:
type: object
properties:
items:
type: array
items:
$ref: '#/components/schemas/User'
total:
type: integer
page:
type: integer
size:
type: integer校验
Red errors in the Swagger Editor mean the structure is invalid. Validate in CI as well; --fail-on-warnings makes style issues fail the build too.
Bash
# 用 swagger-cli 校验(Node)
npx @apidevtools/swagger-cli validate openapi.yaml
# 或用 spectral 做规范 + 风格检查
npx @stoplight/spectral-cli lint openapi.yaml --fail-severity warnCommon trap: quote the
responses keys ('200'). Unquoted, YAML parses them as integers and some tools either fail or silently drop the entry.第一步:最小可运行
YAML
openapi: 3.0.3
info:
title: User API
version: 1.0.0
description: 一个用来练手的用户服务
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: 用户列表
responses:
'200':
description: 成功
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string第二步:补请求参数
YAML
get:
summary: 用户列表
parameters:
- name: page
in: query
description: 页码,从 1 开始
schema:
type: integer
minimum: 1
default: 1
- name: size
in: query
description: 每页条数
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: 成功第三步:抽出 schema
YAML
components:
schemas:
User:
type: object
required: [id, name]
properties:
id:
type: integer
format: int64
name:
type: string
example: Alice
email:
type: string
format: email
example: alice@example.com
UserList:
type: object
properties:
items:
type: array
items:
$ref: '#/components/schemas/User'
total:
type: integer
page:
type: integer
size:
type: integer校验
Swagger Editor 右侧预览出现红色报错就说明结构不合法;也可以用命令行做 CI 校验。--fail-on-warnings 让风格问题也阻断构建。
Bash
# 用 swagger-cli 校验(Node)
npx @apidevtools/swagger-cli validate openapi.yaml
# 或用 spectral 做规范 + 风格检查
npx @stoplight/spectral-cli lint openapi.yaml --fail-severity warn常见错误:
responses 的键必须加引号('200')。不加引号 YAML 会解析成整数,部分工具直接报错或静默丢字段。