2017年8月4日金曜日

Swagger+nodejsの導入

APIを作って管理するさい、ドキュメントを作るのが面倒
そんな場合、Swaggerを使うと楽できる

パッケージのインストール

mkdir swagger_sample
cd swagger_sample
$ npm init  #適当に情報を入れてpackage.jsonを作成
$ npm install express --save
$ npm install swagger-express --save-dev

Swagger-ui

cd ../    #先ほど作ったディレクトリから出る
$ git clone https://github.com/swagger-api/swagger-ui.git
$ cd swagger-ui
$ mv dist ../swagger_sample

You can use the swagger-ui code AS-IS! No need to build or recompile--just clone this repo and use the pre-built files in the dist folder. If you like swagger-ui as-is, stop here.
とあるので、distを利用する

Code

app.js
var express = require('express');
var app = express();
var swagger = require('swagger-express');
app.use(swagger.init(app, {
  apiVersion: '1.0',
  swaggerVersion: '1.0',
  swaggerURL: '/docs',           // swaggerページのパス
  swaggerJSON: '/api-docs',      // swagger表示用のデータアクセス先 
  swaggerUI: './dist',           // swagger-uiが置いてあるパス
  basePath: 'http://localhost:3000',
  apis: ['./api.js'],            // ドキュメントが記載されているファイル
  middleware: function(req, res){}
}));

app.listen(3000);

urlの書き換え

dist/index.htmlのL78を上記で指定したパス「http://localhost:3000/api-docs」に書き換え