Closed hironaeee closed 1 year ago
Express.js、TypeScriptは既に追加されている前提とします。
npm i -D swagger-jsdoc # ドキュメント生成
npm i -D swagger-ui-express # SwaggerのWeb画面が表示できます
npm i -D @types/swagger-jsdoc @types/swagger-ui-express # 型定義ファイルのインストール
Swagger JSDocにより、コメントに基づいてドキュメントが作成されます。
コメントの内容はOpenAPI(Swagger)の仕様に準じており、YAML
形式で記述します。(サンプル)
どこまで詳細に書けばよいか分からなかったのですが、
Web記事いくつかを参考にSwagger UIに最低限、表示されていればよい項目
という観点で選び、うまくいった書き方をコピーして使いまわしています。
// userRoutes.ts
/**
* @swagger
* /api/v1/user/users:
* get:
* tags:
* - users
* description: ユーザー一覧を取得
* produces:
* - application/json
* responses:
* 200:
* description: ユーザーリスト
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/definitions/AccountUser'
*/
router.get("/users", userController.users)
なお、何度も使うものは下記のようにdefinitions
セクションにまとめておき
#/definitions/XXXX
で参照できます。
// AccountUserクラスを定義した例
/**
* @swagger
* definitions:
* AccountUser:
* type: object
* description: ユーザー
* required:
* - id
* - name
* properties:
* id:
* type: string
* description: ユーザーID
* name:
* type: string
* description: ユーザー名
* password:
* type: string
* format: password
* description: パスワード
*/
Swagger JSDocのオプション「apis
」にOpenAPI用コメントを
記載しているファイルを指定します。
// docs.ts
const swaggerOptions: Options = {
...
// ルーティングファイルにOpenAPI用コメントを記載しているので、それらを指定
apis: ['./routes/*Routes.ts']
}
Swagger UIを閲覧できるエンドポイントを「/swagger」に設定しておきます。
// Swagger UI を起動
app.use(
'/swagger',
swaggerUi.serve,
swaggerUi.setup(swaggerDocs)
)
Swagger JSDocで生成された結果のJSONファイル閲覧できる
エンドポイントを「/api-docs.json」に設定しておきます。
// 定義した内容をJSONで閲覧可にする
app.get('/api-docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json')
res.send(swaggerDocs)
})
上記の設定をすれば、デバッグ実行後に「http://localhost:<port>/swagger」にアクセスすると
Swagger UI が表示されます。
公式のデモのようなAPI一覧画面が表示されます。
各APIをクリックしてTry it out
から実際に実行することができます。
開発環境の改善(ドキュメント保守&開発支援)