FastAPI教程-路径参数 作者:马育民 • 2026-08-12 21:37 • 阅读:10002 # 介绍 路径参数(Path Parameters):把变量写在URL路径里面,例如 `/items/{item_id}`,`{item_id}` 就是路径参数。 比如哔站的视频链接:`https://www.bilibili.com/video/视频id` # 基础用法 路径传入id,返回不同的视频 **参数类型:**默认参数类型是 **字符串**,即使传数字。 ```python from fastapi import FastAPI app = FastAPI() @app.get('/video/{id}') def get_video(id: str): if id == '1': video = { 'title': '王者荣耀视频', } elif id == '2': video = { 'title': '吃鸡视频', } else: video = { 'message': '视频不存在', } return video ``` ### 测试 - 访问:`http://127.0.0.1:8000/video/1`,返回 ``` { "title": "王者荣耀视频" } ``` - 访问:`http://127.0.0.1:8000/video/3`,返回 ``` { "message": "视频不存在" } ``` # 类型声明 直接在函数参数写类型,FastAPI自动做 **解析、校验** ```python @app.get('/student/{id}') def get_student(id: int): if id == 1: student = { 'name': '李雷', 'age': 21, } elif id == 2: student = { 'name': '韩梅梅', 'age': 21, } else: student = { 'message': '没有此学号的学生', } return student ``` ### 测试 - 访问 `http://127.0.0.1:8000/student/1`,显示下面内容: ``` { "name": "李雷", "age": 21 } ``` - 访问 `http://127.0.0.1:8000/student/abc`,由于参数是 `abc`,转 `int` 类型报错,显示如下: ``` { "detail": [ { "type": "int_parsing", "loc": [ "path", "id" ], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc" } ] } ``` ### 支持类型 - `str`:默认类型,几乎可以接受任意类型参数 - `int` - `/items/123`,转成 `int` 类型的 `123` - `/items/12.3`、`/items/abc`,校验报错422 - `float` - `/price/99.99`,转成 `float` 类型的 `99.99` - `/price/100`,转为100.0 - `bool` - `true`、`1`,转为 `True` - `false`、`0`,转为 `False` - `bytes`:URL 传入 base64 编码字符串,自动解码为 bytes。 - `uuid.UUID` - 访问 `/user/550e8400‑e29b‑41d4‑a71c‑95a26cf3d479`正常转换 - 格式不对直接报 `422` 错误 # 路径参数顺序优先级 FastAPI 按**从上到下匹配路由**,精确路径要放在变量路径前面。 ### 错误写法: ```python @app.get("/users/{user_id}") async def get_user(user_id: int): return {"user_id": user_id} # 永远不会被命中,上面路由把 /users/me 匹配成 user_id="me" @app.get("/users/me") async def get_me(): return {"me": True} ``` ### 正确写法 **关键:**精确路由放前面 ```python @app.get("/users/me") async def get_me(): return {"me": True} @app.get("/users/{user_id}") async def get_user(user_id: int): return {"user_id": user_id} ``` # 多路径参数 一个url可以多个`{}`,函数参数一一对应: ```python @app.get("/users/{user_id}/orders/{order_id}") async def get_order(user_id: int, order_id: str): return {"user_id": user_id, "order_id": order_id} ``` 访问 `/users/10/orders/ord_001`。 # OpenAPI自动文档 - SwaggerUI:`http://127.0.0.1:8000/docs` - ReDoc:`http://127.0.0.1:8000/redoc` 路径参数会自动出现在文档,支持在线调试;校验失败自动返回标准422 JSON错误响应。 原文出处:/show_1GW3qnCYGJjZ.html