jsonを返却するapiのモックについて

概要

手間を掛けずにjsonを返却するapiのモックを作成する方法を調査。

参考サイト

qiita.com qiita.com

apiのモックを作成

node.jsインストール

json-serverインストール

> npm install -g json-server

jsonファイルを作成

返却するjsonデータファイル test.json を作成。

{
    "api-action": [
        {
            "div": "営業部",
            "member": [
                {
                    "name": "sato",
                    "age": 20
                },
                {
                    "name": "naka",
                    "age": 21
                }
            ]
        },
        {
            "div": "製造部",
            "member": [
                {
                    "name": "sakai",
                    "age": 20
                },
                {
                    "name": "aoi",
                    "age": 21
                }
            ]
        }
    ]
}

json-server起動

> json-server --watch test.json

  \{^_^}/ hi!

  Loading test.json
  Done

  Resources
  http://localhost:3000/api-action

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

apiの動作を確認

curlによるapiの確認

> curl http://localhost:3000/api-action
[
  {
    "div": "営業部",
    "member": [
      {
        "name": "sato",
        "age": 20
      },
      {
        "name": "naka",
        "age": 21
      }
    ]
  },
  {
    "div": "製造部",
    "member": [
      {
        "name": "sakai",
        "age": 20
      },
      {
        "name": "aoi",
        "age": 21
      }
    ]
  }
]

Chrome DHCによるapiの確認

api呼び出しの参考:http://blog.y-yuki.net/entry/2016/11/01/000000