蓝色天空.知识 · 实践 · 创造
我的收藏
FastAPI 教程目录 38章
FastAPI / LEARN BY DOING

FastAPI 基本路由与路径匹配

从同步根路由开始,观察整数路径参数和可选查询参数的不同来源。

学完这一章,你能够

  • 从同步根路由开始,观察整数路径参数和可选查询参数的不同来源。

路由如何选中函数

FastAPI() 创建应用。@app.get("/") 注册根路径上的 GET。请求到达时先匹配 HTTP 方法和路径,再运行关联的函数。同步 def 路由可以直接返回一个字典,由框架生成 JSON 响应。

解压工程后运行 python -m uvicorn main:app --host 127.0.0.1 --port 8000。冒号左边是模块,右边是应用对象。开发用的 --reload 另行启用。先请求 GET /,确认应用确实返回就绪信息。

路径占位符与可选查询

GET /observations/42 匹配 /observations/{sample_id},并按注解将 42 转为整数。GET /observations/no 无法转换,返回 422,detail.loc 指向 path、sample_id。

q: str | None = None 声明可省略的查询参数。省略 q 时得到 None,显式写 ?q= 得到空字符串,写 ?q=north 则得到 north。旧式 str = None 能表达默认值,却无法在类型注解中说明可能得到 None。

从规范核对路由

查看 /openapi.json 中的 /observations/{sample_id},可看到 sample_id 位于 path 且必填,q 位于 query 且可省略。/docs 可用表单发请求。本站从浏览器实际访问了根路径和带参数的路由。

运行同步路由并比较查询参数

含完整源码 · 73 行
展开查看收起
python
"""蓝色天空网 FastAPI 请求与响应实验。"""
from pathlib import Path
from typing import Annotated

from fastapi import Cookie, FastAPI, Header, HTTPException, Query
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles

from models import Observation, StationInput, StationOutput


app = FastAPI(title="蓝色天空网请求实验", docs_url=None)
app.mount("/docs-assets", StaticFiles(directory=Path(__file__).with_name("vendor")), name="docs-assets")


@app.get("/docs", include_in_schema=False)
def docs():
    return get_swagger_ui_html(
        openapi_url="/openapi.json", title=app.title,
        swagger_js_url="/docs-assets/swagger-ui-bundle.js",
        swagger_css_url="/docs-assets/swagger-ui.css",
        swagger_favicon_url="data:,", swagger_ui_parameters={"validatorUrl": None},
    )


@app.get("/", operation_id="read_status")
def status():
    return {"service": "observations", "ready": True}


@app.get("/observations")
def listing(skip: Annotated[int, Query(ge=0)] = 0, limit: Annotated[int, Query(ge=1, le=50)] = 10):
    return {"skip": skip, "limit": limit}


@app.get("/observations/{sample_id}")
def read_sample(sample_id: int, q: str | None = None):
    return {"sample_id": sample_id, "q": q}


@app.post("/observations", operation_id="submit_observation")
def create(sample: Observation) -> Observation:
    return sample


@app.get("/context")
def context(client_tag: Annotated[str | None, Header()] = None,
            view_mode: Annotated[str | None, Cookie()] = None):
    return {"client_tag": client_tag, "view_mode": view_mode}


@app.get("/jump")
def jump():
    return RedirectResponse(url="/observations", status_code=307)


@app.get("/look-up/{sample_id}")
def look_up(sample_id: int):
    if sample_id != 42:
        raise HTTPException(status_code=404, detail="sample missing")
    return {"sample_id": sample_id}


@app.get("/with-header")
def with_header():
    return JSONResponse({"sample_id": 42}, headers={"X-Lab-Result": "verified"})


@app.post("/stations", response_model=StationOutput)
def create_station(station: StationInput):
    return {"id": 1, **station.model_dump()}
根路径返回就绪状态。整数路径可匹配。省略 q、传空字符串和传 north 会得到不同结果。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本章实验包 (mbskycom202611a506.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:FastAPI

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a506.zip

下载课程关联工程包:FastAPI

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

省略使用 None,q= 提供了长度为零的字符串。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习