Restish + OpenAPI
restish は httpie / xh みたいなことができそうに見えて、結構異なる。
単純に GET することはもちろんできる。
restish http://localhost:5000/path
しかし httpie, xh のように送信時の Content-type を自由に設定することはできない。cli からはjson にシリアライズされる。-H Content-Type:application/x-www-form-urlencoded
としても form にシリアライズされるわけではない。jo, httpie, xh は body の組み立て方がほとんど同じだが、restish は shorthand と呼ばれる独自の構文が使える。慣れが必要だが、悪くない。
xh http://example.org a=b c=d
restish http://example.org a: b, c: d
本格的に使うには ~/.config/restish/config.json
に OpenAPI を登録する。spec_files
は local file path か URL である。次のような設定ファイルを作る。restish api config
で対話式に作成しても構わない。
{
"$schema": "https://rest.sh/schemas/apis.json",
"named-api": {
"base": "http://localhost:5000/api",
"spec_files": [
"http://localhost:5000/swagger.json"
]
}
}
すると、次のように呼べるようにコマンドが拡張される。help も自動生成される。
restish named-api --help
named-api の後ろは、OpenAPI の仕様に記述された名前のコマンドを受け取るようになっている。
restish http://localhost:5000/api/users
# 例えば、これが次のように書ける
restish named-api list-users
basePath などが上手く動作しないときは、cache のせいかもしれない。次のように削除して再度試してみる。
rm -rf ~/.cache/restish/
設定ファイルに認証情報を設定すると、認証を自動処理するようになる。ちなみに OpenAPI からも認証情報を読み取る。
{
"$schema": "https://rest.sh/schemas/apis.json",
"named-api": {
"base": "http://localhost:5000/api",
"spec_files": [
"http://localhost:5000/swagger.json"
],
"profiles": {
"default": {
"auth": {
"name": "oauth-client-credentials",
"params": {
"token_url": "http://localhost:7000/tokens",
"client_id": "APP_ID",
"client_secret": "APP_SECRET",
"scopes": "openid",
"grant_type": "client_credentials"
}
}
}
}
}
}
auth.name の部分で処理方法が変わる。https://rest.sh/#/configuration?id=api-auth がリファレンスだが、コードを見たほうが正確だ。上記の設定では、oauth2 client credentials flow を使って取得した access token を bearer として自動処理する。
Restish Shorthand j syntax
"shorthand" syntax(検索向きでない命名だが、、、)には v1 と v2 が存在する。特に理由が無ければ v2 を使用する。restish の引数でもライブラリとして使われている。単体のコマンドラインプログラムは "j"(これまた検索向きでない命名だが、、、)として用意されている。
v1 での「ドットで開始する」キーは、v2 では使えないことに注意。
# v1 syntax
j foo.nest: a, .nest2: b
# v2 syntax
j foo{ nest: a, nest2: b}
ちなみに restish になる前の openapi-cli-generator は shorthand v1 時代のものである。
Hints...
以下のようなエラーができるときの対処法。
$ j foo: "http://test"
Expected '}' but found { at line 1 col 19
{foo: http://test}
..................
実はこれは "//" がコメント開始として識別されている。次のようにする。
$ j foo: "http:/\/test"
{
"foo": "http://test"
}
Discussion