1. 라우터 분리
📚 학습 목표
- 라우터 분리에 대해 이해함
🧭 라우터 분리란?
- FastAPI는 기본적으로 하나의 main.py 같은 파일에 모든 API 경로(/users, /items, /posts 등)를 정의할 수 있음
- 프로젝트가 커지면 수백 개의 API가 생기기 때문에 이를 기능별로 파일로 나눠 관리하는 것이 라우터 분리임
from fastapi import FastAPI, APIRouter
app = FastAPI()
user_router = APIRouter()
@user_router.get("/users")
def read_users():
return [{"username": "user1"}, {"username": "user2"}]
app.include_router(user_router)
✅ 왜 라우터 분리가 좋은가?
- 코드의 가독성 향상
- 유지보수 용이성 증가
- 파일 단위의 기능별 코드 관리 가능
2. Swagger UI와 ReDoc
📚 학습 목표
- API 문서화를 이해하고 활용하는 방법을 학습함
📘 Swagger UI와 ReDoc란?
- FastAPI는 API를 만들면 자동으로 문서화를 지원함
- 별도의 설정 없이 브라우저에서 API를 테스트할 수 있음
- 기본적으로 Swagger UI와 ReDoc을 제공함
🛠️ 작동 방식
- Pydantic 모델, Path/Query/Body 파라미터의 타입 힌트, docstring, status code 등을 기반으로 자동 문서를 생성함
🔐 커스터마이징 방법
- UI의 제목, 설명, 라이선스 정보 등을 수정할 수 있음
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="My API", description="API 설명", version="1.0.0")
class Item(BaseModel):
name: str
price: float
description: str | None = None
@app.post("/items/")
def create_item(item: Item):
return item
🚧 Swagger vs ReDoc 비교
- Swagger UI: 인터랙티브한 API 문서화, 빠른 테스트 지원
- ReDoc: 보다 심플하고 읽기 쉬운 문서 스타일, 큰 스키마에 적합
3. 의존성 주입 (Dependency Injection)
📚 학습 목표
- 의존성 주입의 개념과 FastAPI에서의 구현 방법을 학습함
🔎 의존성 주입이란?
- 외부의 설정, 객체, 기능을 직접 생성하지 않고 외부에서 주입받아 사용하는 방식임
- 예시: DB 연결, 사용자 인증
from fastapi import FastAPI, Depends
app = FastAPI()
def common_parameters(q: str = None, limit: int = 10):
return {"q": q, "limit": limit}
@app.get("/items/")
def read_items(params=Depends(common_parameters)):
return params
4. 미들웨어
📚 학습 목표
- 미들웨어의 개념과 구현 방법을 학습함
✅ 미들웨어란?
- HTTP 요청과 응답을 가로채서 처리하는 기능임
from fastapi import FastAPI, Request
import time
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
5. CORS 설정 (Cross-Origin Resource Sharing)
📚 학습 목표
- CORS에 대해 이해하고 설정하는 방법을 학습함
🌐 CORS란?
- CORS (Cross-Origin Resource Sharing)는 브라우저의 동일 출처 정책(Same-Origin Policy)에 대한 보안 제약을 완화하기 위한 표준임
- 다른 도메인에서 리소스를 요청할 때 허용된 출처만 접근할 수 있도록 서버에서 설정해야 함
🛠️ FastAPI에서 CORS 설정 방법
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost", # 로컬 개발 환경
"http://localhost:8000", # 로컬 서버
"https://myapp.com", # 프로덕션 서버
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def root():
return {"message": "Hello, World!"}
🔍 주요 설정 파라미터 설명
- allow_origins: CORS 요청을 허용할 출처 리스트 (필수)
- allow_credentials: 쿠키를 포함한 인증 정보를 허용할지 여부 (기본값: False)
- allow_methods: 허용할 HTTP 메서드 리스트 (기본값: ["GET"])
- allow_headers: 허용할 HTTP 헤더 리스트 (기본값: ["Accept", "Accept-Language", "Content-Language", "Content-Type"])
본 후기는 [한글과컴퓨터x한국생산성본부x스나이퍼팩토리] 한컴 AI 아카데미 (B-log) 리뷰로 작성되었습니다.
'HancomAI_academy' 카테고리의 다른 글
[스나이퍼팩토리] 한컴AI아카데미 - 활성 함수 (Activation Function) 정리 (0) | 2025.05.18 |
---|---|
[스나이퍼팩토리] 한컴AI아카데미 - ML 정리 (1) | 2025.05.11 |
FastAPI 강의 3주차 요약 및 심화 정리 (0) | 2025.05.06 |
[스나이퍼팩토리] 한컴AI아카데미 - 추가 정리 (0) | 2025.04.27 |
[스나이퍼팩토리] 한컴AI아카데미 - 데이터 분석 과제 모음 (4월 21일~23일) (0) | 2025.04.27 |