이번에는 파이썬 프레임워크인 FastAPI로 RESTfulAPI를 구현해 보려고 합니다.
FastAPI에 대한 설명과 설치 방법은 이전 글을 참고하시면 됩니다.
Fast API란 / Fast API 설치
Fast API란?파이썬 3.6부터 제공되는 트렌디하고 높은 성능을 가진 파이썬 프레임워크이다.기존에 대중적으로 사용되고 있는 Django, Flask와 더불어 성능적으로 우세함을 보장하는 FastAPI는 이름에 걸
seulow-down.tistory.com
GET 기능 (전체 조회)
/posts/ 엔드포인트를 추가합니다. GET 요청을 처리하며, 등록된 모든 블로그 포스트를 조회할 수 있습니다.
get_all_posts 함수는 posts 딕셔너리에 저장된 모든 포스트를 리스트 형태로 반환합니다. 이렇게 하면 API를 통해 모든 블로그 포스트 데이터를 json 배열 형태로 확인할 수 있습니다.
@app.get("/posts/")
def get_all_posts():
return list(posts.values())
조회 요청
FastAPI가 지원하는 Swagger라는 API 플랫폼을 통해 (http://127.0.0.1:8000/docs에 접속하여) Try it out → Execute를 눌러 데이터를 조회할 수 있습니다.
GET 기능 (개별 조회)
특정 블로그 포스트를 조회하는 엔드포인트를 추가합니다. /posts/{post_id} 경로를 통해 클라이언트는 post_id를 사용해 특정 포스트를 요청할 수 있습니다. 또한 존재하지 않는 post_id를 요청할 경우, 에러 메세지와 함께 404 에러 응답을 받습니다.
@app.get("/posts/{post_id}")
def get_post(post_id: int):
if post_id not in posts:
raise HTTPException(status_code=404, detail="Post not found")
return posts[post_id]
조회 요청
http://127.0.0.1:8000/docs에 접속하여 Try it out → post_id 입력 → Execute를 눌러 개별 POST를 조회할 수 있습니다.
POST 기능
/posts/ 경로에 POST 요청을 보내면 제공된 데이터를 사용해 새 포스트를 생성합니다.
@app.post("/posts/", status_code=201)
def create_post(post: Post):
post_id = len(posts) + 1
posts[post_id] = post.dict()
return {"post_id": post_id, **post.dict()}
PUT 기능
/posts/ {post_id} 경로에 PUT 요청을 보내면, 지정된 post_id에 해당하는 포스트를 업데이트 할 수 있습니다.
@app.put("/posts/{post_id}")
def update_post(post_id: int, updated_post: Post):
if post_id not in posts:
raise HTTPException(status_code=404, detail="Post not found")
posts[post_id] = updated_post.dict()
return {"post_id": post_id, **updated_post.dict()}
수정 요청
http://127.0.0.1:8000/docs에 접속해 Try it out → post_id 입력 → Request body를 입력 후 Execute를 눌러 개별 POST를 수정할 수 있습니다.
Delete 기능
/post/{post_id} 경로에 Delete 요청을 보내면 지정된 post_id에 해당하는 포스트를 삭제할 수 있습니다.
@app.delete("/posts/{post_id}")
def delete_post(post_id: int):
if post_id not in posts:
raise HTTPException(status_code=404, detail="Post not found")
del posts[post_id]
return {"detail": "Post deleted"}
삭제 요청
http://127.0.0.1:8000/docs에 접속해 Try it out → post_id 입력 → Execute를 눌러 개별 POST를 삭제할 수 있습니다.
전체 코드
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional, Dict
app = FastAPI()
posts = {
1: {"title": "첫 번째 제목", "content": "첫 번째 글입니다.", "published": True, "rating": 5},
2: {"title": "두 번째 제목", "content": "두 번째 글입니다.", "published": True, "rating": 4}
}
# 블로그 포스트 모델
class Post(BaseModel):
title: str
content: str
published: bool = True
rating: Optional[int] = None
@app.get("/posts/")
def get_all_posts():
return list(posts.values())
@app.get("/posts/{post_id}")
def get_post(post_id: int):
if post_id not in posts:
raise HTTPException(status_code=404, detail="Post not found")
return posts[post_id]
@app.post("/posts/", status_code=201)
def create_post(post: Post):
post_id = len(posts) + 1
posts[post_id] = post.dict()
return {"post_id": post_id, **post.dict()}
@app.put("/posts/{post_id}")
def update_post(post_id: int, updated_post: Post):
if post_id not in posts:
raise HTTPException(status_code=404, detail="Post not found")
posts[post_id] = updated_post.dict()
return {"post_id": post_id, **updated_post.dict()}
@app.delete("/posts/{post_id}")
def delete_post(post_id: int):
if post_id not in posts:
raise HTTPException(status_code=404, detail="Post not found")
del posts[post_id]
return {"detail": "Post deleted"}
'개발 | 프로젝트 > API' 카테고리의 다른 글
Fast API란 / Fast API 설치 (0) | 2024.09.21 |
---|---|
카카오맵 API / Kakao Map API 사용하는 법 (0) | 2024.05.25 |