Python/FastAPI

[FastAPI] (8) API Router 사용하기

yubi5050 2022. 12. 16. 16:20

API Router 사용하기

API Endpoints를 여러 .py 파일에 분리하여 작성하기 위한 APIRouter 라는 모듈이 존재한다.

해당 모듈을 사용하면 큰 갈래의 API들 끼리는 묶어 관리를 편하게 할 수 있다.

 

📁 Folder Structure

├── router
│   ├── router_1.py // health check router
│   └── router_2.py // servic1 router
└── app.py

 

Router 분기 작성

app.py에 router를 추가하고, prefix, tags 등을 설정한다.

 

🛠 app.py 

import uvicorn
from fastapi import FastAPI
from routers.router_1 import router as health_router
from routers.router_2 import router as svc1_router

# Create APP
def create_app() -> FastAPI:
    app = FastAPI()
    return app

app = create_app()

# Add Router
app.include_router(
    health_router, # health
    prefix="/api/health",
    tags= ['health_check']
)

app.include_router(
    svc1_router, # 
    prefix="/api/svc1",
    tags= ['service_1']
)

if __name__ == '__main__':
    uvicorn.run('app:app', reload=True, port=8000)

 

Router 파일 작성

🛠 router1.py : 서버나 DB 등에 대한 Health check api 작성

from fastapi import APIRouter

router = APIRouter(tags=["health_check"])

# Server Status Check
@router.get("/", responses={200: {"description": "ok"}},)
async def index() -> dict:
    return {"Running": True}

 

🛠 router2.py : 특정 서비스의 하위 비즈니스 로직 API 작성

from fastapi import APIRouter

router = APIRouter(tags=["service_1"])

# Service 1 Check
@router.get("/list", responses={404: {"description": "not found"}, 200: {"description": "ok"}},)
async def get_list() -> dict:
    # write service logic
    return {"Service List": 'ok'}

'''
@router.post("/list")
@router.delete("/list")
@router.patch("/list")
@router.put("/list")
'''

 

 

 

API Test

http://127.0.0.1:8000/docs 로 접속하면 다음과 같은 Swagger 화면에서 API 가 prefix에 맞게 잘 연결된 것을 알 수 있다.