JSON Server でダミーサーバを手軽に構築する

JSON を返すダミー API サーバを構築する際、以下が手軽で便利そうだったので使ってみる。

github.com


npm コマンドでインストール。

npm install -g json-server

APIJSON ファイルで作成する。次の場合、exampleAPI のエンドポイントとなり、value のオブジェクトがレスポンスボディとなる。

{
  "example": {
    "values": [
      { "id": "1", "name": "foo" },
      { "id": "2", "name": "bar" },
      { "id": "3", "name": "baz" },
      { "id": "4", "name": "hoge" },
      { "id": "5", "name": "fuga" }
    ]
  }
}

JSON Server を起動する。--watch オプションを付けると JSON ファイルの変更を監視してくれる。便利。

json-server --watch example.json

http://localhost:3000/example にアクセスすると以下のレスポンスが返る。

{
  "values": [
    {
      "id": "1",
      "name": "foo"
    },
    {
      "id": "2",
      "name": "bar"
    },
    {
      "id": "3",
      "name": "baz"
    },
    {
      "id": "4",
      "name": "hoge"
    },
    {
      "id": "5",
      "name": "fuga"
    }
  ]
}

JSON Server 起動時に js ファイルを指定して、動的にレスポンスを生成することもできる。(未検証)

(2019/10/01 追記)

ルーティングについて。

JSON Server ではエンドポイントの設定に / を含めることができない。例えば、/example/10001 のような記述を db.json に書くことはできない。

そこで、次のような routes.json を用意する。

{
  "/example/10001": "/example1",
  "/example/10002": "/example2"
}

これに合わせて次のような db.json を用意。

{
  "example1": {
    "values": [
      // ...
    ]
  },
  "example2": {
    "values": [
      // ...
    ]
  }
}

JSON Server 起動。

json-server --watch db.json --routes routes.json

http://localhost:3000/example/10001 にアクセスすると内部で /example1 にルーティングされて、db.jsonexample1 の内容が返却される。

参考) Add custom routes - typicode/json-server