๐ FastAPI + uv ๋ก Todo App API ๋ง๋ค๊ธฐ (๊ฐ์ฅ ๊น๋ํ ๋ฐฉ๋ฒ!)
Source: Dev.to
Introduction
๋ฒ๊ฐ์ฒ๋ผ ๋น ๋ฅธ API๋ฅผ Python ํจํค์ง ํผ๋ ์์ด ๋ง๋ค๊ณ ์ถ์ผ์ ๊ฐ์?
์ด ๊ฐ์ด๋์์๋ FastAPI์ uv๋ฅผ ์ฌ์ฉํด Todo API๋ฅผ ๋ง๋ค ๊ฒ์
๋๋ค. uv๋ ๊ฐ์ ํ๊ฒฝ์ ์๋์ผ๋ก ๊ด๋ฆฌํ๊ณ , ์์กด์ฑ ํด๊ฒฐ์ ์ฒ๋ฆฌํ๋ฉฐ, ์ฌ๋ฌ๋ถ์ ์์
์ ๋ฐฉํดํ์ง ์๋ ์ฐจ์ธ๋ Python ํจํค์ง ๋งค๋์ ์
๋๋ค.
What is uv?
uv๋ pip๊ณผ virtualenv๋ฅผ ๋์ฒดํ๋ ํ๋์ ์ธ Python ํจํค์ง ๋งค๋์ ๋ก, ๋ค์์ ์ ๊ณตํฉ๋๋ค:
- ๐ ์ด๊ณ ์ ์์กด์ฑ ์ค์น
- ๐ฆ ์๋ ๊ฐ์ ํ๊ฒฝ ์์ฑ
- ๐งผ
requirements.txt์์ด ๊น๋ํ ํ๋ก์ ํธ ์ค์
Rust๋ก ๊ตฌํ๋์ด ๋น ๋ฅด๊ณ ์ฌํ ๊ฐ๋ฅํ Python ์ํฌํ๋ก์ ์ต์ ํ๋์ด ์์ต๋๋คโAPI, CLI ๋๊ตฌ, ๋ฐ์ดํฐ ์ฑ์ ์์ฑ๋ง์ถค์ ๋๋ค.
Project Setup
mkdir fastapi-todo && cd fastapi-todo
uv init --app
uv add fastapi --extra standard
Define the data model (models.py)
# models.py
from pydantic import BaseModel
class Todo(BaseModel):
id: int
title: str
completed: bool = False
Build the FastAPI application (main.py)
# main.py
from fastapi import FastAPI, HTTPException
from models import Todo
app = FastAPI()
todos: list[Todo] = []
@app.get("/")
def home():
return {"message": "Welcome to the FastAPI Todo App"}
@app.get("/todos")
def list_todos():
return todos
@app.post("/todos", status_code=201)
def add_todo(todo: Todo):
if any(t.id == todo.id for t in todos):
raise HTTPException(status_code=400, detail="Todo with this ID already exists.")
todos.append(todo)
return todo
@app.put("/todos/{todo_id}")
def update(todo_id: int, updated: Todo):
for i, t in enumerate(todos):
if t.id == todo_id:
todos[i] = updated
return updated
raise HTTPException(status_code=404, detail="Todo not found")
@app.delete("/todos/{todo_id}")
def delete(todo_id: int):
global todos
todos = [t for t in todos if t.id != todo_id]
return {"message": "Todo deleted"}
Run the application
uv run fastapi dev
์๋ฒ๋ http://127.0.0.1:8000์์ ์์๋ฉ๋๋ค.
Explore the interactive API docs at .