[FastAPI] APIRouter - 라우팅 설정하기

2026. 5. 2. 16:29·Backend/Python
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
'Backend/Python' 카테고리의 다른 글
  • [FastAPI] lifespan - 생명주기
  • [FastAPI] FastAPI에 대하여
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (297)
      • CS (40)
        • CV (2)
        • PS (37)
      • Reveiw (19)
        • Paper (19)
        • Github (0)
      • ML (13)
        • Pytorch (5)
      • Language (72)
        • Python (21)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (77)
        • React (8)
        • ReactNative (6)
        • SolidJS (20)
        • CSS (12)
      • Backend (47)
        • DB (18)
        • Node.js (11)
        • Python (3)
      • UI (3)
      • Automation (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    vscode
    frontend
    backend
    GAN
    SOLID
    API
    figma
    PyTorch
    Express
    ts
    PRISMA
    Git
    js
    FastAPI
    DB
    modal
    react
    nodejs
    deploy
    ReactNative
    ML
    Three
    CS
    ps
    mongo
    CSS
    python
    CV
    postgresql
    review
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.5
Rayi
[FastAPI] APIRouter - 라우팅 설정하기
상단으로

티스토리툴바