FastAPI 入门指南:现代 Python Web 框架的快速构建利器
·
1. 什么是 FastAPI?
FastAPI 是一个现代、快速(高性能)的 Python Web 框架,用于构建 API。它基于标准 Python 类型提示,使用 Python 3.6+ 的特性,并建立在 Starlette(用于 Web 底层)和 Pydantic(用于数据验证)之上。
主要特性:
- 极高性能:与 Node.js 和 Go 相当,是现有 Python 框架中最快的之一。
- 快速开发:开发速度提升约 200% 至 300%。
- 减少错误:利用 Python 类型提示,减少约 40% 的人为错误。
- 直观:强大的编辑器支持,自动补全无处不在。
- 简单:易于使用和学习,文档详尽。
- 简短:最小化代码重复,每个参数声明可做多件事。
- 健壮:生产就绪的代码,带有自动交互式文档。
- 标准化:基于并完全兼容开放标准:OpenAPI(以前称为 Swagger)和 JSON Schema。
2. Python类型提示与FastAPI参数类型
FastAPI的核心特性之一是基于Python类型提示,这使得API开发更加直观、安全且高效。对于有Java背景的开发者,理解Python类型与Java类型的对应关系很有帮助。
Python与Java类型对照表
| Python类型 | 说明 | 示例 | Java对应 |
|---|---|---|---|
str |
字符串 | "张三" |
String |
int |
整数 | 18 |
int、Integer、Long |
float |
浮点数 | 99.9 |
double、Double |
bool |
布尔 | True |
boolean |
bytes |
字节数组 | b"hello" |
byte[] |
None |
空值 | None |
null |
list |
列表 | [1,2,3] |
List |
tuple |
元组 | (1,"Tom") |
不完全对应 |
set |
集合(去重) | {1,2,3} |
Set |
dict |
字典 | {"id":1} |
Map |
泛型类型(最常用)
| Python类型 | 说明 | Java对应 |
|---|---|---|
list[str] |
字符串列表 | List<String> |
list[int] |
整数列表 | List<Integer> |
dict[str,str] |
字符串Map | Map<String,String> |
dict[str,object] |
混合Map | Map<String,Object> |
set[str] |
字符串集合 | Set<String> |
tuple[int,str] |
元组 | 无对应 |
特殊类型
| Python类型 | 说明 | Java对应 |
|---|---|---|
Any |
任意类型 | Object |
| `str | None` | 可为空字符串 |
| `int | None` | 可为空整数 |
| `int | str` | 整数或字符串 |
Literal["A","B"] |
固定值枚举 | enum |
FastAPI 参数类型
| 类型 | 示例 | 说明 |
|---|---|---|
| Query参数 | id:int |
URL查询参数 |
| Path参数 | id:int |
URL路径参数 |
| Body对象 | UserReq |
请求体对象 |
| Form表单 | name:str=Form(...) |
表单数据 |
| 文件上传 | file:UploadFile |
单个文件上传 |
| 多文件 | files:list[UploadFile] |
多个文件上传 |
FastAPI的优势:通过类型提示,FastAPI能够自动:
- 数据验证:确保传入数据符合类型要求
- 序列化/反序列化:自动转换JSON与Python对象
- 文档生成:自动生成交互式API文档
- 编辑器支持:提供更好的代码补全和错误检查
3.安装FastApi
安装 FastAPI 核心 + 标准工具集,包括:
- uvicorn — ASGI 服务器
- httpx — HTTP 客户端(用于测试)
- jinja2 — 模板引擎
- python-multipart — 文件上传支持
- itsdangerous — 安全相关
pip install "fastapi[standard]"
验证安装
pip list
FastApi启动项目
第一个程序
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def file_download():
return {
'code': 200,
'msg': '发布成功'
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
访问接口文档
http://localhost:1451/docs
4. FastAPI 参数类型(详细介绍)
1. Query参数(URL查询参数)
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/user")
def get_user(
id: int,
name: str
):
return {
"id": id,
"name": name
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
GET /user?id=1&name=张三
2.Path参数(路径参数)
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/user/{id}")
def get_user(id: int):
return {
"id": id
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
GET /user/1
3.Body对象(JSON请求体)
import uvicorn
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class UserReq(BaseModel):
name: str
age: int
@app.post("/save")
def save(req: UserReq):
return req
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
POST /save
Content-Type: application/json
4.Body嵌套对象(AI项目经常用)
import uvicorn
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class Question(BaseModel):
title: str
score: int
class Paper(BaseModel):
paper_name: str
questions: list[Question]
@app.post("/paper")
def create_paper(req: Paper):
return req
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
{
"paper_name":"新能源汽车试卷",
"questions":[
{
"title":"什么是新能源汽车",
"score":10
},
{
"title":"动力电池分类",
"score":20
}
]
}
5.Form表单
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.post("/saveForm")
def save_form(
name: str = Form(...),
age: int = Form(...)
):
return {
"name": name,
"age": age
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
Content-Type: application/x-www-form-urlencoded
6.单文件上传
import uvicorn
from fastapi import UploadFile
app = FastAPI()
@app.post("/upload")
async def upload(
file: UploadFile
):
return {
"filename": file.filename
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
7.Form + 文件上传(最常见知识库上传就是这种。)
from fastapi import UploadFile,Form
import uvicorn
app = FastAPI()
@app.post("/knowledge/upload")
async def upload(
file: UploadFile,
courseId: int = Form(...),
courseName: str = Form(...)
):
return {
"courseId": courseId,
"courseName": courseName,
"filename": file.filename
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1451)
5.APIRouter 介绍及使用
APIRouter 是用来拆分和管理路由的工具,本质上就是“子路由模块”,用于把一个大型项目的接口拆成多个文件,避免所有接口都写在 main.py 里变得混乱。
1. APIRouter 是什么?
FastAPI 的 APIRouter 可以理解为:
一个“迷你 FastAPI 应用”,专门负责一组相关接口
比如:
用户模块:user_router
文件模块:file_router
课程模块:course_router
2. 为什么要用 APIRouter?
如果不用 APIRouter,你会这样写:
@app.get("/user/list")
@app.post("/user/create")
@app.get("/file/list")
@app.post("/file/upload")
所有接口堆在 main.py → 非常难维护
3. APIRouter 基本用法
(1)创建 router
from fastapi import APIRouter
router = APIRouter()
(2)定义接口
from fastapi import APIRouter, UploadFile, File, Form
# 封装的返回工具
from app.common import ApiResponse
router = APIRouter()
@router.post("/save/file/info", summary="添加文件知识库(pdf,word)")
def save_file_info(
file: UploadFile = File(...,description="文件"),
name: str = Form(...,description="课程名称")
):
return ApiResponse.success("添加成功")
(3)在 main.py 中使用 router
from fastapi import FastAPI
from app.api.user import router as user_router
app = FastAPI()
app.include_router(user_router, prefix="/user", tags=["用户模块"])
更多推荐



所有评论(0)