在Linux上使用Swagger(現稱為OpenAPI)進行API數據模型設計的步驟如下:
安裝Swagger工具鏈:
sudo apt update
sudo apt install nodejs npm
npm install -g swagger-editor
npm install -g swagger-cli
npm install -g swagger-codegen
設計API規范:
swagger-editor
http://localhost:3001
開始設計API。使用YAML格式編寫API規范,遵循OpenAPI 3.0標準,為每個端點添加詳細的描述和示例,定義清晰的數據模型。驗證API規范:
swagger-cli validate api-spec.yaml
生成API文檔:
swagger-codegen generate -i api-spec.yaml -l html -o ./docs
npm install -g redoc-cli
redoc-cli bundle api-spec.yaml -o redoc.html
生成服務器存根和客戶端SDK:
swagger-codegen generate -i api-spec.yaml -l nodejs-server -o ./server
swagger-codegen generate -i api-spec.yaml -l python -o ./client/python
集成到CI/CD流程:
stages:
- validate
validate_spec:
stage: validate
script:
- npm install -g swagger-cli
- swagger-cli validate api-spec.yaml
使用Swagger UI進行測試:
docker pull swaggerapi/swagger-ui
docker run -p 8080:8080 -e SWAGGER_JSON=/api-spec.yaml -v $(pwd)/api-spec.yaml:/api-spec.yaml swaggerapi/swagger-ui
http://your_server_ip:8080
,你將看到Swagger的歡迎頁面,可以點擊“TRY IT OUT”按鈕來測試API請求。通過以上步驟,您可以在Linux環境下充分利用Swagger工具鏈來設計、文檔化和測試高質量的API。