Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体

一、什么是FastAPI?

一句话:FastAPI是一个Python Web框架,能把你的Python函数变成网络接口,让别人通过浏览器或代码调用。

特性 作用 大白话
高性能 天生支持异步 速度快,不卡顿
类型提示与验证 自动校验参数类型 传错类型直接报错,不用手动写校验
可交互式文档 自动生成API文档页面 浏览器里直接看到所有接口,还能在线测试

二、第一个FastAPI项目

运行命令

bash 复制代码
uvicorn main:app --reload
  • main:Python文件名(main.py
  • app:FastAPI实例的变量名
  • --reload:代码改了自动重启服务

交互式文档地址http://127.0.0.1:8000/docs(FastAPI自动生成,可以在这个页面直接测试接口)

三、虚拟环境

一句话:给你的项目一个"独立房间",不和别的项目共享Python包,避免版本冲突。

四、路由

一句话:路由就是"网址"和"处理函数"的对应关系。访问什么地址,就执行什么代码。

python 复制代码
@app.get("/")           # 访问 http://127.0.0.1:8000/
async def root():
    return {"message": "hello world"}

@app.get("/hello")      # 访问 http://127.0.0.1:8000/hello
async def get_hello():
    return {"msg": f"你好 FastAPI"}

路由三要素

部分 示例 含义
装饰器 @app.get(...) 声明这是一个GET请求
路径 "/hello" URL地址
处理函数 async def get_hello() 访问这个地址时执行的代码

五、三种参数类型

参数类型 位置 作用 请求方法
路径参数 URL路径的一部分 /book/{id} 指向唯一的特定资源 GET
查询参数 URL ? 之后 k1=v1&k2=v2 过滤、排序、分页 GET
请求体参数 HTTP请求的Body中 创建、更新资源,携带大量数据 POST、PUT

六、路径参数

位置 :URL路径的一部分,比如 /book/5 中的 5

基本用法

python 复制代码
@app.get("/book/{id}")
async def get_book(id: int):                 # int是类型注解,自动校验
    return {"id": id, "title": f"这是第{id}本书"}

加校验(Path函数)

python 复制代码
from fastapi import Path

@app.get("/book/{id}")
async def get_book(id: int = Path(..., gt=0, lt=100)):  # 必须填,大于0,小于100
    return {"id": id, "title": f"这是第{id}本书"}

@app.get("/author/{name}")
async def get_name(name: str = Path(..., min_length=2, max_length=10)):  # 长度2-10个字
    return {"msg": f"这是{name}的信息"}

Path常用参数

参数 说明
... 必填
gt / ge 大于 / 大于等于
lt / le 小于 / 小于等于
description 描述信息
min_length 最小长度
max_length 最大长度

七、查询参数

位置 :URL ? 之后,格式 k1=v1&k2=v2。比如 /news?skip=0&limit=10

python 复制代码
@app.get("/news/news_list")
async def get_news_list(skip: int, limit: int = 10):   # limit默认值为10
    return {"skip": skip, "limit": limit}
# 访问:http://127.0.0.1:8000/news/news_list?skip=0&limit=10

加校验(Query函数)

python 复制代码
from fastapi import Query

@app.get("/user")
async def get_user(user_id: int = Query(..., gt=0)):
    return {"user_id": user_id}

判断原则 :函数参数不在路径里(不是 {xxx})的,FastAPI自动当作查询参数。

八、请求体参数

位置:HTTP请求的消息体(Body)中,用JSON格式传递大量数据。

步骤

  1. pydantic.BaseModel 定义数据模型
  2. 用类型注解绑定到处理函数
python 复制代码
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(default="张三", min_length=2, max_length=10, description="用户名")
    password: str = Field(min_length=2, max_length=10)

@app.post("/register")
async def register(user: User):
    return user

Field常用参数(和Path、Query类似):

参数 说明
... 必填
default 默认值
gt / ge 大于 / 大于等于
lt / le 小于 / 小于等于
min_length 最小长度
max_length 最大长度
description 描述信息

今日核心总结

  1. FastAPI是什么:高性能Python Web框架,能把Python函数变成网络接口。

  2. 路由 = 网址 + 处理函数 :用 @app.get("/路径") 装饰器声明。

  3. 三种参数

    • 路径参数/book/{id},在URL路径里,用 Path() 校验
    • 查询参数?key=value,在URL问号后面,用 Query() 校验
    • 请求体参数 :JSON格式,用 pydantic.BaseModel 定义,Field() 校验
  4. 三大校验工具PathQueryField,参数几乎一样。

相关推荐
冷凝娇4 分钟前
【Pytest】2026 学习总结
学习·pytest
程序员小八77714 分钟前
Java 快速转 Go
java·python·golang
hh9501 小时前
Agent Plan x DeepSeek Harness — Token 预算管理与成本追踪体系技术
人工智能·学习·adg·火山引擎·adg成都社区
梦想的旅途21 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信
丰锋ff1 小时前
基于 Qt 的智能门禁系统
qt·学习
%472 小时前
DAY41
pytorch·python
小小帅呀2 小时前
学习 VLA 第 2 天:深度学习基础
人工智能·深度学习·学习
敲代码还房贷2 小时前
VMware17 + Ubuntu22.04 共享 完整步骤
linux·python·ubuntu
具身AGI2 小时前
人类第一视角数据走上评测台:物理AI 人类学习路线
学习
测试19982 小时前
Selenium 无法定位元素的几种解决方案
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例