React

React : REST API 예시

고래고래00 2024. 6. 10. 19:51
1 게시글을 추가 POST /posts
2 모든 게시글 조회 GET /posts
3 특정 게시글 조회 GET /posts/:id
4 특정 게시글 정보 업데이트 PUT /posts/:id
5 특정 게시글 정보 일부 수정 PATCH /posts/:id
6 특정 게시글 정보 삭제 DELETE /posts/:id

POST /posts

새로운 게시물을 생성

  • URL: /posts
  • Method: POST
  • Headers:
    • Content-Type: application/json
  • Request Body:
{
  "title": "string",
  "body": "string",
  "userId": "integer"
}
  • Response:
    201 Created 
{
  "id": "integer",
  "title": "string",
  "body": "string",
  "userId": "integer"
}

       400 Bad Request: 요청 본문이 잘못되었을 때

 

GET /posts

모든 게시물을 조회

  • URL: /posts
  • Method: GET
  • Headers: 없음
  • Response:
    • 200 OK
[
  {
    "id": "integer",
    "title": "string",
    "body": "string",
    "userId": "integer"
  },
  ...
]

 

GET /posts/{id}

특정 게시물을 조회

  • URL: /posts/{id}
  • Method: GET
  • Headers: 없음
  • Response:

             200 OK

{
  "id": "integer",
  "title": "string",
  "body": "string",
  "userId": "integer"
}

           

             404 Not Found: 해당 ID의 게시물이 존재하지 않을 때

 

PUT /posts/{id}

특정 게시물을 업데이트 (전체 업데이트)

  • URL: /posts/{id}
  • Method: PUT
  • Headers:
    • Content-Type: application/json
  • Request Body:
    • Response:
      200 OK
{
  "id": "integer",
  "title": "string",
  "body": "string",
  "userId": "integer"
}

             

               400 Bad Request: 요청 본문이 잘못되었을 때

               404 Not Found: 해당 ID의 게시물이 존재하지 않을 때

 

PATCH /posts/{id}

특정 게시물을 부분적으로 업데이트

  • URL: /posts/{id}
  • Method: PATCH
  • Headers:
    • Content-Type: application/json
  • Request Body (모든 필드가 선택 사항):
{
  "title": "string",
  "body": "string",
  "userId": "integer"
}
  • Response:
    200 OK 
{
  "id": "integer",
  "title": "string",
  "body": "string",
  "userId": "integer"
}

       

       400 Bad Request: 요청 본문이 잘못되었을 때

       404 Not Found: 해당 ID의 게시물이 존재하지 않을 때

 

DELETE /posts/{id}

특정 게시물을 삭제

  • URL: /posts/{id}
  • Method: DELETE
  • Headers: 없음
  • Response:
    • 200 OK: 성공적으로 삭제되었을 때
    • 404 Not Found: 해당 ID의 게시물이 존재하지 않을 때

 

예시 코드

데이터를 가져오기 위한 GET 요청

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;

데이터를 생성하기 위한 POST 요청

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;