FastAPI:APIRouter
lastmod 2026-11-10created 2023-07-312 edits
APIRouter는 FastAPI 에서 경로 작업(엔드포인트)들을 묶어 모듈 단위로 관리하는 클래스이다. 큰 애플리케이션을 파일별로 나누어 각 라우터에 @router.get() 같은 데코레이터로 경로를 등록한 뒤 app.include_router() 로 합치며, 이때 공통 prefix, tags, dependencies, responses 를 한 번에 지정할 수 있다. 데코레이터 대신 add_api_route() 메서드를 쓰면 클래스의 메서드 같은 호출 가능 객체를 동적으로 등록할 수 있다.
add_api_route
from fastapi import FastAPI, APIRouter
class Hello:
def __init__(self, name: str):
self.name = name
self.router = APIRouter()
self.router.add_api_route("/hello", self.hello, methods=["GET"])
def hello(self):
return {"Hello": self.name}
app = FastAPI()
hello = Hello("World")
app.include_router(hello.router)