跳至主要内容

[Swagger] 產生API文件

TL;DR

建立API之後,我們需要產生一個文件來讓前端的夥伴使用,這時候就可以使用Swagger來產生文件!

參考資料

相關連結


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"
},