
规范优先的 API 开发
先编写 OpenAPI 规范,再生成代码——确保文档永不不同步。

OpenAPI 3.1 规范
# openapi.yaml
openapi: 3.1.0
info:
title: User API
version: 1.0.0
paths:
/users:
get:
operationId: listUsers
summary: List all users
parameters:
- name: page
in: query
schema: { type: integer, minimum: 1, default: 1 }
- name: limit
in: query
schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
users:
type: array
items:
$ref: '#/components/schemas/User'
total:
type: integer
post:
operationId: createUser
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserInput'
responses:
'201':
description: Created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'409':
description: Email already taken
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
User:
type: object
required: [id, name, email, createdAt]
properties:
id:
type: string
format: uuid
name:
type: string
minLength: 2
email:
type: string
format: email
createdAt:
type: string
format: date-time
CreateUserInput:
type: object
required: [name, email]
properties:
name:
type: string
minLength: 2
maxLength: 100
email:
type: string
format: email
role:
type: string
enum: [user, admin]
default: user
Error:
type: object
required: [error]
properties:
error:
type: string
使用 Fastify 进行 OpenAPI 验证
import Fastify from 'fastify'
import fastifySwagger from '@fastify/swagger'
import fastifySwaggerUi from '@fastify/swagger-ui'
const app = Fastify({ logger: true })
await app.register(fastifySwagger, {
openapi: {
info: { title: 'User API', version: '1.0.0' },
},
})
await app.register(fastifySwaggerUi, {
routePrefix: '/docs',
})
// Inline JSON Schema (converted from OpenAPI)
app.get('/users', {
schema: {
querystring: {
type: 'object',
properties: {
page: { type: 'integer', minimum: 1, default: 1 },
limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
},
},
response: {
200: {
type: 'object',
properties: {
users: { type: 'array', items: { $ref: '#/components/schemas/User' } },
total: { type: 'integer' },
},
},
},
},
handler: async (request, reply) => {
const { page, limit } = request.query
const [users, total] = await Promise.all([
db.users.findMany({ skip: (page - 1) * limit, take: limit }),
db.users.count(),
])
return { users, total }
},
})
生成 TypeScript 客户端
npx openapi-typescript openapi.yaml -o src/api-types.ts
npx openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o src/api-client
验证中间件(Express)
import { OpenApiValidator } from 'express-openapi-validator'
app.use(
OpenApiValidator.middleware({
apiSpec: './openapi.yaml',
validateRequests: true,
validateResponses: process.env.NODE_ENV !== 'production',
})
)
// 自动验证所有请求是否符合规范!