🔧 백엔드 🌿 중급

FastAPI로 Python API 만들기

현대적인 Python 웹 프레임워크 FastAPI 마스터

⏱️ 6시간 👁️ 25 조회
📖 강좌 내용
# FastAPI로 Python API 만들기

## 학습 목표
FastAPI로 고성능 Python REST API를 개발합니다.

## 1. FastAPI란?
현대적이고 빠른 Python 웹 프레임워크입니다.
- 자동 API 문서 생성
- 타입 힌트 기반 검증
- 비동기 지원
- 뛰어난 성능

## 2. 설치 및 실행
pip install fastapi uvicorn

main.py:
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"Hello": "World"}

실행:
uvicorn main:app --reload

API 문서:
http://localhost:8000/docs (Swagger)
http://localhost:8000/redoc (ReDoc)

## 3. 경로 매개변수
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}

@app.get("/items/{item_id}")
def get_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

## 4. 쿼리 매개변수
@app.get("/items")
def get_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}

@app.get("/search")
def search(q: str, page: int = 1, size: int = 10):
return {"query": q, "page": page, "size": size}

## 5. Pydantic 모델
from pydantic import BaseModel, EmailStr
from typing import Optional

class UserCreate(BaseModel):
name: str
email: EmailStr
age: Optional[int] = None

class UserResponse(BaseModel):
id: int
name: str
email: str

@app.post("/users", response_model=UserResponse)
def create_user(user: UserCreate):
return {"id": 1, **user.dict()}

## 6. 요청 본문
@app.post("/items")
def create_item(item: Item):
return item

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}

## 7. 응답 모델
from typing import List

class Item(BaseModel):
id: int
name: str
price: float

@app.get("/items", response_model=List[Item])
def get_items():
return [
{"id": 1, "name": "Item1", "price": 10.0},
{"id": 2, "name": "Item2", "price": 20.0}
]

## 8. 의존성 주입
from fastapi import Depends

def get_db():
db = Database()
try:
yield db
finally:
db.close()

@app.get("/users")
def get_users(db = Depends(get_db)):
return db.query(User).all()

## 9. 에러 처리
from fastapi import HTTPException

@app.get("/users/{user_id}")
def get_user(user_id: int):
user = db.get(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user

## 10. 미들웨어
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

@app.middleware("http")
async def log_requests(request, call_next):
print(f"{request.method} {request.url}")
response = await call_next(request)
return response

## 11. 비동기 처리
@app.get("/async-items")
async def get_async_items():
items = await fetch_items_from_db()
return items

import httpx

@app.get("/external")
async def get_external():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
return response.json()

## 12. 인증
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/protected")
def protected_route(token: str = Depends(oauth2_scheme)):
return {"token": token}

@app.post("/token")
def login(username: str, password: str):
# 인증 로직
return {"access_token": "token123", "token_type": "bearer"}

## 13. 라우터 분리
routers/users.py:
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])

@router.get("/")
def get_users():
return []

main.py:
from routers import users
app.include_router(users.router)

## 14. 배포
pip install gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker

Docker:
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

## 추천 학습 순서
1. 기본 라우팅
2. Pydantic 모델
3. 의존성 주입
4. 인증 구현
5. 라우터 분리 및 배포