
FastAPI是什么?快速上手指南
OpenAPI 規范
Swagger工具鏈
設計驅動 vs 代碼驅動
npm install swagger-ui-express swagger-jsdoc --save
在app.js
中引入:
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
在路由文件(如routes/users.js
)頂部添加注釋:
/**
* @swagger
* /users:
* get:
* summary: 獲取用戶列表
* tags:
* - 用戶管理
* responses:
* 200:
* description: 返回用戶數組
*/
router.get('/', userController.list);
const options = {
definition: {
openapi: '3.0.0',
info: { title: '示例API', version: '1.0.0', description: 'Node.js + Swagger文檔示例' },
servers: [{ url: 'http://localhost:3000', description: '本地開發環境' }],
},
apis: ['./routes/*.js'],
};
const swaggerSpec = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
啟動服務后,訪問http://localhost:3000/api-docs
即可查看自動生成的Swagger UI文檔,并可在線調試接口。
< dependency>
< groupId > org.springdoc < /groupId >
< artifactId > springdoc-openapi-ui < /artifactId >
< version > 1.7.0 < /version >
< /dependency >
在Controller中添加@Operation
與@ApiResponse
:
@Operation(summary = "獲取所有訂單", description = "返回訂單列表")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "查詢成功"),
@ApiResponse(responseCode = "404", description = "未找到資源")
})
@GetMapping("/orders")
public List < Order > listOrders() { … }
啟動項目后,訪問/swagger-ui.html
可查看Spring Boot Swagger文檔。
在.github/workflows/swagger.yml
中添加:
name: Generate & Deploy Swagger Docs
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: 安裝依賴
run: npm ci
- name: 生成Swagger Spec
run: node scripts/gen-swagger.js
- name: 部署到 GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
publish_dir: ./swagger-ui-static
npm install -g swagger-codegen-cli
swagger-codegen generate -i swagger.json -l python -o ./client-python
swagger-ui-express
中傳入自定義CSS,或使用主題包。通過使用Swagger自動化生成API文檔,不僅能大幅降低維護成本,還可提升開發、測試與運維效率。結合設計驅動與代碼驅動策略,并融入CI/CD與AI輔助,打造一條從設計到發布的端到端API文檔自動化流水線,幫助團隊持續交付高質量接口服務。
原文引自YouTube視頻:https://www.youtube.com/watch?v=dhMlXoTD3mQ