一、什么是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格式传递大量数据。
步骤:
- 用
pydantic.BaseModel定义数据模型 - 用类型注解绑定到处理函数
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 |
描述信息 |
今日核心总结
-
FastAPI是什么:高性能Python Web框架,能把Python函数变成网络接口。
-
路由 = 网址 + 处理函数 :用
@app.get("/路径")装饰器声明。 -
三种参数:
- 路径参数 :
/book/{id},在URL路径里,用Path()校验 - 查询参数 :
?key=value,在URL问号后面,用Query()校验 - 请求体参数 :JSON格式,用
pydantic.BaseModel定义,Field()校验
- 路径参数 :
-
三大校验工具 :
Path、Query、Field,参数几乎一样。