Swagger定義ファイルの書き方(超手抜き編)


Swagger定義ファイルは、いろいろ定義してバリデーションを厳密にできる反面、ちょっと使おうと思うと、ルールが厳しくて億劫になりがちです。

そこで、必要最低限のSwagger定義ファイルの書き方を備忘録として残しておきます。
いざ本番となるときには、SwaggerのSpecificationに従って厳密に定義してください。

(参考情報)
https://swagger.io/docs/specification/2-0/basic-structure/

一番簡単な定義

結論だけ示すと、一番簡単な定義は以下の通りです。
/pathsのところを参考にしてください。

swagger.yaml
swagger: '2.0'
info:
  version: 'first version'
  title: Sample Api
host: localhost:10010
basePath: /

schemes:
  - http

consumes:
  - application/json
produces:
  - application/json

securityDefinitions:
  basicAuth:
    type: basic
  tokenAuth:
    type: apiKey
    name: Authorization
    in: header

paths:
  /swagger:
    x-swagger-pipe: swagger_raw

  /test_post:
    post:
      x-swagger-router-controller: echo
      operationId: test_post
      parameters:
        - in: body
          name: body
          schema:
            type: object
      responses:
        200:
          description: Success
          schema:
            type: object

  /test_get:
    get:
      x-swagger-router-controller: echo
      operationId: test_get
      parameters:
        - in: query
          name: param
          type: string
      responses:
        200:
          description: Success
          schema:
            type: object

definitions:
  Empty:
    type: "object"
    title: "Empty Schema"

swagger-nodeで最短で立ち上げる

RESTful実行環境に最適なswagger-nodeを使って立ち上げます。
swagger-nodeについては、以下の記事を参考にしてください。

SwaggerでRESTful環境を構築する

> swagger project create first_restful
※Frameworkにはexpressを選択します。

> cd first_restful

Swagger定義ファイルをさきほどのswagger.yamlに置き換えてください。

置き換え対象ファイル:./api/swagger/swagger.yaml

以下のファイルを作成します。

作成ファイル:./api/controllers/echo.js

echo.js
'use strict';

module.exports = {
  test_post: test,
  test_get: test
};

function test(req, res) {
  console.log("calling: test");

  var event = {
    headers: req.headers,
    body: JSON.stringify(req.body),
    path: req.swagger.apiPath,
    httpMethod: req.method,
    queryStringParameters: req.query
  };

  res.json( { event: event } );
}

./api/controllers/hello_world.js はいらないので削除してもよいです。

Restful環境を立ち上げます。

> swagger project start

curlでたたく

さっそく、Web APIを呼び出したく、例えば、curlを使います。

> curl https://localhost:10010/test_get

{“event”:{XXXXXXわらわらXX}}

マイ最速

とはいいつつも、なんだかんだ言って、私は以下が最速

> git clone https://github.com/poruruba/swagger_template.git
> cd swagger_template
> npm install
> node app.js

(参考)
SwaggerでLambdaのデバッグ環境を作る(1)

以上。最短の記事でした。