LoginSignup
11
10

More than 5 years have passed since last update.

JSON ScemaからAPIドキュメントを作成するGoのコマンド書いてみた

Last updated at Posted at 2015-05-23

PRMDのように、JSON Schemaからドキュメントを生成するものを作ってみました。

使い方

インストール

go get github.com/hiroosak/gendoc

JSON Schemaを用意する

init で テンプレートがymlで出力されるので、それを使ったりしながらリソースごとに編集します。

$ gendoc init user > src/user.yml
$ gendoc init article > src/article.yml
# 編集
$ vim src/{user,article}.yml

# ドキュメント作成
$ gendoc doc -src src  > doc.html

HTMLができます。

image
http://hiroosak.github.io/gendoc/sample.html

JSON Schemaのサンプル

リソースごとにJSON Hyper-Schema形式のjsonを書いていきます。

user.yml
---
$schema: "http://json-schema.org/draft-04/hyper-schema"
id: "user"
title: user
type: object
definitions:
  id:
    type: integer
    description: resource id
    example: 1
  name:
    type: string
    description: user name
    example: Ken
links:
- description: List existing users.
  href: "/users"
  method: GET
  rel: instances
  title: List
properties:
  id:
    "$ref": "#/definitions/id"
  name:
    "$ref": "#/definitions/name"
required:
- id
- name

* いまのところ id の設定は必須です。

metaとoverview

ドキュメント生成時にJSONファイルを用意して、ドキュメントの内容を少しだけ変更できます。

meta

{
  "title": "ドキュメントのタイトル",
  "base_url": "APIのベースのURL",
  "headers": [
    "リクエスト時のヘッダー"
  ]
} 

デフォルトは

{
  "title": "API Document",
  "base_url": "http://localhost",
  "headers": []
} 

overview

ドキュメントの頭に何かhtmlを入れたい場合に使います。

$ echo '<h1 class="page-header">ドキュメント</h1>' > overview.html
$  gendoc doc -meta meta.json -overview overview.html -src src  > doc.html

tips

他のスキーマファイルを読み込む

例えば、articleの結果にuserのJSONデータを入れたい場合は
$refuser.jsonを設定しておけば、ドキュメント上でuser以下の階層が表示されるようになります。

article.yml
---
$schema: "http://json-schema.org/draft-04/hyper-schema"
id: "article"
title: article
type: object
definitions:
  id:
    type: integer
    description: resource id
    example: 1
links:
- description: List existing articles.
  href: "/articles"
  method: GET
  rel: instances
  title: List
properties:
  id:
    "$ref": "#/definitions/id"
  user:
    "$ref": "user.json"
required:
- id
- user

結果

image

yamlからjsonに変換する

gen でyamlからjsonに変換できます。
他でJSON Schemaファイルを使いたい場合に変換したものを置いておきます。

$ gendoc gen -src src -dst dst
$ tree src/ dst/
src/
├── article.yml
└── user.yml
dst/
├── article.json
└── user.json
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10