728x90
FastAPI에서 각 엔드포인트들의 주소를 하나로 묶어 사용하려면 APIRouter() 객체를 사용하면 됩니다.
include_router( )
우선 FastAPI 객체가 필요합니다.
from fastapi import FastAPI
app = FastAPI()
app의 include_router( ) 함수로 APIRouter( ) 객체를 연결할 수 있습니다.
from fastapi import FastAPI
from app.routes.news import news_router # APIRouter 객체
app = FastAPI()
app.include_router(news_router, prefix="/news", tags=["news"])
news_router | APIRouter 객체 이름
prefix | 라우팅된 엔드포인트들이 공통으로 가질 경로(접두어). 이 경우 news_router에 속한 모든 엔드 포인트들은 /news 경로를 루트로 가지게 됩니다.
tags | Swagger 문서*에서 엔드포인트를 그룹지을 이름(태그). 한 번에 여러 개의 태그를 붙일 수 있습니다.
*Swagger 문서 : API가 어떤 데이터를 주고받는지 UI(화면)로 보여주고, 그 자리에서 바로 테스트까지 해볼 수 있게 해주는 도구
APIRouter
app과 연결할 라우팅은 APIRouter( ) 객체로 관리합니다.
from fastapi import APIRouter
news_router = APIRouter()
APIRouter( )는 같은 라우팅으로 묶고자 하는 엔드포인트 함수 위에 데코레이션으로 작성하여 사용합니다. 만약 app.include_router( )에서 news_router의 prefix가 "/news"였다면,post_news_id( ) 엔드포인트는 "/news/id"로 요청할 때 호출됩니다.
# 해당 라우팅에서 루트 경로의 GET 메소드 엔드포인트 입니다.
@news_router.get("")
async def get_news():
# ...
# 해당 라우팅에서 '/id' 경로의 POST 메소드 엔드포인트 입니다.
@news_router.post("/id")
async def post_news_id():
# ...728x90
'Backend > Python' 카테고리의 다른 글
| [FastAPI] lifespan - 생명주기 (0) | 2026.05.11 |
|---|---|
| [FastAPI] FastAPI에 대하여 (0) | 2026.05.02 |