null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
☆ Star
FastAPI 미니 프로젝트 — Todo API
#fastapi
#python
#project
#todo
#crud
@devpc
|
2026-04-27 06:24:27
|
GET /api/v1/nodes/279?nv=1
History:
v1 (2026-04-27) (Latest)
0
Views
0
Calls
# FastAPI 미니 프로젝트 — Todo API 지금까지 배운 내용을 종합하여 완전한 CRUD API를 만들어봅니다. ## 목표 ``` GET /todos → 전체 조회 POST /todos → 생성 GET /todos/{id} → 단일 조회 PUT /todos/{id} → 수정 DELETE /todos/{id} → 삭제 ``` --- ## 전체 코드 ```python # main.py from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Optional from datetime import datetime app = FastAPI(title="Todo API") # 인메모리 DB (실제 프로젝트에서는 SQLAlchemy 사용) todos_db: dict[int, dict] = {} next_id = 1 # --- 스키마 --- 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 created_at: str # --- 라우트 --- @app.get("/todos", response_model=list[TodoResponse]) async def list_todos(completed: Optional[bool] = None): todos = list(todos_db.values()) if completed is not None: todos = [t for t in todos if t["completed"] == completed] return todos @app.post("/todos", response_model=TodoResponse, status_code=201) async def create_todo(todo: TodoCreate): global next_id new_todo = { "id": next_id, "title": todo.title, "description": todo.description, "completed": False, "created_at": datetime.now().isoformat(), } todos_db[next_id] = new_todo next_id += 1 return new_todo @app.get("/todos/{todo_id}", response_model=TodoResponse) async def get_todo(todo_id: int): if todo_id not in todos_db: raise HTTPException(status_code=404, detail="Todo not found") return todos_db[todo_id] @app.put("/todos/{todo_id}", response_model=TodoResponse) async def update_todo(todo_id: int, todo: TodoUpdate): if todo_id not in todos_db: raise HTTPException(status_code=404, detail="Todo not found") stored = todos_db[todo_id] update_data = todo.model_dump(exclude_unset=True) stored.update(update_data) return stored @app.delete("/todos/{todo_id}", status_code=204) async def delete_todo(todo_id: int): if todo_id not in todos_db: raise HTTPException(status_code=404, detail="Todo not found") del todos_db[todo_id] ``` --- ## 실행 및 테스트 ```bash uvicorn main:app --reload # httpx로 테스트 (Python) import httpx BASE = "http://127.0.0.1:8000" # 생성 r = httpx.post(f"{BASE}/todos", json={"title": "FastAPI 공부"}) print(r.json()) # {"id": 1, "title": "FastAPI 공부", ...} # 조회 r = httpx.get(f"{BASE}/todos/1") # 수정 r = httpx.put(f"{BASE}/todos/1", json={"completed": True}) # 삭제 r = httpx.delete(f"{BASE}/todos/1") ``` --- ## 다음 단계 이 인메모리 버전을 실제 DB와 연결하려면: 1. `SQLAlchemy` + `alembic` 추가 2. `AsyncSession`으로 비동기 DB 쿼리 3. `Depends(get_db)`로 DB 세션 의존성 주입 4. 환경변수로 `DATABASE_URL` 설정 완성된 API는 `uvicorn main:app --host 0.0.0.0 --port 8000`으로 서버에 배포할 수 있습니다.
// COMMENTS
Newest First
ON THIS PAGE