[Front-End General] JSON Server で fake REST API を立てる

フロントの実装時に API ができていることはまれなので、モックがあると良いですね。

[markdown]
## Installation

ここではグローバルインストールしておく。

> * [typicode/json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously)](https://github.com/typicode/json-server)

“`
% sudo npm install -g json-server
“`

## Usage

db.json を作成。

“`json:db.json
{
“posts”: [
{ “id”: 1, “title”: “json-server”, “author”: “typicode” }
],
“comments”: [
{ “id”: 1, “body”: “some comment”, “postId”: 1 }
],
“profile”: { “name”: “typicode” }
}
“`

`json-server –watch db.json` でサーバを起動する。

“`
% json-server –watch db.json
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching…
“`

`http://localhost:3000` をブラウザで表示すると、定義されたメソッドやデータベースの状態を確認できる。

## GET する

かんたんに動作を確認してみます。
ちなみに POST もできます。

### curl

`curl` で `GET` すると以下を確認できる。
整形済みの情報が返ってきますね。

“`
% curl -X GET “http://localhost:3000/posts”
[
{
“id”: 1,
“title”: “json-server”,
“author”: “typicode”
}
]
“`

> * [【個人メモ】JSON Serverを使って手っ取り早くWebAPIのモックアップを作る – Qiita](http://qiita.com/futoase/items/2859a60c8b240da70572)
> * [APIモックを使って開発速度を上げよう – Qiita](http://qiita.com/roana0229/items/547437b6314fd283ddca)

今回は不要ですが、curl の返値を整形表示する方法については、以下が詳しい。

“`
% curl -X GET “http://weather.livedoor.com/forecast/webservice/json/v1?city=170010” | python -m json.tool
“`

> * [json形式のAPIをcurlで確認するTips – Qiita](http://qiita.com/roana0229/items/585ce757e65850c7b37f)
> * [コマンドラインからcurlで取得するjsonを見やすく表示する – Qiita](http://qiita.com/pugiemonn/items/731c33e8cd8ccc6a6c4c)

### jq

jq というツールは brew でインストールできる。

“`
% brew install jq
“`

> * [jq](https://stedolan.github.io/jq/)

こんな形で実行すると、色つきで整形して日本語もうまい事扱えますね。

“`
% curl -X GET “http://weather.livedoor.com/forecast/webservice/json/v1?city=170010” | jq ‘.’ -C | less -R
“`
> * [CLIでJSONの整形をする – ( ꒪⌓꒪) ゆるよろ日記](http://yuroyoro.hatenablog.com/entry/2013/04/02/190709)
> * [jqで簡単JSON加工 | Developers.IO](http://dev.classmethod.jp/tool/jq/)

## 補遺

SSL(HTTPS) について。

> * [Support for HTTPS · Issue #244 · typicode/json-server](https://github.com/typicode/json-server/issues/244)
> * [typicode/hotel: A simple process manager for developers. Start apps from your browser and get local dev domains in seconds](https://github.com/typicode/hotel)
> * [スマホアプリ開発時にさくっと叩けるAPIサーバをnginx・Let’s encrypt・JSON Serverで構築する – Qiita](http://qiita.com/uti/items/ab2910881058cad871c9)
[/markdown]