JSON Serverを利用すると、REST APIのモックを作成することができます。まだ完成していないAPIがあり、フロントの実装を進めづらいときなどに活用できて便利です。ここでは基本的な使い方を確認します。
目次
インストール
プロジェクトに json-server を追加します。
npm install --save-dev json-server準備
db.jsonファイル作成
今回、以下のような postsリソース と usersリソース を操作していきます。
{
  "posts": [
    {
      "id": 1,
      "title": "titleAAA",
      "body": "bodyAAA",
      "userId": 1
    }
  ],
  "users": [
    {
      "id": 1,
      "name": "xxxx"
    }
  ]
}package.jsonを更新
scriptsを追加します。
  "scripts": {
    "json-server": "json-server --watch db.json --port 5000"
  },JSON Serverを起動
npm run json-server でJSON Serverを起動させます。
$ npm run json-server
> json-server-mock-api@1.0.0 json-server /pj/json-server-test
> json-server --watch db.json --port 5000
  \{^_^}/ hi!
  Loading db.json
  Done
  Resources
  http://localhost:5000/posts
  http://localhost:5000/users
  Home
  http://localhost:5000
  Type s + enter at any time to create a snapshot of the database
  Watching...APIリクエストの動作確認
curlで動作確認していきます。
Get
$ curl http://localhost:5000/posts
[
  {
    "id": 1,
    "title": "titleAAA",
    "body": "bodyAAA",
    "userId": 1
  }
]子リソースを含める|_embed
$ curl http://localhost:5000/users?_embed=posts
[
  {
    "id": 1,
    "name": "xxxx",
    "posts": [
      {
        "id": 1,
        "title": "titleAAA",
        "body": "bodyAAA",
        "userId": 1
      }
    ]
  }
]親リソースを含める|_expand
$ curl http://localhost:5000/posts?_expand=user
[
  {
    "id": 1,
    "title": "titleAAA",
    "body": "bodyAAA",
    "userId": 1,
    "user": {
      "id": 1,
      "name": "xxxx"
    }
  }
]Post
postリソース を追加します。
$ curl -X POST \
> -H 'Content-Type:application/json' \
> -d '{"title":"titleBBB","body":"bodyBBB","userId":1}' \
> http://localhost:5000/posts
{
  "title": "titleBBB",
  "body": "bodyBBB",
  "userId": 1,
  "id": 2
}db.json の内容が以下のように更新されました。
{
  "posts": [
    {
      "id": 1,
      "title": "titleAAA",
      "body": "bodyAAA",
      "userId": 1
    },
    {
      "title": "titleBBB",
      "body": "bodyBBB",
      "userId": 1,
      "id": 2
    }
  ],
  "users": [
    {
      "id": 1,
      "name": "xxxx"
    }
  ]
}Put
postリソース を更新します。
$ curl -X PUT \
> -H 'Content-Type:application/json' \
> -d '{"title":"titleCCC"}' \
> http://localhost:5000/posts/2
{
  "title": "titleCCC",
  "id": 2
}db.json の内容が以下のように更新されました。
{
  "posts": [
    {
      "id": 1,
      "title": "titleAAA",
      "body": "bodyAAA",
      "userId": 1
    },
    {
      "title": "titleCCC",
      "id": 2
    }
  ],
  "users": [
    {
      "id": 1,
      "name": "xxxx"
    }
  ]
}Delete
postリソース を削除します。
$ curl -X DELETE http://localhost:5000/posts/2
{}db.json の内容が以下のように更新されました。
{
  "posts": [
    {
      "id": 1,
      "title": "titleAAA",
      "body": "bodyAAA",
      "userId": 1
    }
  ],
  "users": [
    {
      "id": 1,
      "name": "xxxx"
    }
  ]
}