가상데이터 JSONPlaceholder 사용법

시작하기

backend server가 없을때 임시로 가상 데이터를 만들어 api 테스트를 해볼수 있습니다.

JSONPlaceholder

JSONPlaceholder url을 통해 리소스를 불러올수 있습니다.
JSONPlaceholder 홈페이지

API

JSONPlaceholder는 6가지의 기본 리소스를 가지고 있습니다.

1
2
3
4
5
6
/posts	100 posts
/comments 500 comments
/albums 100 albums
/photos 5000 photos
/todos 200 todos
/users 10 users

Api example

1
2
3
4
5
6
GET    /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1

사용법

axios, fetch등 http 콜을 통해서 데이터를 가져옵니다.

App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { useEffect } from 'react';
import axios from 'axios';

const App: React.FC = () => {
useEffect(() => {
const fetchData = async () => {
try {
const {data} = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log(data);
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);
return (
<div className="App"/>
)
}

JSON server

프로젝트 내부에 Json placeholder 데이터를 저장할수 있습니다.

설치하기

npm install -g json-server

사용법

프로젝트에서 서버를 켜줍니다.

1
json-server --watch db.json --port 8000

–port 8000 옵션은 db 서버를 8000번 포트로 설정해줍니다.

json-server 시작시 포트 및 API
api 콜을할때 8000포트로 요청을 하면 됩니다.
서버가 시작시 프로젝트에 db.json파일이 생성됩니다.

db.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}

api콜시에 db.json파일 내부의 값을 수정,삭제,추가등의 작업을 할수있습니다.

App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { useEffect } from 'react';
import axios from 'axios';

const App: React.FC = () => {
useEffect(() => {
const fetchData = async () => {
try {
const {data} = await axios.get('http://localhost:8000/comments');
console.log(data);
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);
return (
<div className="App"/>
)
}

JSONPlaceholder로 쉽게 api 테스트를 할수 있게 되었습니다.

Share