////
Search
📗

2. Router

RouterFastAPI에서 파일을 나눠서 관리하는 첫 관문이다.
지금까지 main.py에 모든 것을 다 넣었었는데, 엔드포인트파일별로 분리하는 것으로 생각하면 된다.
이로 인해 main.py앱 생성라우터 연결만 담당하고 실제 엔드포인트 함수들은 routers/*py로 옮기는 것을 목표로 한다.
현재까지는 아래와 같은 프로젝트 구조를 적용했다.
project/ app/ main.py
Python
복사
이제 이 구조를 다음과 같이 변경한다.
project/ app/ main.py routers/ *.py
Python
복사
routers 폴더를 따로 두는 이유는 엔드포인트가 늘어날수록 도메인별로 나누는 것유지보수 측면에서 압도적으로 유리하기 때문이다.
앞선 글(1. 기초)에서 대부분 숫자를 사용하고 계산하는 API를 예제로 사용했기 때문에 math.py를 만들고 몇 엔드포인트를 작성한다.
"""This module defines the API endpoints for operations such as sum and difference.""" from fastapi import APIRouter from pydantic import BaseModel router = APIRouter(prefix="/math", tags=["math"]) class SumRequest(BaseModel): """Pydantic model for summing two numbers.""" a: int b: int class SumResponse(BaseModel): """Pydantic model for the response of summing two numbers.""" result: int class DiffRequest(BaseModel): """Pydantic model for calculating the difference of two numbers.""" a: int b: int class DiffResponse(BaseModel): """Pydantic model for the response of calculating the difference of two numbers.""" result: int @router.post("/sum", response_model=SumResponse) def sum_numbers(body: SumRequest) -> SumResponse: """Endpoint to sum two numbers.""" return SumResponse(result=body.a + body.b) @router.post("/diff", response_model=DiffResponse) def diff_numbers(body: DiffRequest) -> DiffResponse: """Endpoint to calculate the difference of two numbers.""" return DiffResponse(result=body.a - body.b)
Python
복사
class를 작성하는 부분이나 함수를 작성하는 부분은 이전과 다르지 않다.
router = APIRouter(prefix="/math", tags=["math"])
Python
복사
이 부분만 기존 main.py에서 사용했던 것과 다르고 추가된 항목이 있다.
먼저, main.py에서는 APIRouter가 아닌 FastAPI를 사용했다. FastAPI()전체 앱을 하나 만드는 것이고, APIRouter엔드포인트 묶음을 만드는 것이다. 이제 main.py의 app은 하위 router 묶음을 관리하는 방향으로 가기 때문에 router 안에서는 엔드포인트 묶음을 기준으로 구현한다.
prefix는 이 라우터 안에 있는 모든 API는 /math로 시작하게한다. 기존에 <addr>/sum 이런 형태로 사용했는데 prefix를 지정하면 <addr>/<prefix>/sum 형태로 사용해야한다. tags/docs에서 해당 tag 그룹으로 묶여서 보이게 하는 속성이다.
router 작성을 끝냈다면 main.py도 수정을 해 주어야 한다.
"""This is the main entry point for the FastAPI application. It initializes the FastAPI app and includes the routers for different endpoints. """ from fastapi import FastAPI from app.routers.math import router as math_router app = FastAPI(title="FastAPI with Routers") # title은 /docs 상단에 표시 된다. app.include_router(math_router)
Python
복사
app.include_router(math_router)
Python
복사
include_routermain.py가 모든 엔드포인트를 다 알 필요 없이 라우터 단위로 플러그인처럼 붙일 수 있게 해주는 도구이다.