Software Framework/FastAPI
[FastAPI] 라우팅 | study book
Bull_
2024. 8. 20. 18:25
Fast API의 라우팅
라우트는 api 요청 메소드를 수락하고 선택적으로 인수를 받을 수 있도록 허락해준다. 우리가 기존에 사용하던 단일 라우팅 방식은 다음과 같다.
from fastapi import FastAPI
from todo import todo_router
app = FastAPI()
@app.get("/")
async def welcome() -> dict:
return {
"message": "Hello World"
}
FastAPI() 인스턴스를 생성하여 라우트를 정의했었다. 하지만 여러 라우팅을 해야하는 상황이라면 다음 클래스를 사용해주는 것이 좋다.
FastAPI - APIRouter()
from fastapi import APIRouter
router = APIRouter()
@router.get("/hello")
async def say_hello() -> dict:
return {
"message": "Hello World"
}
Uvicorn은 Python ASGI 서버로, FastAPI 애플리케이션을 실행하는 데 사용된다. 그러나 APIRouter는 FastAPI에서 라우트들을 관리하기 위해 사용하는 클래스로, 직접 실행될 수 있는 애플리케이션 객체가 아니다. FastAPI() 클래스에 APIRouter() 인스턴스를 추가해야 한다. 이를 도와주는 include_router()를 사용하면 된다.
from fastapi import FastAPI, APIRouter
router = APIRouter()
@router.get("/items/")
async def read_items():
return {"message": "Hello World"}
app = FastAPI()
app.include_router(router)
참고 자료
https://product.kyobobook.co.kr/detail/S000201188332
FastAPI를 사용한 파이썬 웹 개발 | 압둘라지즈 압둘라지즈 아데시나 - 교보문고
FastAPI를 사용한 파이썬 웹 개발 | FastAPI의 핵심 기능과 5가지 기술 스택(몽고DB, 도커, pydantic, SQLModel, pytest)으로 이벤트 플래너 애플리케이션을 처음부터 끝까지 완성해본다!이 책의 강점은 ‘이
product.kyobobook.co.kr