基本写法

from fastapi import FastAPI

app = FastAPI()

@app.get(“/”)
def read_root():
return {“hello”: “world”}

@app.get(“/items/{item_id}”)
def read_item(item_id: int, q: str | None = None):
return {“item_id”: item_id, “q”: q}

使用 Pydantic 的请求体和响应体

from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class Item(BaseModel):
name: str
price: float
tags: list[str] = []

@app.post(“/items”, response_model=Item, status_code=201)
def create_item(item: Item):
# item 已经是一个 Pydantic 实例,已经验证并转换
return item

APIRouter 的示例(模块化)

app/
  main.py
  api/
    __init__.py
    users.py
    items.py
    router.py

users.py:

from fastapi import APIRouter, Depends
router = APIRouter()

@router.get(“/”)
def list_users():
return [{“id”:1, “name”:”Alice”}]

@router.get(“/{user_id}”)
def get_user(user_id: int):
return {“id”:user_id}

router.py(汇总):

from fastapi import APIRouter
from .users import router as users_router
from .items import router as items_router

api_router = APIRouter()
api_router.include_router(users_router, prefix=”/users”, tags=[“users”])
api_router.include_router(items_router, prefix=”/items”, tags=[“items”])

main.py:

from fastapi import FastAPI
from app.api.router import api_router

app = FastAPI(title=”My App”)
app.include_router(api_router, prefix=”/api”)

include_router()

是 FastAPI 中用来把一个子路由模块挂载到主路由上的方法,用于组织和管理多个路由文件,让项目结构更清晰、模块化。

  • router 要挂载的子路由对象(APIRouter 实例)
  • prefix 统一的路径前缀,如 /users,给该路由组的所有接口自动加上前缀
  • tags 用于 Swagger 文档分组显示
  • dependencies 给该路由组统一加依赖,如统一验证 Token

.

作者 admin

百度广告效果展示