1
2

初心者向け:JSONサーバー入門

Posted at

JSONサーバーとは?

JSONサーバーは、シンプルなJSONファイルを使ってモック(擬似)REST APIを作成できるツールです。
これを使うと、実際のバックエンドが完成していなくても、手軽にAPIをシミュレーションできます。

前提

  • Node.jsをマシンにインストールしておくこと

手順

  1. 新しいNode.jsプロジェクトを初期化します(すでにプロジェクトがある場合はスキップ):

    npm init -y
    
  2. JSONサーバーをインストール:

    npm install json-server
    
  3. db.jsonというファイルを作成し、以下のように初期データを記述:

    {
      "posts": [
        { "id": 1, "title": "Hello World", "author": "John Doe" }
      ],
      "comments": [
        { "id": 1, "body": "Nice post!", "postId": 1 }
      ],
      "profile": { "name": "John Doe" }
    }
    
  4. JSONサーバーをポート5000で起動:

    npx json-server --watch db.json --port 5000
    

watchオプションを使用することで、db.jsonファイルに加えた変更をリアルタイムでサーバーに反映できます。

JSONサーバーへのアクセス

エンドポイントの例

GET /posts

すべての投稿が取得できます。

[
  {
    "id": 1,
    "title": "Hello World",
    "author": "John Doe"
  }
]

POST /posts

リクエストボディに新しい投稿のデータを含めましょう。

{
  "title": "New Post",
  "author": "Jane Doe"
}

成功すると、新しい投稿が追加されます。

{
  "id": 2,
  "title": "New Post",
  "author": "Jane Doe"
}

PUT /posts/1

IDが1の投稿を更新します。リクエストボディに更新内容を含めましょう。

{
  "title": "Updated Post",
  "author": "John Doe"
}

成功すると、更新された投稿が返されます。

{
  "id": 1,
  "title": "Updated Post",
  "author": "John Doe"
}

DELETE /posts/1

IDが1の投稿を削除します。成功すると、削除された投稿のデータが返されます。

{
  "id": 1,
  "title": "Hello World",
  "author": "John Doe"
}

より詳細な情報が必要な方は、JSONサーバーのGitHubリポジトリをご覧ください。

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