JSON 서버(json 서버)
오늘 우리는 1분 안에 모의 휴식 json 서버를 제공할 수 있는 매우 편리한 도구인 json-server를 살펴볼 것입니다. 일반 엔터프라이즈 애플리케이션에서는 많은 팀 및 타사 API와 함께 작업합니다. 타사 json-server를 호출해야 한다고 상상해 보십시오. 이 도구가 찾고 있는 도구입니다.
JSON 서버
JSON 서버 설치
컴퓨터에 NPM이 설치되어 있어야 합니다. 그렇지 않은 경우 이 게시물을 참조하여 NPM을 설치하십시오. 아래는 내 컴퓨터에 출력과 함께 json-server
를 설치하는 하나의 라이너 명령을 보여줍니다.
$ npm install -g json-server
npm WARN deprecated graceful-fs@3.0.8: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
/usr/local/bin/json-server -> /usr/local/lib/node_modules/json-server/bin/index.js
- bytes@2.3.0 node_modules/json-server/node_modules/raw-body/node_modules/bytes
/usr/local/lib
└─┬ json-server@0.8.10
├─┬ body-parser@1.15.1
│ └── bytes@2.3.0
├─┬ compression@1.6.1
│ └── bytes@2.2.0
├─┬ lowdb@0.10.3
│ └─┬ steno@0.4.4
│ └── graceful-fs@4.1.4
├─┬ update-notifier@0.5.0
│ └─┬ configstore@1.4.0
│ ├── graceful-fs@4.1.4
│ └─┬ write-file-atomic@1.1.4
│ └── graceful-fs@4.1.4
└─┬ yargs@4.7.0
├─┬ pkg-conf@1.1.2
│ └─┬ load-json-file@1.1.0
│ └── graceful-fs@4.1.4
└─┬ read-pkg-up@1.0.1
└─┬ read-pkg@1.1.0
└─┬ path-type@1.1.0
└── graceful-fs@4.1.4
$
json-server 버전 및 옵션 확인
$ 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]
$
JSON 서버 실행
이제 json-server를 시작할 시간입니다. 다음은 직원 json 데이터가 포함된 샘플 파일입니다.
{
"employees": [
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
},
{
"name": "David",
"salary": "5000",
"id": 2
}
]
}
여기서 중요한 점은 배열 즉 직원의 이름입니다. JSON 서버는 이를 기반으로 REST API를 생성합니다. 위의 파일로 json-server를 시작합시다.
$ json-server --watch db.json
\{^_^}/ hi!
Loading db.json
Done
Resources
https://localhost:3000/employees
Home
https://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
이 터미널을 닫지 마십시오. 그렇지 않으면 json-server가 종료됩니다. 다음은 샘플 CRUD 요청 및 응답입니다.
JSON 서버 GET - 모든 직원 읽기
$ curl -X GET -H "Content-Type: application/json" "https://localhost:3000/employees"
[
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
},
{
"name": "David",
"salary": "5000",
"id": 2
}
]
$
json-server에서 ID를 기반으로 직원 가져오기
$ curl -X GET -H "Content-Type: application/json" "https://localhost:3000/employees/1"
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
}
$
JSON 서버 POST - 직원 만들기
$ curl -X POST -H "Content-Type: application/json" -d '{"name": "Lisa","salary": "2000"}' "https://localhost:3000/employees"
{
"name": "Lisa",
"salary": 2000,
"id": 3
}
$
JSON 서버 PUT - 직원 데이터 업데이트
$ curl -XPUT -H "Content-Type: application/json" -d '{"name": "Lisa", "salary": "8000"}' "https://localhost:3000/employees/3"
{
"name": "Lisa",
"salary": 8000,
"id": 3
}
$
JSON 서버 DELETE - 직원 삭제
$ curl -X DELETE -H "Content-Type: application/json" "https://localhost:3000/employees/2"
{}
$ curl -GET -H "Content-Type: application/json" "https://localhost:3000/employees"
[
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
},
{
"name": "Lisa",
"salary": 8000,
"id": 3
}
]
$
간단한 JSON으로 볼 수 있듯이 json-server는 우리가 사용할 데모 API를 생성합니다. 모든 PUT, POST, DELETE 요청은 db.json
파일에 저장됩니다. 이제 GET 및 DELETE에 대한 URI는 동일합니다. 유사하게 POST 및 PUT 요청에 대해서도 동일합니다. 간단한 매핑 파일을 사용하여 사용자 지정 URI도 만들 수 있습니다.
json-server 사용자 지정 경로
json-server가 사용할 사용자 지정 경로로 파일을 만듭니다. <코드>routes.json
{
"/employees/list": "/employees",
"/employees/get/:id": "/employees/:id",
"/employees/create": "/employees",
"/employees/update/:id": "/employees/:id",
"/employees/delete/:id": "/employees/:id"
}
또한 json-server 포트를 변경하고 타사 API처럼 시뮬레이션할 수 있습니다. 실제 서비스가 준비되면 기본 URL을 변경하기만 하면 됩니다. 이제 아래와 같이 JSON 서버를 다시 시작하십시오.
$ json-server --port 7000 --routes routes.json --watch db.json
(node:60899) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
\{^_^}/ hi!
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...
우리가 정의한 맞춤 경로를 보여줍니다.
사용자 지정 경로가 있는 json-server 예제
다음은 사용자 지정 경로를 사용한 일부 명령 및 출력의 예입니다.
$ curl -X GET -H "Content-Type: application/json" "https://localhost:7000/employees/list"
[
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
},
{
"name": "Lisa",
"salary": 8000,
"id": 3
}
]
$ curl -X GET -H "Content-Type: application/json" "https://localhost:7000/employees/get/1"
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
}
$ curl -X POST -H "Content-Type: application/json" -d '{"name": "Lisa","salary": "2000"}' "https://localhost:7000/employees/create"
{
"name": "Lisa",
"salary": 2000,
"id": 4
}
$ curl -XPUT -H "Content-Type: application/json" -d '{"name": "Lisa", "salary": "8000"}' "https://localhost:7000/emloyees/update/4"
{
"name": "Lisa",
"salary": 8000,
"id": 4
}
$ curl -XDELETE -H "Content-Type: application/json" "https://localhost:7000/employees/delete/4"
{}
$ curl -GET -H "Content-Type: application/json" "https://localhost:7000/employees/list"
[
{
"id": 1,
"name": "Pankaj",
"salary": "10000"
},
{
"name": "Lisa",
"salary": 8000,
"id": 3
}
]
$
JSON 서버는 정렬, 검색 및 페이지 매김과 같은 다른 유용한 옵션을 제공합니다. 이것이 json-server에 대한 전부입니다. 데모 Rest JSON API를 생성해야 할 때마다 도구로 이동합니다. 참조: json-server GitHub