APIクライアントを自動生成するやつ

Heroicsという、JSON Schemaを元にAPIクライアントのコードを自動生成するやつを見た。 Heroicsにはbin/heroics-generateというコマンドラインツールが付いていて、JSON Schemaを解析したあと、 client.erbというERBのテンプレートに解析結果のオブジェクトを渡した結果、client.rbという雑なファイルを生成する。

$ gem install heroics
$ heroics-generate SuperAwesomeClient schema.json https://api.example.com > client.rb

Heroicsから生成されるもの

JSON Schemaからこんな感じで使えるやつを生成してくれる。

# client.rb
client = SuperAwesomeClient.connect(api_key)
client.recipe.create("title")
client.recipe.list #=> [...]
client.recipe.show(123)

JSON Schema

普通JSONで書くけど紙面の都合上ちょっと読みにくいのでYAML形式で記述しときます。

---
"$schema": http://json-schema.org/draft-04/hyper-schema
title: Super ultra awesome API
type:
- object
properties:
  recipe:
    "$ref": "#/definitions/recipe"
definitions:
  recipe:
    title: Cooking Recipe
    type:
    - object
    properties:
      id:
        "$ref": "#/definitions/recipe/definitions/_id"
      created_at:
        "$ref": "#/definitions/recipe/definitions/_created_at"
      title:
        "$ref": "#/definitions/recipe/definitions/title"
    definitions:
      id:
        description: ID
        readOnly: true
        type:
        - string
      created_at:
        description: When this object was created
        format: date-time
        readOnly: true
        type:
        - string
      title:
        description: Recipe title
        type: "string"
    links:
    - description: List recipes
      href: "/recipes"
      method: GET
      rel: instances
      title: List
    - description: Show the recipe
      href: "/recipes/({#/definitions/recipe/definitions/id})"
      method: GET
      rel: self
      title: Show
    - description: Create a new recipe
      href: "/recipes"
      method: POST
      rel: create
      title: Create
      schema:
        properties:
          title:
            "$ref": "#/definitions/recipe/definitions/title"

Heroicsが解析するもの

定義されてるオブジェクト一覧を json.properties から持ってきて、それをクラスとして定義する。 また、これらのオブジェクトに定義されているlinksというプロパティから定義されているAPIの情報を知り、 定義したクラスにそのAPIにアクセスするためのメソッドを生やす。このときメソッド名はlinks内のtitleプロパティが利用される。 "$ref": "#/definitions/recipe/definitions/title"や href: "/recipes/({#/definitions/recipe/definitions/id})"というのは JSON Schemaで定められている他のプロパティを参照するための記法。

まとめ

JSON Schemaからいろいろ自動生成して君だけの最強のデッキをつくろう。
あわせて読みたい