LoginSignup
1
1

More than 1 year has passed since last update.

1分でREST APIのモックサーバーを作る

Posted at

json-server を使ってAPIのモックを作る手順を備忘録として残す。

手順

  1. package.json の作成
  2. json-server のインストール
  3. jsonの追加
  4. サーバ起動

1. package.json の作成

Node.jsインストール済みの環境で、プロジェクトとなるディレクトリ(ここではapi-mock)を作成し、そのディレクトリへ移動したら、$ npm initコマンドを実行。

package.jsonが生成される。

※今回はyarnではなくnpmを用いている

package.json
{
  "name": "api-mock",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
}

2. json-server のインストール

$ npm install json-server --save-devを実行すると、開発環境にjson-serverがインストールされ、devDependenciesに追加される。同時に、package-lock.jsonnode_modulesが生成される。

package.json

〜〜〜〜省略〜〜〜〜
  "devDependencies": {
    "json-server": "^0.17.0"
  }

3. jsonの追加

レスポンスデータを記述するjsonファイルを作成する。

db.json
{
  "posts": [
    { "id": 1, "title": "春日", "author": "若林" }
  ],
  "comments": [
    { "id": 1, "body": "リトルトゥース", "postId": 1 }
  ]
}

4. サーバ起動

package.jsonのscriptsを追加。

package.json
{
  "name": "api-mock",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    // 追加
    "json-server": "json-server --watch db.json"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "json-server": "^0.17.0"
  }
}

$ npm run json-serverを実行。
以下の表示が出れば成功。
スクリーンショット 2022-06-24 1.02.09.png

http://localhost:3000/posts を開くとレスポンスを確認できる。

スクリーンショット 2022-06-24 1.03.11.png

1
1
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
1
1