LoginSignup
95
87

More than 5 years have passed since last update.

JSON Server - 簡単にAPIのモックを作成

Last updated at Posted at 2015-11-26

Apiの実装がまだ終わっていないので、フロントの作業が進まない、、
そんな時にJSON Serverを使って、ローカル環境にAPIのモックアップを作ることができました。

インストール

npm install -g json-server

以上です。

JSONデータを用意

保存場所はデスクトップでもどこでも大丈夫です。
db.jsonといった名前でJSONファイルを保存してください。

{
   // ルーティングのためのキーが必要
    "list": [
        {
            "id": 1
            "name": "yamada"
            "gender": "M"
        },
        {
            "id": 2
            "name": "satou"
            "gender": "W"
        },
        {
            "id": 3
            "name": "tanaka"
            "gender": "M"
        }
    ]
}

Json-serverを起動

db.jsonを使って、Json-serverを起動します。

$ json-server --watch db.json

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/list

  Home
  http://localhost:3000

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

  Watching...

あとはhttp://localhost:3000/listにアクセスするだけで良いようです。

curl http://localhost:3000/list

[
  {
    "id": 1
    "name": "yamada"
    "gender": "M"
  },
  {
    "id": 2
    "name": "satou"
    "gender": "W"
  },
  ~ 
]

POST形式でリクエストする

POST形式でリクエストすると、db.jsonに送信したデータが保存できます。

curl -X POST http://localhost:3000/list -d name=fugafuga

{
  "name": "fugafuga",
  "id": 4
}

これで、"name": "fugafuga" なレコードが追加されます。

GruntやGulpを使わずとも簡単にAPIのモックを作ることができました。routesを設定すれば、もう少し色々できそう。気軽にモックを作成したい時に使っていきたいと思います。

参考

95
87
0

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
95
87