1단계
1단계 — 왜 Python · FastAPI 인가
25 분
1단계 — 왜 Python · FastAPI 인가
데이터 다루기 · 머신러닝 · 자동화 — Python 이 가장 합의된 언어입니다. FastAPI 가 들어오면서 웹 API 도 가벼움 + 타입 안정 둘 다 잡혔어요.
1. Python 이 선택되는 영역
- 데이터 처리 — pandas · numpy · polars
- 머신러닝 — PyTorch · TensorFlow · scikit-learn
- 크롤링 — Playwright · Scrapy · BeautifulSoup
- 자동화 · 스크립팅 — 짧은 코드로 빠른 결과
- 백엔드 API — FastAPI · Django · Flask
반대로 성능이 극한인 시스템 레벨 (OS · 드라이버) 은 Rust · C++ · Go.
2. FastAPI 의 매력 다섯
- 타입 힌트가 곧 검증 — 파라미터 타입 지정 → 자동 검증 + OpenAPI 문서
- 비동기 지원 —
async def자연스러움 - OpenAPI 자동 생성 —
/docs에서 Swagger UI,/redoc에서 ReDoc - 빠름 — Starlette + Pydantic 기반. Node.js 급 · Python 으로 가장 빠른 프레임워크
- 작은 표면적 — Spring 의 1/10 만 알아도 시작 가능
3. 첫 API 한 장
# main.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
tags: list[str] = []
@app.get("/")
def hello():
return {"message": "안녕하세요, FastAPI!"}
@app.post("/items")
def create_item(item: Item):
return {"created": item, "id": 1}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "query": q}
실행:
uv run uvicorn main:app --reload
자동 문서:
http://localhost:8000/docs— Swagger UI (실행 가능)http://localhost:8000/redoc— ReDoc (읽기 전용)http://localhost:8000/openapi.json— OpenAPI 스펙 원본
4. Python 패키지 매니저는 uv
# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
uv init my-api
cd my-api
uv add fastapi "uvicorn[standard]" pydantic
uv add --dev pytest ruff
uv run uvicorn main:app --reload
uv 는 pip + venv + Poetry 를 한 번에 대체. Rust 로 작성 · 10~100배 빠름 · 재현 가능한 lock 파일.
5. Pydantic — 데이터 검증
from pydantic import BaseModel, Field, EmailStr
class User(BaseModel):
id: int
email: EmailStr
nickname: str = Field(min_length=2, max_length=30)
age: int | None = Field(default=None, ge=0, le=150)
EmailStr— 이메일 포맷 검증Field(min_length=2)— 길이 제약ge/le— 범위None기본값 — 옵셔널
잘못된 데이터가 오면 FastAPI 가 자동으로 422 응답.
6. 의존성 주입
from fastapi import Depends
def get_db():
db = SessionLocal()
try: yield db
finally: db.close()
@app.get("/users")
def list_users(db = Depends(get_db)):
return db.query(User).all()
Depends 로 DB · 인증 · 권한 같은 공용 로직을 주입. 테스트 시 mock 으로 교체 쉬움.
7. 비동기
import httpx
@app.get("/external")
async def call_external():
async with httpx.AsyncClient() as client:
r = await client.get("https://api.example.com/data")
return r.json()
async def + await 조합으로 수천 동시 요청 처리.
8. Spring 과의 비교
| 측면 | Spring Boot 4 | FastAPI |
|---|---|---|
| 타입 | Java 정적 | Python 힌트 (선택) |
| 시작 시간 | 5~10 초 | 0.5 초 |
| 학습 곡선 | 가파름 | 완만함 |
| 생태계 | 엔터프라이즈 모든 것 | 데이터 · ML 특화 |
| 메모리 | 200 MB+ | 50 MB |
작은·중간 규모 API 또는 데이터 파이프라인은 FastAPI. 대규모 엔터프라이즈는 Spring.
9. 자주 걸리는 자리
uvicornvsgunicorn— 개발은 uvicorn, 프로덕션은 gunicorn + uvicorn workers- 동기 함수 섞어 씀 —
def+async def혼용 시 이벤트 루프 차단 - Pydantic v1 vs v2 — 2026 은 v2 표준.
.dict()→.model_dump() .env로딩 안 함 —pydantic-settings또는python-dotenv로 명시
10. 직접 해 보기
위 main.py 를 저장하고:
uv run uvicorn main:app --reload
curl http://localhost:8000
curl -X POST http://localhost:8000/items -H "Content-Type: application/json" \
-d '{"name":"사과","price":1000}'
그 후 브라우저 http://localhost:8000/docs 에서 직접 실행.
더 깊이
다음 단계
2단계에서는 이 단일 파일을 유지보수 가능한 폴더 구조 로 펼쳐 봅니다.