OpenAPI 规范驱动开发:从接口文档到代码生成的完整工作流
OpenAPI Specification Driven Development: From API Docs to Code Generation
| Alex | 2026-09-12T20:12:00
我们团队用 OpenAPI 规范来驱动前后端开发,接口文档就是单一真相源。前端自动生成类型定义和请求函数,后端自动生成 Controller 骨架。
Our team uses OpenAPI spec as the single source of truth for frontend-backend development, with auto-generated types, request functions, and controller skeletons.
前后端联调最烦的事情是什么?接口文档跟实际代码不一致。后端改了字段名没说,前端按旧文档写代码,联调的时候才发现对不上。我们的解决方案是用 OpenAPI 规范作为单一真相源。 工作流 后端先写 OpenAPI 规范(YAML 文件),定义接口的 URL、参数、响应格式 前端从 OpenAPI 规范自动生成 TypeScript 类型定义和请求函数 后端从 OpenAPI 规范生成 Controller 接口骨架 双方各自实现,联调时基本不会有不一致 OpenAPI 规范示例 paths: /api/users/{id}: get: operationId: getUserById parameters: - name: id in: path required: true schema: type: integer responses: '200': content: application/json: schema: $ref: '#/components/schemas/User' components: schemas: User: type: object required: [id, username, email] properties: id: type: integer username: type: string maxLength: 50 email: type: string format: email 前端代码生成 用 openapi-typescript + openapi-fetch 自动生成: # 生成 TypeScript 类型 npx openapi-typescript api-spec.yaml -o src/api/types.ts # 类型安全的请求 import createClient from 'openapi-fetch'; import type { paths } from './types'; const client = createClient<paths>({ baseUrl: '/api' }); const { data } = await client.GET('/api/users/{id}', { params: { path: { id: 1 } } }); // data 自动推导为 User 类型 效果 推行三个月后,前后端联调时的接口不一致问题基本消失了。而且因为类型是自动生成的,前端的类型安全性也提高了很多,编辑器的自动补全效果很好。
The worst part of frontend-backend collaboration is documentation-code inconsistency. We solved it with OpenAPI as the single source of truth. Workflow Backend writes OpenAPI spec → Frontend auto-generates TypeScript types and request functions → Backend generates controller skeletons → Both implement independently. Result After three months, API inconsistency issues during integration virtually disappeared.