Slate - 為你打造漂亮的 API 文件

這陣子在找一種工具可以將 Restful API 彙整起來能用網頁的方式執行讀取,上網找了不少工具,例如下方三套是常見的 API 文檔工具,在本篇則是介紹 Slate。

  • swagger:相當標準的 API 文件化工具,從設計、建置、撰寫、測試、各式各樣的技巧環環包圍。
  • apidoc: 這套也不錯,寫的方式是將所有 API 的註記放在原始碼的方法(function)的上方,但小缺點也在這了,如果參數值過多、回傳值也好幾行,這樣就一直在滑鼠捲軸了。不過資料不多的話,是滿適合的。
  • slate : 輕量化的寫法,允許你使用 markdown 撰寫 API 文件,並且是 ruby 語法執行 bundle 套件安裝,打包之後預設是用靜態的 html ,甚至你可以推上 github pages 進行託管。

先決條件

務必要有 Ruby 1.9.2 或更高的版本。並且還需要 bundler gem,可以透過命令來做安裝 gem install bundler,安裝或升級可以參考以下連結。

安裝 Slate

先進入到 slate github https://github.com/lord/slate

  1. 首先按右上角的 Fork slate 的 repo
  2. fork 的 repo 已經複製一份到你自己的 repo 了
    https://github.com/<<YOURUSERNAME>>/slate,將它 clone 下來到你的本地端的資料夾 git clone https://github.com/weijutu/slate.git
  3. 進入 slate 資料夾 cd slate
  4. 初始化 Slate

將套件都裝起來,使用以下的指令進行安裝

1
$ bundle install

過程中就會進行安裝套件

1
2
3
4
5
6
7
8
9
10
Fetching gem metadata from https://rubygems.org/............
Fetching concurrent-ruby 1.0.5
Installing concurrent-ruby 1.0.5
Fetching i18n 0.7.0
Installing i18n 0.7.0
Fetching minitest 5.10.1
Installing minitest 5.10.1
Fetching thread_safe 0.3.5
Installing thread_safe 0.3.5
Fetching tzinfo 1.2.2

接著將 slate 執行起來

1
$ bundle exec middleman server

執行之後,就可以打開瀏覽器開啟 http://localhost:4567,這樣一下子就開了一個全新的 slate api 靜態文件!!

1
2
3
4
5
 ~/Projects/slate 
$ bundle exec middleman server
== The Middleman is loading
== View your site at "http://localhost:4567"
== Inspect your site configuration at "http://localhost:4567/__middleman"

是不是看起來很不賴呢?

開始寫 API 文件

大致上是 markdown 寫法的,若有不了解 markdown 語言的人,可以參考這篇文章 Markdown 語法說明

標題

1
2
3
# Level 1 Header
## Level 2 Header
### Level 3 Header

段落文字

1
This is some paragraph text. Exciting, no?

程式碼範本

1
2
3
4
const kittn = require('kittn');

let api = kittn.authorize('meowmeowmeow');
let max = api.kittens.delete(2);

語法註解

1
> This is a code annotation. 

表格

1
2
3
4
Table Header 1 | Table Header 2 | Table Header 3
-------------- | -------------- | --------------
Row 1 col 1 | Row 1 col 2 | Row 1 col 3
Row 2 col 1 | Row 2 col 2 | Row 2 col 3

文字格式

1
This text is **bold**, this is *italic*, this is an `inline code block`.

列表

1
2
3
4
5
6
7
1. This
2. Is
3. An

* This
* Is
* A

連結

1
This is an [internal link](#error-code-definitions)

產生靜態網頁

修改完之後,我們將他產生靜態網站,可以使用以下的命令

1
$ bundle exec middleman build --clean

部署過程中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
create  build/stylesheets/print.css
create build/stylesheets/screen.css
create build/images/navbar.png
create build/images/logo.png
create build/fonts/slate.woff
create build/fonts/slate.woff2
create build/fonts/slate.ttf
create build/fonts/slate.eot
create build/fonts/slate.svg
create build/index.html.tmp
create build/javascripts/all_nosearch.js
create build/javascripts/all.js
create build/index.html
Project built successfully.

你會發現會新增了一個 build 資料夾,裡面包含了許多被編譯出來的檔案

打開 index.html 就可以看到建置的結果囉。

提供一個實際範本

/slate/source/index.html.md 檔案做修改
在這裡提供一個實際範本可以做點參考。

語法範本在這裡:範例

顯示如下圖:

參考