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,参数几乎一样。

相关推荐
智写-AI1 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
铅笔侠_小龙虾2 小时前
Rust 学习目录
开发语言·学习·rust
yuhuofei20212 小时前
【Python入门】了解掌握Python中函数的基本使用
python
一个有温度的技术博主3 小时前
【VulnHub 实战】DC-1 靶机渗透测试笔记(一):信息收集与主机发现
服务器·网络·笔记
渣渣灰飞3 小时前
MySQL 系统学习 第五阶段:企业级 MySQL 实战开发 第二章:RBAC 权限系统设计
android·学习·mysql
白帽小阳3 小时前
2026前端面试题!(附答案及解析)
javascript·网络·python·安全·web安全·网络安全·护网行动
六bring个六3 小时前
open Harmony中分布式软总线的学习任务清单
分布式·学习·c/c++·open harmony
乱写代码4 小时前
Python开发技巧--类型注解Literal
python