3
2

More than 3 years have passed since last update.

超簡単!Mock API開発:json-serverを試す

Posted at

今更ながらjson-serverを試します。

準備

node.jsが必要な以外は特にありません。
作業場作って(どこでもいいです)、json-serverをインストール。

cd
mkdir mock-api
cd mock-api

npm install -D json-server"

API定義(実装)

定義ファイル生成

jsonなら名前とかは何でもいい。

touch api.json

サンプルデータを実装

基準となるデータを入れる。

api.json
{
  "users": [
    {
      "id": 1,
      "name": "hoge",
      "age": 11
    },
    {
      "id": 2,
      "name": "foo",
      "age": 22
    }
  ]
}

実行

これでREST APIサーバが起動します。

npx json-server api.json

つまり、

  • GET(取得)
  • POST(登録)
  • PUT(更新)
  • DELETE(削除)

ができます。

試してみる

curlでサクッと試してみます。

取得

すべてを取得。

curl -X GET http://localhost:3000/users

1つだけ取得。

curl -X GET http://localhost:3000/users/1

登録

curl -X POST -d "name=bar&age=33"  http://localhost:3000/users

登録されたかは全てを取得してみるといいでしょう。インメモリに貯まるようです。

更新

curl -X PUT -d "name=bar&age=44" http://localhost:3000/users/3

削除

curl -X DELETE http://localhost:3000/users/3

すばらしい!!

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2