지난번 UV게시물에 작성한 fastapi설치 방법으로 진행
--> 지난번 UV환경 만들고, fastapi 설치 방법 보기
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return{"Hello":"world"}
get은 조회 용도
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return{"Hello":"World"}
@app.get("/item/{item_id}")
def read_item(item_id:int, q:str = None):
return {"item_id":item_id, "q":q}
router폴더를 만들고 그 안에 __init__.py 폴더와 엔드포인트.py 파일 생성 후 엔드포인트.py에 코드 분리시키기
main.py에 작성해둔 items 기능 코드를 items.py로 이동시킴
# router/items.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
그 후 main.py에 router/items.py 로 옮겨준 코드를 연결시킴
이때, prefix와 tags 그리고 description 지정할 수 있음
# main.py
from fastapi import FastAPI
from routers import items
app = FastAPI()
@app.get("/'")
def read_root():
return {"Hello":"World"}
app.include_router(items.router, prefix="/items" tags = ["items"])
연결시켜줄 때 prefix를 지정하면 router/items.py에서
@router.get("/items/{item_id}")를 @router("/{item_id}")로 바꿔줘야함.
이 라우터(items.router) 안에 있는 모든 경로(path) 앞에 자동으로 /items를 붙여줌
Swagger UI(/docs)에서 이 라우터에 속한 API들을 "items"라는 그룹으로 묶어줌.
Swagger UI(자동 문서)에서 API 설명을 보여주고 싶을 때 쓰는 옵션
# 엔드포인트(라우트) 전체 설명
# router/items.py
from fastapi import APIRouter
router = APIRouter()
@router.get(
"/{item_id}",
description="아이템 ID로 특정 아이템을 조회합니다. "
"q 파라미터를 넣으면 검색 조건이 추가됩니다."
)
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

# 개별 파라미터 설명
# router/items.py
from fastapi import APIRouter, Path, Query
router = APIRouter()
@router.get("/items/{item_id}")
def read_item(
item_id: int = Path(..., description="조회할 아이템의 고유 ID"),
q: str | None = Query(None, description="검색 필터에 사용할 문자열")
):
return {"item_id": item_id, "q": q}

| 타입 (Type) | 사용 위치 | 데이터 출처 | 예시 |
|---|---|---|---|
| Field | Pydantic 모델 내부 | Request Body(JSON) | {"name": "김철수"} |
| Query | 함수 파라미터 | URL 쿼리 스트링(Query String) | /items?q=search |
| Path | 함수 파라미터 | URL 경로(Path Parameter) | /items/123 |
| Body | 함수 파라미터 | Request Body(JSON 데이터) | {"title": "책 제목"} |
| Header | 함수 파라미터 | HTTP 요청 헤더 | Authorization: Bearer <token> |
| 구분 | Field | Body |
|---|---|---|
| 사용 위치 | Pydantic 모델 클래스 내부 | 엔드포인트 함수 파라미터 |
| 용도 | 모델의 각 필드 정의 (검증/메타데이터 추가) | Body 데이터를 직접 받기 |
| 언제 사용 | 구조화된 데이터 모델 정의 시 | 단순 값이나 특별한 경우 |
| 권장도 | 대부분의 경우 권장 | 특수한 경우에만 사용 |