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

相关推荐
言乐64 小时前
Python加速器4跨境网络加速器
运维·服务器·开发语言·网络·python
weixin_440730504 小时前
线程02-并发串行-互斥锁-Semaphore-Event
python·thread
爱吃苹果的日记本5 小时前
数据结构第三课(时间复杂度)
数据结构·学习
张小凡vip5 小时前
python--爬虫--经验积累的遇到的坑
开发语言·爬虫·python
毕业设计7036 小时前
(免费领源码) 基于微信小程序的预制菜商城的设计与实现25172-java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
vue.js·python·mysql·微信小程序·pycharm·微信开发者工具·推荐算法
疯狂打码的少年6 小时前
【计算机网络】IPv6基础(特点、表示法、与IPv4对比)
网络·笔记·计算机网络
xifangge20256 小时前
AGENTS.md 怎么写?涵盖 Java、Python、Vue、Go 的 8 套开箱即用模板
java·vue.js·python
大草原的小灰灰6 小时前
Python基础语法
开发语言·python
小葱炖豆腐7 小时前
python绘制excel折线图
python·excel·numpy·pandas·matplotlib
泡泡鱼(敲代码中)8 小时前
MySQL基础学习笔记:从数据模型到DDL全掌握
开发语言·数据库·笔记·学习·mysql