Fast Api 基础
FastApi基础
安装FastApi
pip install fastapi[all]
如果是uv
uv add fastapi[all]
创建项目
from fastapi import FastAPI # 创建 FastAPI 实例 app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World888"} # 访问 /hello 响应结果 msg: 你好 FastAPI @app.get("/hello") async def get_hello(): return {"msg": "你好 FastAPI"}
运行项目
# --reload:更改代码后自动重启服务器,其中“project”是python入口文件名 uvicorn project:app --reload
项目默认运行在127.0.0.1:8000,可使用浏览器访问,api接口文档在/docs
路由
路由就是 URL 地址和处理函数之间的映射关系,它决定了当用户访问某个特定网址时,服务器应该执行哪段代码来返回结果。
FastAPI 的路由定义基于 Python 的装饰器模式
# app:fastapi实例,即app = FastAPI() # get:请求方法 # ("/"):请求路径 @app.get("/") async def root(): return {"message": "hello world"}
参数
同一段接口逻辑,根据参数不同返回不同的数据,参数就是客户端发送请求时附带的额外信息和指令。参数的作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互。
| 参数分类 | 位置 | 作用 | 方法 |
|---|---|---|---|
| 路径参数 | URL路径的一部分,例如/book/{id} | 指向唯一的、特定的资源 | GET |
| 查询参数 | URL?之后,例如key1=value1 | 对资源集合进行过滤、排序、分页等操作 | GET |
| 请求体 | HTTP请求中的消息体body | 创建、更新资源、携带数据,例如json | POST、PUT等 |
Path 类型注解
FastApi允许为参数声明额外的信息和校验,路径参数使用Path 类型注解,使用时需要导入from fastapi import Path
| Path 参数 | 说明 |
|---|---|
... | 声明该参数是一个必填值 |
gt/ge | 大于/大于等于 |
lt/le | 小于/小于等于 |
description | 参数描述 |
min_length | 最小长度限制 |
max_length | 最大长度限制 |
from fastapi import FastAPI, Path app = FastAPI() @app.get("/author/{book_id}") async def get_name(name: int = Path( ..., gt=0, le=100, description=""" 书籍ID,取值范围1-100 """ )): return {"message": f"get {name}"}
查询参数 Query 类型注解
查询参数使用Query 类型注解,使用时需要导入from fastapi import Query
如下示例,调用curl http://127.0.0.1:8000/news/news_list?skip=10&limit=100
不传参则默认skip=1, limit=10
from fastapi import FastAPI, Query app = FastAPI() @app.get("/news/news_list") async def get_news_list( skip: int = Query(1, description="跳过的行数", lt=100), limit: int = Query(10, description="返回的记录数") ): return {"skip": skip, "limit": limit}
Field类型注解
请求体参数使用Field类型注解,其中的Field(…)有几种作用:
Field(...):该参数是一个必填项Field(10):该参数的默认值为10Field(None):该参数的默认值为None
使用时需要导入pydantic 的 Field 函数,from pydantic import BaseModel, Field
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() # 注册: 用户名和密码 → str class User(BaseModel): username: str = Field(default="张三", min_length=2, max_length=10, description="用户名,长度要求2-10个字") password: str = Field(min_length=3, max_length=20) @app.post("/register") async def register(user: User): return user
请求与响应
默认情况下,FastAPI 会自动将路径操作函数返回的 Python 对象(字典、列表、Pydantic 模型等),经由 jsonable_encoder 转换为JSON 兼容格式,并包装为 JSONResponse 返回。这省去了手动序列化的步骤,让开发者能更专注于业务逻辑。
如果需要返回非 JSON 数据(如 HTML、文件流),FastAPI 提供了丰富的响应类型来返回不同数据
| 响应类型 | 用途 | 示例 |
|---|---|---|
JSONResponse | 默认响应,返回JSON数据 | return {"key": "value"} |
HTMLResponse | 返回HTML内容 | return HTMLResponse(html_content) |
PlainTextResponse | 返回纯文本 | return PlainTextResponse("text") |
FileResponse | 返回文件下载 | return FileResponse(path) |
StreamingResponse | 流式响应 | 生成器函数返回数据 |
RedirectResponse | 重定向 | return RedirectResponse(url) |
例如,响应html格式:
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() # 接口 → 响应 HTML 代码 @app.get("/html", response_class=HTMLResponse) async def get_html(): return "<h1>这是一级标题</h1>"
响应文件
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() # 接口: 返回一张图片内容 @app.get("/file") async def get_file(): path = "./files/1.jpeg" return FileResponse(path)
自定义响应数据格式
response_model 是路径操作装饰器(如 @app.get或 @app.post)的关键参数,它通过一个 Pydantic 模型来严格定义和约束 API 端点的输出格式。这一机制在提供自动数据验证和序列化的同时,更是保障数据安全性的第一道防线。
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # 需求:books接口 → 响应数据格式 id、title、content class News(BaseModel): id: int title: str content: str @app.get("/books/{id}", response_model=News) async def get_news(id: int): return { "id": id, "title": f"这是第{id}本书", "content": "这是一本关于fastapi的书" }
异常处理
对于客户端引发的错误(4xx,如资源未找到、认证失败),应使用 fastapi.HTTPException 来中断正常处理流程,并返回标准错误响应 。
from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() # 需求:books接口 → 响应数据格式 id、title、content class News(BaseModel): id: int title: str content: str @app.get("/books/{id}", response_model=News) async def get_news(id: int): if id > 100: raise HTTPException(status_code=404, detail="id 不存在") return { "id": id, "title": f"这是第{id}本书", "content": "这是一本关于fastapi的书" }
中间件
中间件(Middleware)是一个在每次请求进入 FastAPI 应用时都会被执行的函数。它在请求到达实际的路径操作(路由处理函数)之前运行,并且在响应返回给客户端之前再运行一次。中间件为每个请求前后添加统一的处理逻辑(记录日志、身份认证、跨域、设置响应头、性能监控等)
定义中间件
@app.middleware("http")定义中间件,多个中间件的执行顺序__自下而上__
@app.middleware("http") async def middleware2(request, call_next): print("中间件2 start") response = await call_next(request) print("中间件2 end") return response
依赖注入
依赖项:可重用的组件(函数/类),负责提供某种功能或数据。使用依赖注入系统来共享通用逻辑,减少代码重复。
优点:
- 代码复用:一次编写,多处使用
- 解耦:业务逻辑与基础设施代码分离
- 易于测试:轻松地用模拟依赖替换真实依赖进行测试
如,多个列表分页页面,共享分页逻辑
from fastapi import FastAPI, Query, Depends # 2. 导入 Depends app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} # 分页参数逻辑共用: 新闻列表和用户列表 # 1. 依赖项 async def common_parameters( skip: int = Query(0, ge=0), limit: int = Query(10, le=60) ): return {"skip": skip, "limit": limit} # 3. 声明依赖项 → 依赖注入 @app.get("/news/news_list") async def get_news_list(commons=Depends(common_parameters)): return commons # 3. 声明依赖项 → 依赖注入 @app.get("/user/user_list") async def get_user_list(commons=Depends(common_parameters)): return commons
依赖注入的场景
-
处理请求参数(从请求中提取和验证参数)
-
共享业务逻辑(抽取封装多个路由公用的逻辑代码)
-
共享数据库连接(管理数据库会话的创建、使用、关闭)
-
安全和认证(验证用户身份、检查权限、角色要求等)