Skip to main content

JSON Server (json-server) Xây dựng REST JSON Webservice trong một phút

JSON Server 

JSON Server là một Node module giúp bạn tạo nhanh một REST JSON webservice cung cấp dữ liệu demo trong một phút cài đặt

Link package JSON Server: https://www.npmjs.com/package/json-server

Cài đặt JSON Server

Đầu tiên để sử dụng bạn cần cài đặt vào dự án thông qua NPM:

npm install -g json-server

Sau khi cài đặt bạn check verson bằng lệnh: json-server -v hoặc cần xem các option trong config bằng lệnh json-server -help

$ json-server -v
0.8.10

$ json-server -help
/usr/local/bin/json-server [options] <source>

Options:
  --config, -c       Path to config file           [default: "json-server.json"]
  --port, -p         Set port                                    [default: 3000]
  --host, -H         Set host                               [default: "0.0.0.0"]
  --watch, -w        Watch file(s)                                     [boolean]
  --routes, -r       Path to routes file
  --static, -s       Set static files directory
  --read-only, --ro  Allow only GET requests                           [boolean]
  --no-cors, --nc    Disable Cross-Origin Resource Sharing             [boolean]
  --no-gzip, --ng    Disable GZIP Content-Encoding                     [boolean]
  --snapshots, -S    Set snapshots directory                      [default: "."]
  --delay, -d        Add delay to responses (ms)
  --id, -i           Set database id property (e.g. _id)         [default: "id"]
  --quiet, -q        Suppress log messages from output                 [boolean]

Hướng dẫn sử dụng JSON Server

Bước 1: Đầu tiên bạn tạo một file db.json với fake data

{
  "employees": [
    {
      "id": 1,
      "name": "Pankaj",
      "salary": "10000"
    },
    {
      "name": "David",
      "salary": "5000",
      "id": 2
    }
  ]
}

Bước 2: Đây là một danh sách employees, giờ chúng ta chạy một webservice với fake data ở trên với lệnh

json-server --watch db.json

Bạn sẽ thấy màn hình hiển thị 

  Loading db.json
  Done

  Resources
  http://localhost:3000/employees

  Home
  http://localhost:3000

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

Bước 3: Mở browser để kiểm tra REST JSON WebService

Bây giờ bạn vào browser và mở url http://localhost/employees sẽ thấy trả về json từ file db.json 

  {
    "id": 1,
    "name": "Pankaj",
    "salary": "10000"
  },
  {
    "name": "David",
    "salary": "5000",
    "id": 2
  }

hoặc bạn muốn get employee với id cụ thể bằng url http://localhost/employees/1

{
  "id": 1,
  "name": "Pankaj",
  "salary": "10000"
}

Đó là cách get, vậy put, post hay delete data mới thì sao

Bước 4: POST/ PUT/ DELETE với fake data với JSON Server

Với POST - Dùng Update dữ liệu employee với id là 1

fetch('https://localhost:3000/employees/1', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  // body: '{"name": "Lisa","salary": "2000"}',
  body: JSON.stringify({
    'name': 'Lisa',
    'salary': '2000'
  })
});

Với PUT - Tạo mới employee

fetch('https://localhost:3000/employees/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  // body: '{"name": "Lisa", "salary": "8000"}',
  body: JSON.stringify({
    'name': 'Lisa',
    'salary': '8000'
  })
});

Với DELETE - Xoá một employee

fetch('https://localhost:3000/employees/1', {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json'
  }
});

Sau mỗi lần bạn có thể reload browser để check lại sự thay đổi trong data trả về từ JSON Server

Nâng cao với JSON Server

JSON-Server Custom Routes

Tạo file routes.json để tạo thay đổi route mặc định của JSON Server

{
  "/employees/list": "/employees",
  "/employees/get/:id": "/employees/:id",
  "/employees/create": "/employees",
  "/employees/update/:id": "/employees/:id",
  "/employees/delete/:id": "/employees/:id"
}

Khởi động JSON Server, với option port để change port bạn muốn

json-server --port 7000 --routes routes.json --watch db.json

Kết quả

Loading db.json
  Loading routes.json
  Done

  Resources
  https://localhost:7000/employees

  Other routes
  /employees/list -> /employees
  /employees/get/:id -> /employees/:id
  /employees/create -> /employees
  /employees/update/:id -> /employees/:id
  /employees/delete/:id -> /employees/:id

  Home
  https://localhost:7000

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

Filter trong JSON-Server 

Bạn có thể dụng filter trong params, ví dụ như

GET /employees?name=Lisa
GET /employees?id=1&id=2

Tìm kiếm với JSON-Server

GET /employees?q=lisa