SwaggerでAPIを定義してモックアップを作る

REST APIの仕様定義には色々ありますが、Open API Initiativeでも標準ツールとして採用されている SwaggerをつかってAPI仕様を記載しモックアップを作ってみましょう。
Swaggerはユーザが多いのもあって周辺ツールの充実と多言語対応が良いので今から採用するならオススメです。

Swagger.yamlAPI仕様を記述する。

SwaggerではAPIの仕様をswagger.yamlで記載しますが、
swagger-editorというツールが非常に便利です。
ツールとしてインストールも出来ますし、オンラインでも使えます。
http://editor.swagger.io/#/

まずはこんなyamlを書いてみます。

swagger: '2.0'
info:
  version: "0.0.0"
  title: サンプル api
# Describe your paths here
paths:
  # This is a path endpoint. Change it.
  /users:
    get:
      description: |
        メンバ一覧取得API.
      parameters:
        -
          name: size
          in: query
          description: Size of array
          required: false
          type: number
          format: number
      responses:
        # Response code
        200:
          description: ユーザデータ(List)
          schema:
            title: ArrayOfUsers
            type: array
            items:
              $ref: '#/definitions/User'
  /users/{id}:
    get:
      description: |
        メンバ取得API.
      parameters:
        -
          name: id
          in: path
          description: user id
          required: true
          type: number
          format: number
      responses:
        # Response code
        200:
          description: ユーザデータ
          schema:
            $ref: '#/definitions/User'
definitions:
 User:
  type: object
  properties:
    id:
      type: number
    name:
      type: string
    age:
      type: number

簡単に言うと、
「/users」で一覧が取得できて
「/users/{id}」でUserID指定のデータが取得出来るというものです。
またdefinitionsのところでUserデータ型を指定しています。

ソースの生成

これで、Springのソースを出力してみましょう。
SwaggerからはNode、GoServer、JAX-RSPythonRails等色々な言語の実装を自動生成できますが、SpringBootだと起動が楽なので今回はSpringでいきます。
「Generate Server」から「spring」を選ぶと出来たソースがZipで落ちてくるので解凍するとMavenプロジェクトになっています。
もうこれでサーバの基礎は動きます。
楽勝ですね。

それでは動かしていきます。
まずはPomを開いて42行目あたりの「provided」行を削除しましょう。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>       ←この行削除
        </dependency>

レスポンス内容をそれらしく作る

Swaggerで生成されるモックはレスポンス内容は空っぽで生成されます。
なのでレスポンス内容は自分でモックコードを書く必要があります。

ソースの中のio.swagger.api.UsersApiControllerを開いて「// do some magic!」と書かれているところにモックコードをこんな感じで書きます。

@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-11-08T06:41:55.099Z")
@Controller
public class UsersApiController implements UsersApi {
    public ResponseEntity<List<User>> usersGet(@ApiParam(value = "Size of array") @RequestParam(value = "size", required = false) BigDecimal size
    ) {
        // do some magic!
        User user1 = new User();
        user1.setId(BigDecimal.ONE);
        user1.setName("aaa");
        User user2 = new User();
        user2.setId(BigDecimal.TEN);
        user2.setName("bbb");
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

    public ResponseEntity<User> usersIdGet(@ApiParam(value = "user id", required = true) @PathVariable("id") BigDecimal id ) {
        // do some magic!
        User user1 = new User();
        user1.setId(BigDecimal.ONE);
        user1.setName("aaa");
        return new ResponseEntity<>(user1, HttpStatus.OK);
    }

これでOK。
あとは起動して、「http://localhost:8080/」にアクセスすればSwaggerUIがみれます。
f:id:GARAPON:20161108172530p:plain

TryItOutをおしてみると
f:id:GARAPON:20161108172537p:plain

こんな感じで動いていますね。