[Swagger] 產生API文件
TL;DR
建立API之後,我們需要產生一個文件來讓前端的夥伴使用,這時候就可以使用Swagger來產生文件!
參考資料
- 使用 Swagger 自動生成 API 文件 | Ray
- Swagger-自動產生API文件 (Node.js 實作+範例程式碼)
- Vercel部署Swagger完全沒有畫面解決方法 | Github issue
- 部署在Vercel上的Swagger沒有吃到Swagger UI CSS設定解決方法 | Github issue
- 解決Swagger UI CSS後路由換行錯誤 | Github issue
相關連結
- swagger-autogen搭配express路由範例程式碼 | Github
- Swagger Petstore 範例頁面 | Swagger UI
swagger.js
我的swagger.js
程式碼:
swagger.js
const swaggerAutogen = require("swagger-autogen")();
const doc = {
info: {
version: "1.0.0",
title: "Dreamboost募資平台API",
description:
" Documentation automatically generated by the <b>swagger-autogen</b> module.<br><br> 說明欄位包含的符號分別代表: <ul><li>是否需token(登入狀態)</li><li>是否需為本人</li></ul> ",
},
host: "填入要部署的domain",
basePath: "/",
schemes: ["https"],
consumes: ["application/json"],
produces: ["application/json"],
securityDefinitions: {
apiKeyAuth: {
type: "apiKey",
in: "header", // can be "header", "query" or "cookie"
name: "Authorization", // name of the header, query parameter or cookie
description: "any description...",
},
},
definitions: {
Parents: {
father: "Simon Doe",
mother: "Marie Doe",
},
User: {
name: "Jhon Doe",
age: 29,
parents: {
$ref: "#/definitions/Parents",
},
diplomas: [
{
school: "XYZ University",
year: 2020,
completed: true,
internship: {
hours: 290,
location: "XYZ Company",
},
},
],
},
AddUser: {
$name: "Jhon Doe",
$age: 29,
about: "",
},
},
};
const outputFile = "./swagger_output.json"; // 輸出的文件名稱
const endpointsFiles = ["./app.js"]; // 要指向的 API,通常使用 Express 直接指向到 app.js 就可以
swaggerAutogen(outputFile, endpointsFiles,doc); // swaggerAutogen 的方法
並且在package.json
內加入scripts
如下:
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www",
"openapi":"node ./swagger"
},