# 10 章 · 综合实战代码

一份生产级的电商 API 完整 OpenAPI 文档 + 一键启动的开发环境。

## 文件清单

```
code/
├── openapi.yaml              ← 800 行完整文档（认真读完一次能学很多）
├── docker-compose.yml        ← 一键起 4 个服务
└── README.md                 ← 本文
```

## 快速开始

### 1. 启动全套服务

```bash
docker compose up -d
```

四个服务一键就绪：

| 服务            | 地址                          | 用途                 |
| --------------- | ----------------------------- | -------------------- |
| Swagger UI      | http://localhost:8080         | 在线浏览 API 文档     |
| Swagger Editor  | http://localhost:8081         | 在浏览器编辑 yaml     |
| Prism Mock      | http://localhost:4010         | Mock API 服务         |
| Redoc           | http://localhost:8082         | 漂亮的发布版文档      |

### 2. 调用 Mock API 试试

```bash
# 商品列表（公开接口）
curl http://localhost:4010/v1/products

# 登录拿 token
curl -X POST http://localhost:4010/v1/auth/login \
  -H 'content-type: application/json' \
  -d '{"email":"alice@x.com","password":"s3cret"}'

# 拿 token 调需要鉴权的接口
curl http://localhost:4010/v1/me \
  -H 'authorization: Bearer fake-token-for-mock'

# Prism 会自动按 schema 校验请求体
curl -X POST http://localhost:4010/v1/auth/login \
  -H 'content-type: application/json' \
  -d '{"email":"not-an-email"}'
# → 返回 422，提示 email 格式错误
```

### 3. 给前端生成 SDK

```bash
docker run --rm -v $PWD:/local \
  openapitools/openapi-generator-cli generate \
  -i /local/openapi.yaml \
  -g typescript-axios \
  -o /local/sdk-ts
```

### 4. 给后端生成接口骨架

```bash
# Spring Boot
docker run --rm -v $PWD:/local \
  openapitools/openapi-generator-cli generate \
  -i /local/openapi.yaml \
  -g spring \
  -o /local/server-spring \
  --additional-properties=interfaceOnly=true,useSpringBoot3=true

# Node.js Express
docker run --rm -v $PWD:/local \
  openapitools/openapi-generator-cli generate \
  -i /local/openapi.yaml \
  -g nodejs-express-server \
  -o /local/server-node
```

### 5. 静态文档发布

```bash
npx -y @redocly/cli build-docs openapi.yaml -o public/api.html
# public/api.html 是单文件，扔到任何静态服务器都能用
```

## 学习建议

1. **先用 Swagger UI 浏览全部接口**（http://localhost:8080），有个全局印象
2. **打开 openapi.yaml**，对照看每个接口对应哪段 yaml
3. **试着改 yaml 加字段** —— 比如给 `Product` 加一个 `tags: array`
4. **用 codegen 生成自己感兴趣语言的 SDK**，看下生成的代码长啥样
5. **接入到自己的项目**，把 yaml 当真理之源

## 工程检查清单

- [ ] 用 `npx @stoplight/spectral-cli lint openapi.yaml` 检查 yaml 质量
- [ ] CI 里跑 openapi-diff，PR 自动检测 breaking change
- [ ] 给每个 operation 起好 operationId，让生成的方法名漂亮
- [ ] 用 components 把模型 / 参数 / 响应都抽出来复用
- [ ] 自动化部署 Redoc 到内部 wiki / GitHub Pages
- [ ] 配合 schemathesis 跑模糊测试，确保后端真的符合 yaml
