[FastAPI] add_api_route 파라미터

2025. 1. 30. 11:00·파이썬/Fast API
반응형

FastAPI의 add_api_route는 매우 강력한 기능을 제공하지만, 많은 매개변수로 인해 처음에는 이해하기 어려울 수 있습니다. 각 매개변수의 역할과 실제 활용 방법에 대해 알아보겠습니다.

필수 매개변수 이해하기

from fastapi import FastAPI, Response
from typing import List, Dict, Any

app = FastAPI()

# 기본적인 매개변수 사용
app.add_api_route(
    path="/users",              # 엔드포인트 경로
    endpoint=get_users,         # 실행될 함수
    methods=["GET"]             # HTTP 메서드
)

응답 관련 매개변수

응답 형식과 관련된 매개변수들은 API의 출력을 제어합니다.

from pydantic import BaseModel

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

app.add_api_route(
    path="/users/{user_id}",
    endpoint=get_user,
    response_model=UserResponse,           # 응답 데이터 모델
    status_code=200,                       # HTTP 상태 코드
    response_description="User found",     # 응답 설명
    response_model_exclude={"password"},   # 제외할 필드
    response_model_by_alias=True,         # 별칭 사용 여부
    responses={                           # 가능한 응답 정의
        404: {"description": "User not found"},
        400: {"description": "Invalid ID"}
    }
)

문서화 관련 매개변수

API 문서 자동 생성을 위한 매개변수들입니다.

app.add_api_route(
    path="/users",
    endpoint=create_user,
    tags=["users"],                    # API 그룹화
    summary="Create new user",         # API 요약
    description="Creates a new user in the system", # 상세 설명
    deprecated=False,                  # 사용 중단 여부
    operation_id="createUser",         # 작업 고유 ID
    include_in_schema=True            # 스키마 포함 여부
)

대규모 API 관리를 위한 구조화

API가 많아질 때는 다음과 같은 구조로 관리하면 효과적입니다:

# api/routes/base.py
from typing import Type
from fastapi import APIRouter

class BaseRouter:
    def __init__(self, prefix: str, tags: List[str]):
        self.router = APIRouter(prefix=prefix, tags=tags)

    def configure(self) -> APIRouter:
        self._register_routes()
        return self.router

    def _register_routes(self):
        raise NotImplementedError

# api/routes/users.py
class UserRouter(BaseRouter):
    def __init__(self):
        super().__init__(prefix="/users", tags=["users"])

    def _register_routes(self):
        self.router.add_api_route(
            path="",
            endpoint=self.get_users,
            methods=["GET"],
            response_model=List[UserResponse],
            summary="Get all users",
            description="Retrieves a list of all users"
        )

        self.router.add_api_route(
            path="/{user_id}",
            endpoint=self.get_user,
            methods=["GET"],
            response_model=UserResponse,
            summary="Get user by ID"
        )

    async def get_users(self):
        return await UserService.get_all()

    async def get_user(self, user_id: int):
        return await UserService.get_by_id(user_id)

# main.py
app = FastAPI()

def configure_routes(app: FastAPI):
    routers = [
        UserRouter(),
        ProductRouter(),
        OrderRouter()
    ]

    for router in routers:
        app.include_router(router.configure())

configure_routes(app)

고급 기능 활용

from fastapi import Depends, Security
from typing import Callable

class APIRouteManager:
    def __init__(self, app: FastAPI):
        self.app = app
        self.common_responses = {
            401: {"description": "Unauthorized"},
            403: {"description": "Forbidden"},
            500: {"description": "Internal Server Error"}
        }

    def add_secured_route(
        self,
        path: str,
        endpoint: Callable,
        auth_handler: Callable,
        **kwargs
    ):
        # 기본 응답 합치기
        responses = {
            **self.common_responses,
            **(kwargs.get("responses", {}))
        }

        # 의존성 추가
        dependencies = [
            Depends(auth_handler),
            *(kwargs.get("dependencies", []))
        ]

        self.app.add_api_route(
            path=path,
            endpoint=endpoint,
            dependencies=dependencies,
            responses=responses,
            **kwargs
        )

# 사용 예시
route_manager = APIRouteManager(app)
route_manager.add_secured_route(
    path="/admin/users",
    endpoint=admin_get_users,
    auth_handler=check_admin_token,
    methods=["GET"],
    summary="Admin: Get all users"
)

매개변수 설정 가이드라인

  1. 필수 설정
    • path: API 엔드포인트 경로
    • endpoint: 실행될 함수
    • methods: HTTP 메서드
  2. 권장 설정
    • response_model: 응답 데이터 구조 정의
    • status_code: 기본 HTTP 상태 코드
    • tags: API 그룹화
    • summary: API 간단 설명
    • responses: 가능한 응답 정의
  3. 선택적 설정
    • dependencies: 의존성 주입
    • deprecated: API 사용 중단 표시
    • operation_id: API 작업 식별자
    • response_model_exclude: 제외할 필드

이러한 구조화된 접근 방식을 통해 대규모 API도 효과적으로 관리할 수 있으며, 코드의 재사용성과 유지보수성을 높일 수 있습니다.

저작자표시 비영리 변경금지 (새창열림)

'파이썬 > Fast API' 카테고리의 다른 글

라우터 구현과 에러 처리 - Part 2  (0) 2025.01.31
프로젝트 구조와 기본 설정 - Part 1  (0) 2025.01.31
[FastAPI] add_api_route로 동적 라우팅 구현  (1) 2025.01.28
Pydantic 상속과 타입 어노테이션 활용  (0) 2025.01.27
[HTTP] 프론트엔드와 백엔드의 데이터 통신 Content-Type  (2) 2025.01.22
'파이썬/Fast API' 카테고리의 다른 글
  • 라우터 구현과 에러 처리 - Part 2
  • 프로젝트 구조와 기본 설정 - Part 1
  • [FastAPI] add_api_route로 동적 라우팅 구현
  • Pydantic 상속과 타입 어노테이션 활용
코샵
코샵
나의 코딩 일기장
    반응형
  • 코샵
    끄적끄적 코딩 공방
    코샵
    • 분류 전체보기 (727)
      • 스마트팜 (1)
      • 상품 추천 (223)
      • DataBase (0)
        • MongoDB (4)
        • PostgreSQL (0)
      • 하드웨어 (18)
      • 일기장 (4)
      • 파이썬 (130)
        • Basic (41)
        • OpenCV (8)
        • Pandas (15)
        • PyQT (3)
        • SBC(Single Board Computer) (1)
        • 크롤링 (14)
        • Fast API (29)
        • Package (6)
      • Unity (138)
        • Tip (41)
        • Project (1)
        • Design Pattern (8)
        • Firebase (6)
        • Asset (2)
      • Linux (4)
      • C# (97)
        • Algorithm (11)
        • Window (7)
      • TypeScript (51)
        • CSS (10)
      • Git (11)
      • SQL (5)
      • Flutter (10)
        • Tip (1)
      • System (1)
      • BaekJoon (6)
      • Portfolio (2)
      • MacOS (1)
      • 유틸리티 (1)
      • 서비스 (6)
      • 자동화 (3)
      • Hobby (10)
        • 물생활 (10)
        • 식집사 (0)
  • 인기 글

  • 태그

    셀레니움
    믈레코비타멸균우유
    cv2
    unity
    스크립트 실행
    리스트
    list
    ipcamera
    카페24리뷰이관
    쇼핑몰리뷰
    rtsp
    파이썬
    카페24리뷰
    라떼우유
    programming101
    리뷰이관
    appdevelopment
    programmerlife
    리뷰관리
    상품 리뷰 크롤링
    codingtips
    스마트스토어리뷰
    긴유통기한우유
    Python
    codingcommunity
    스크립트 실행 순서
    learntocode
    C#
    유니티
    devlife
  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
코샵
[FastAPI] add_api_route 파라미터
상단으로

티스토리툴바