👻

フロント開発中に使用するRestAPIのモック

2022/01/05に公開

json-server

https://github.com/typicode/json-server

install

npm install -g json-server

初期設定

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

run

json-server --watch db.json

デフォルト3000ポートで起動する
portの変更もできる

json-server --watch db.json --port 3001

select

Chrome ARC
#GET
http://localhost:3000/posts
response
[
  {
    "id": 1,
    "title": "json-server",
    "author": "typicode"
  }
]

Chrome ARC
#GET
http://localhost:3000/comments
response
[
  {
    "id": 1,
    "body": "some comment",
    "postId": 1
  }
]

Chrome ARC
#GET
http://localhost:3000/profile
response
{
  "name": "typicode"
}

insert

Chrome ARC
#POST
http://localhost:3000/posts
#application/json
{
    "id": 2,
    "title": "json-server2",
    "author": "typicode2"
}
response
{
"id": 2,
"title": "json-server2",
"author": "typicode2"
}
db.jsonが更新されている
{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    },
    {
      "id": 2,
      "title": "json-server2",
      "author": "typicode2"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

insert後のGET

Chrome ARC
#GET
http://localhost:3000/posts/2
response
{
  "id": 2,
  "title": "json-server2",
  "author": "typicode2"
}

update

Chrome ARC
#PUT
http://localhost:3000/posts
#application/json
{
    "id": 2,
    "title": "json-server-update",
    "author": "typicode-update"
}
response
{
  "id": 2,
  "title": "json-server-update",
  "author": "typicode-update"
}

update後のGET

Chrome ARC
#GET
http://localhost:3000/posts/2
response
{
  "id": 2,
  "title": "json-server-update",
  "author": "typicode-update"
}

delete

Chrome ARC
#DELETE
http://localhost:3000/posts/2
response
{}

delete後のGET

Chrome ARC
#GET
http://localhost:3000/posts/2
response
{}

Discussion