我正在开发一个FastAPI应用程序,我想创建多部分路径。我的意思是,我知道如何为所有REST方法创建这样的路径:
/api/people/{person_id}
但是怎么写呢?
/api/people/{person_id}/accounts/{account_id}
我可以继续在"people"中添加路线routes模块来创建额外的帐户路径,但我觉得应该有一个单独的"accounts"Routes模块可以包含在"people"路由模块,我只是错过了一些东西。
我是不是想太多了?除了我在评论中提到的,像这样的东西会有用吗?
from fastapi import FastAPI, APIRouter
app = FastAPI()
people_router = APIRouter(prefix='/people')
account_router = APIRouter(prefix='/{person_id}/accounts')
@people_router.get('/{person_id}')
def get_person_id(person_id: int) -> dict[str, int]:
return {'person_id': person_id}
@account_router.get('/{account_id}')
def get_account_id(person_id: int, account_id: int) -> dict[str, int]:
return {'person_id': person_id, 'account_id': account_id}
people_router.include_router(account_router)
app.include_router(people_router, prefix='/api')