Web API Mockサーバをサクッと立てたいときのjson-server
フロントの開発や、サーバサイドで他Web APIを叩くときにAPI側の開発が完了してないときや、いろいろな返却値を試したいときがある。
そのときにサクッとMockを立てられるOSSがあったので紹介する。
json-server
node.jsで書かれたWeb API MockサーバでREST APIをコーディングなしでサクッと立てられる。公式に書いてあった
Get a full fake REST API with zero coding in less than 30 seconds (seriously)も嘘でなかった。
環境構築
必要なのはnode.js
この辺を参考にnvmを入れて環境作っておくとよい。
その後npmでjson-serverを入れる。
グローバルに入れたくない場合、まず適当なフォルダを作ってnpm initでパッケージのリスト作る。
グローバルに入れたくない場合、まず適当なフォルダを作ってnpm initでパッケージのリスト作る。
jun-mac:json-server jun-ishioka$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
Seenpm help json
for definitive documentation on these fields
and exactly what they do.
Usenpm <span style="color: #dad085;">install</span> <pkg> <span style="color: #e28964;">-</span><span style="color: #e28964;">-</span>save
afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (json-seerver-test) json-server-test
version: (1.0.0)
description: for test
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/jun-ishioka/temp/json-server/package.json:
{
"name": "json-server-test",
"version": "1.0.0",
"description": "for test",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes) yes
その後json-serverを入れる。
いろいろパッケージが入るのでこれで完了
jun-mac:json-server jun-ishioka$ npm install --save-dev json-server
いろいろパッケージが入るのでこれで完了
使用方法
{
"users": [
{ "id": 1, "name": "kageki", "genger": "man" },
{ "id": 2, "name": "kageki_2", "genger": "man" }
]
}
以下コマンドで立ち上げ
jun-mac:json-server jun-ishioka$ node node_modules/json-server/bin/index.js -w db.json
{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/users
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
リクエストを投げてみるとjsonが返却される。
jun-mac:~ jun-ishioka$ curl -O GET http://localhost:3000/users
curl: Remote file name has no length!
curl: try 'curl --help' or 'curl --manual' for more information
[
{
"id": 1,
"name": "kageki",
"genger": "man"
},
{
"id": 2,
"name": "kageki_2",
"genger": "man"
}
]
応用的な使い方
今回自分がそうだったが、たまにPOSTリクエストだがデータ取得に使われるAPIなどがある。json-serverはRESTの原則に従っているので、POSTが投げられるとこのjson.dbにデータが追加されてしまう。
それを避けるためにPOSTをGETに曲げる必要があるが、それは独自ファイルを作り起動するとできる。
このページに詳しく書いてある。