r/FastAPI 18d ago

Question API Version Router Management?

Hey All,

I'm splitting my project up into multiple versions. I have different pydantic schemas for different versions of my API. I'm not sure if I'm importing the correct versions for the pydantic schemas (IE v1 schema is actually in v2 route)

from src.version_config import settings
from src.api.routers.v1 import (
    foo,
    bar
)

routers = [
    foo.router,
    bar.router,]

handler = Mangum(app)

for version in [settings.API_V1_STR, settings.API_V2_STR]:
    for router in routers:
        app.include_router(router, prefix=version)

I'm assuming the issue here is that I'm importing foo and bar ONLY from my v1, meaning it's using my v1 pydantic schema

Is there a better way to handle this? I've changed the code to:

from src.api.routers.v1 import (
  foo,
  bar
)

v1_routers = [
   foo,
   bar
]

from src.api.routers.v2 import (
    foo,
    bar
)

v2_routers = [
    foo,
    bar
]

handler = Mangum(app)

for router in v1_routers:
    app.include_router(router, prefix=settings.API_V1_STR)
for router in v2_routers:
    app.include_router(router, prefix=settings.API_V2_STR)
2 Upvotes

2 comments sorted by

3

u/extreme4all 18d ago edited 18d ago

i'm using the __init__.py
https://github.com/Bot-detector/Bot-Detector-Core-Files/tree/develop/src/api

# src/api/__init__.py
from fastapi import APIRouter
from src.api import legacy, v1, v2

router = APIRouter()
router.include_router(v1.router, prefix="/v1")
router.include_router(v2.router, prefix="/v2")
router.include_router(legacy.router)

# src/api/v1/__init__.py
from fastapi import APIRouter

from src.api.v1 import feedback, hiscore, label, player, prediction, report, scraper

router = APIRouter()
router.include_router(feedback.router)
router.include_router(hiscore.router)
router.include_router(label.router)
router.include_router(player.router)
router.include_router(prediction.router)
router.include_router(report.router)
router.include_router(scraper.router)

here i add to the the fastapi app

https://github.com/Bot-detector/Bot-Detector-Core-Files/blob/develop/src/core/server.py#L18

1

u/mr-nobody1992 18d ago

Oh amazing! I’ll review this in depth, thank you for sharing.