HTTP 메서드는 클라이언트가 서버에게 요청의 성격을 알리는 데 사용.
REST API는 이러한 HTTP 메서드를 사용해 CRUD 작업 수행 가능.
서버에 데이터 요청 시 사용. 요청 데이터는 URL에 포함되어 전송.
주로 데이터 조회에 사용.
REST API에서 사용 : 특정 리소스 조회 시 사용.
서버에 데이터 제출 시 사용. 요청 데이터는 요청 본문(body)에 포함되어 전송.
주로 새로운 데이터 생성 또는 제출에 사용.
REST API에서의 사용 : 새로운 리소스 생성 시 사용.
서버의 데이터 업데이트 시 사용. 요청 데이터는 요청 본문(body)에 포함되어 전송.
주로 기존 데이터 수정시 사용(PUT:리소스 전체 수정, PATCH:리소스 일부 수정)
REST API에서의 사용: 기존 리소스 수정 시 사용.
서버의 데이터 삭제 시 사용.
REST API에서의 사용: 특정 리소스 삭제 시 사용.
기본 URL
| 요청내용 | method | url |
|---|---|---|
| 게시글 추가 | POST | /posts |
| 모든 게시글 조회 | GET | /posts |
| 특정 게시글 조회 | GET | /posts/:id |
| 특정 게시글 업데이트 | PUT | /posts/:id |
| 특정 게시글 일부 수정 | PATCH | /posts/:id |
| 특정 게시글 삭제 | DELETE | /posts/:id |
Content-Type: application/json란?
Content-Type: application/json은 HTTP 요청 또는 응답 본문 데이터 형식을 명시하는 헤더. 본문 데이터가 JSON 형식임을 서버 또는 클라이언트에 알리는 역할 수행.
새로운 게시글 생성.
/postsPOSTContent-Type: application/json{
"title": "string",
"body": "string",
"userId": "integer"
}{
"id": "integer",
"title": "string",
"body": "string",
"userId": "integer"
}모든 게시글 조회 요청.
/postsGET[
{
"id": "integer",
"title": "string",
"body": "string",
"userId": "integer"
},
...
]특정 게시글 조회.
/posts/{id}GET{
"id": "integer",
"title": "string",
"body": "string",
"userId": "integer"
}특정 게시글 전체 수정(전체 업데이트)
/posts/{id}PUTContent-Type: application/json{
"title": "string",
"body": "string",
"userId": "integer"
}{
"id": "integer",
"title": "string",
"body": "string",
"userId": "integer"
}특정 게시글 일부 수정.
/posts/{id}PATCHContent-Type: application/json{
"title": "string",
"body": "string",
"userId": "integer"
}{
"id": "integer",
"title": "string",
"body": "string",
"userId": "integer"
}특정 게시글 삭제.
/posts/{id}DELETEReact에서 HTTP 요청을 보내는 대표적인 방법은 fetch API 또는 axios 라이브러리 사용하는 것.
아래는 fetch 사용 예시.
import React, { useState, useEffect } from "react";
function App() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
// get 요청 시, fetch는 method를 명시하지 않아도 됨.
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
const result = await response.json();
setData(result);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []);
return <div>{data ? <div>{data.title}</div> : <div>Loading...</div>}</div>;
}
export default App;
method 미작성 시 기본값은 GET.
response.json() 사용하여 JSON 데이터 파싱(문자열 → 객체 변환 과정 필요) 가능.
import React, { useState } from "react";
function App() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [response, setResponse] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: title,
body: body,
userId: 1,
}),
});
const result = await res.json();
setResponse(result);
} catch (error) {
console.error("Error creating data:", error);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Title"
/>
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Body"
/>
<button type="submit">Create Post</button>
</form>
{response && <div>Created Post ID: {response.id}</div>}
</div>
);
}
export default App;
method 명시 필수.
headers에 Content-Type 설정 필요.
body는 JSON.stringify 사용하여 문자열 변환 후 전송.