swagger-node を使って API ドキュメントとスタブサーバーを作成する

2017.07.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Swagger module for Node.js

SwaggerOpenAPI Specification (OAS) に準拠した API ドキュメントを YAML または JSON で定義できるフレームワークです。Amazon API Gateway を始めとした各種サービスで用いられることから、世界的に最もポピュラーな API フレームワークと言えるでしょう。

今回はそんな Swagger の Node.js 製のモジュールである「swagger-node」の使いかたを README に沿って試してみました。

検証環境

  • macOS Sierra 10.12.3
  • Node.js v6.11.0
  • swagger-node 0.7.5

swagger-node のインストール

まずは始めに swagger-node をインストールしましょう。swagger-node が内部で npm を利用していることから、今回は npm を使ってインストールしました。

$ npm install swagger -g

コマンドが通るか試しておきましょう。

$ swagger --version
0.7.5

新しい Swagger プロジェクトの作成

swagger-node のプロジェクトは、以下のコマンドを実行することで作成できます。create の後にはプロジェクト名を入れます。今回は hello-world としました。

コマンドを実行すると、利用するサーバーサイドフレームワークの選択が求められます。connect, express, hapi, restify, sails から選ぶことができます。今回は最もポピュラーで機能的にも充実している express を選びました。

$ swagger project create hello-world
? Framework? (Use arrow keys)
  connect
❯ express
  hapi
  restify
  sails

以下のようなファイル構成のプロジェクトが作成されます。

.
├── README.md
├── api
│   ├── controllers
│   │   ├── README.md
│   │   └── hello_world.js
│   ├── helpers
│   │   └── README.md
│   ├── mocks
│   │   └── README.md
│   └── swagger
│       └── swagger.yaml
├── app.js
├── config
│   ├── README.md
│   └── default.yaml
├── node_modules
│   └── ...
├── package.json
└── test
    └── api
        ├── controllers
        │   ├── README.md
        │   └── hello_world.js
        └── helpers
            └── README.md

Swagger Editor を起動する

Swagger ファイルを編集するための Web アプリケーション「Swagger Editor」をコマンド一発で起動できます。

$ swagger project edit

コマンドを実行すると Web ブラウザで Swagger Editor が表示されます。実際にプレビューしながら編集できるので便利です。

Swagger-Editor

スタブサーバーの起動

スタブサーバーのみ起動したい場合は、次のコマンドを実行します。

$ swagger project start hello-world
Starting: /path/to/hello-world/app.js...
  project started here: http://localhost:10010/
  project will restart on changes.
  to restart at any time, enter `rs`
try this:
curl http://127.0.0.1:10010/hello?name=Scott

コマンド出力にある通り 127.0.0.1:10010 で起動しています。curl なり何なりでリクエストすることができます。

$ curl "http://127.0.0.1:10010/hello?name=Scott"
"Hello, Scott!"

このサンプルの API のロジックは api/controllers/hello_world.js に書かれています。

'use strict';

var util = require('util');

module.exports = {
  hello: hello
};

function hello(req, res) {
  // variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name}
  var name = req.swagger.params.name.value || 'stranger';
  var hello = util.format('Hello, %s!', name);

  // this sends back a JSON response which is a single string
  res.json(hello);
}

このメソッドが実行されている理由は swagger.yaml 本体にあります。paths 以下の x-swagger-router-controller でファイルを指定、operationId でメソッドを指定できます。つまり、パスごとにファイルを変えたり API ごとに別処理に変えたりできます。

paths:
  /hello:
    # binds a127 app logic to a route
    x-swagger-router-controller: hello_world
    get:
      description: Returns 'Hello' to the caller
      # used as the method name of the controller
      operationId: hello
      parameters:
        - name: name
          in: query
          description: The name of the person to whom to say hello aaa
          required: false
          type: string
      responses:
        "200":
          description: Success
          schema:
            # a pointer to a definition
            $ref: "#/definitions/HelloWorldResponse"
        # responses may fall through to errors
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"

まとめ

Swagger は、ドキュメントの定義だけではなく Editor やスタブサーバーなども提供されています。swagger-node ではこれらの機能を簡単なコマンドを実行するだけで使えるので、非常に便利です。活用していきましょう!