from typing import Annotated, Literal
from fastapi import APIRouter, HTTPException, Path, Query, Request, Response
from .models import Entry, EntryPatch
router = APIRouter()
@router.get("/", tags=["status"])
async def home():
"""查看本机服务是否就绪。"""
return {"service": "records", "ready": True}
@router.get("/types/{kind}", tags=["status"])
def show_type(kind: Literal["list", "str", "int"]):
return {"list": [2, 4], "str": "北岸", "int": 7}[kind]
def current(request, record_id):
try:
return request.app.state.records[record_id]
except KeyError:
raise HTTPException(status_code=404, detail="record missing") from None
@router.get(
"/records/{record_id}", tags=["records"], operation_id="read_record",
summary="读取一条记录", description="**记录编号**来自路径,查询条件来自 URL。",
response_description="记录内容和实际查询参数",
)
async def read_record(request: Request,
record_id: Annotated[int, Path(ge=1, description="正整数记录号")],
q: Annotated[str | None, Query(description="可选搜索文本")] = None,
include_tax: bool = False, limit: int = 1):
"""只有未显式提供 description 时才使用这段说明。"""
record = current(request, record_id).copy()
if not include_tax:
record.pop("tax")
return {"record_id": record_id, "q": q, "limit": limit, "record": record}
@router.post("/records", status_code=201, tags=["records"])
async def create_record(request: Request, entry: Entry):
record_id = request.app.state.next_id
request.app.state.next_id += 1
request.app.state.records[record_id] = entry.model_dump()
return {"id": record_id, "entry": entry}
@router.put("/records/{record_id}", tags=["records"])
async def replace_record(request: Request, record_id: int, entry: Entry):
current(request, record_id)
request.app.state.records[record_id] = entry.model_dump()
return {"id": record_id, "entry": entry}
@router.patch("/records/{record_id}", tags=["records"])
async def patch_record(request: Request, record_id: int, patch: EntryPatch):
record = current(request, record_id)
record.update(patch.model_dump(exclude_unset=True))
return {"id": record_id, "entry": record}
@router.delete("/records/{record_id}", status_code=204, tags=["records"])
async def delete_record(request: Request, record_id: int):
current(request, record_id)
del request.app.state.records[record_id]
return Response(status_code=204)
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
入口文件:projects/fastapi-dev-lab/app/routes.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
routes.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a502.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip