Python 24일 코스 - Day 24: 미니 프로젝트 FastAPI Todo API

Day 24: 미니 프로젝트 - FastAPI Todo API

FastAPI 설치

pip install fastapi uvicorn

프로젝트 구조

todo-api/
├── main.py          # API 엔드포인트
├── models.py        # 데이터 모델
├── database.py      # DB 연결
└── requirements.txt

데이터 모델 정의

# models.py
from pydantic import BaseModel
from typing import Optional

class TodoCreate(BaseModel):
    title: str
    description: Optional[str] = None

class TodoUpdate(BaseModel):
    title: Optional[str] = None
    description: Optional[str] = None
    completed: Optional[bool] = None

class TodoResponse(BaseModel):
    id: int
    title: str
    description: Optional[str]
    completed: bool

API 엔드포인트 구현

# main.py
from fastapi import FastAPI, HTTPException
from models import TodoCreate, TodoUpdate, TodoResponse

app = FastAPI(title="Todo API")

todos: dict[int, dict] = {}
next_id = 1

@app.get("/todos", response_model=list[TodoResponse])
def get_todos():
    return list(todos.values())

@app.post("/todos", response_model=TodoResponse, status_code=201)
def create_todo(todo: TodoCreate):
    global next_id
    new_todo = {
        "id": next_id,
        "title": todo.title,
        "description": todo.description,
        "completed": False,
    }
    todos[next_id] = new_todo
    next_id += 1
    return new_todo

@app.get("/todos/{todo_id}", response_model=TodoResponse)
def get_todo(todo_id: int):
    if todo_id not in todos:
        raise HTTPException(status_code=404, detail="할 일을 찾을 수 없습니다")
    return todos[todo_id]

@app.patch("/todos/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo: TodoUpdate):
    if todo_id not in todos:
        raise HTTPException(status_code=404, detail="할 일을 찾을 수 없습니다")
    stored = todos[todo_id]
    update_data = todo.model_dump(exclude_unset=True)
    stored.update(update_data)
    return stored

@app.delete("/todos/{todo_id}", status_code=204)
def delete_todo(todo_id: int):
    if todo_id not in todos:
        raise HTTPException(status_code=404, detail="할 일을 찾을 수 없습니다")
    del todos[todo_id]

서버 실행과 API 문서

uvicorn main:app --reload

# 브라우저에서 자동 API 문서 확인
# http://127.0.0.1:8000/docs   (Swagger UI)
# http://127.0.0.1:8000/redoc  (ReDoc)

API 테스트

메서드경로설명
GET/todos전체 목록 조회
POST/todos새 할 일 생성
GET/todos/{id}단건 조회
PATCH/todos/{id}수정
DELETE/todos/{id}삭제

오늘의 연습문제

  1. SQLite 데이터베이스를 연동하여 서버를 재시작해도 데이터가 유지되게 하세요.
  2. 할 일에 우선순위(high, medium, low) 필드를 추가하고 필터링 API를 구현하세요.
  3. pytest와 TestClient로 모든 엔드포인트의 테스트를 작성하세요.

이 글이 도움이 되었나요?