如果需要构建应用程序或api,很少将所有的内容都放入一个文件中。
fastapi提供了一个方便的工具可灵活的构建应用。(类似于flask的蓝图)
假如文件结构如下:
.
├── app
│ ├── init.py
│ ├── main.py
│ └── routers
│ ├── init.py
│ ├── items.py
│ └── users.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/", tags=["users"])
async def read_users():
return [{
"username": "Foo"}, {
"username": "Bar"}]
@router.get("/users/me", tags=["users"])
async def read_user_me():
return {
"username": "fakecurrentuser"}
@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
return {
"username": username}
可以将APIRouter视为“迷你FastAPI”类。
支持所有相同的选项。
所有相同的参数,响应,依赖性,标签等。
然后在main文件中:
from fastapi import Depends, FastAPI, Header, HTTPException
from .routers import items, users
app = FastAPI()
async def get_token_header(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
app.include_router(users.router)
app.include_router(
items.router,
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={
404: {
"description": "Not found"}},
)