Python Web后端开发 · 篇4

RESTful API设计:FastAPI现代框架

API设计规范、FastAPI框架与自动数据验证

现代Web开发越来越倾向于前后端分离:前端(React/Vue/小程序)负责界面展示,后端只提供数据接口——这就是API。本文将学习RESTful API设计原则,并使用FastAPI框架搭建一个完整的待办事项API,体验自动数据验证和API文档生成的强大能力。

目录

1 什么是API?前后端分离架构
2 RESTful设计原则
3 FastAPI入门与Pydantic模型
4 自动API文档(Swagger UI)
5 依赖注入
6 实战:待办事项API完整CRUD

一、什么是API?

API(Application Programming Interface,应用编程接口)是程序之间通信的"约定"。在Web开发中,API就是后端暴露给前端的数据接口。

打个比方:餐厅的服务员就是API——你告诉服务员你要什么(请求),服务员从厨房(后端)取来菜品(响应)端给你。你不需要知道厨房怎么做的。

前后端分离架构

Web浏览器
手机App
小程序
→
API
→
后端服务
数据库

同一个API可以同时服务于Web、App、小程序等多种客户端

二、RESTful设计原则

REST(Representational State Transfer)是一种API设计风格。遵循REST原则的API叫做RESTful API,它有几个核心约定:

  1. URL代表资源(名词),HTTP方法代表操作(动词)
  2. URL使用复数名词:/todos 而不是 /getTodo
  3. 使用正确的HTTP方法:GET获取、POST创建、PUT更新、DELETE删除
  4. 返回合适的状态码:200成功、201已创建、404不存在、500服务器错误
操作
好的RESTful设计
坏的设计
获取全部
GET /todos
GET /getAllTodos
获取单个
GET /todos/5
GET /getTodoById?id=5
创建
POST /todos
POST /createNewTodo
更新
PUT /todos/5
POST /updateTodo
删除
DELETE /todos/5
GET /deleteTodo?id=5
小贴士:HTTP方法速记

记住CRUD和HTTP方法的对应:Create→POST, Read→GET, Update→PUT/PATCH, Delete→DELETE。GET和DELETE不应该修改数据。

三、FastAPI入门与Pydantic模型

FastAPI是一个现代的Python Web框架,基于Python类型提示,具有高性能、自动数据验证和自动文档生成等特点。

对比项
Flask
FastAPI
定位
通用Web框架
专注API开发
数据验证
需要第三方库
内置Pydantic
API文档
需要第三方
自动生成Swagger
性能
同步
原生异步(ASGI)
模板渲染
内置Jinja2
不擅长(API为主)

安装FastAPI和运行服务器:

Bash 安装FastAPI
# 安装FastAPI和uvicorn服务器
pip install fastapi uvicorn

# 运行(假设文件名为main.py)
uvicorn main:app --reload
Python main.py - FastAPI入门
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
# 定义数据模型(Pydantic自动验证)
class Todo(BaseModel):
title: str # 必填字符串
description: Optional[str] = None # 可选
completed: bool = False # 默认False
# GET请求 - 返回JSON
@app.get("/")
def root():
return {"message": "Hello FastAPI!"}
# GET请求 - 带路径参数
@app.get("/items/{item_id}")
def read_item(item_id: int):
# item_id 自动验证为int类型!
return {"item_id": item_id}
# POST请求 - 自动验证请求体
@app.post("/todos")
def create_todo(todo: Todo):
# todo 已经是验证过的Todo对象
return {"created": todo.title}

FastAPI最强大的特性之一是Pydantic数据模型。你只需定义Python类的类型注解,FastAPI就会自动:

四、自动API文档(Swagger UI)

FastAPI启动后,你可以直接访问自动生成的交互式API文档,无需任何额外配置:

Swagger UI能做什么?

  1. 查看所有API端点、方法和参数
  2. 直接在浏览器中发送测试请求
  3. 查看请求/响应的数据格式示例
  4. 生成客户端SDK代码
小贴士:给API添加描述

使用 @app.post("/todos", summary="创建待办", description="创建一个新的待办事项") 可以让自动生成的文档更清晰易懂。

五、依赖注入

依赖注入是FastAPI的核心设计模式——它允许你把通用的逻辑(如数据库连接、身份验证)抽取为独立的函数,然后在多个路由中复用。

Python 依赖注入示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from fastapi import FastAPI, Depends, HTTPException
app = FastAPI()
# 定义一个依赖项:验证token
def verify_token(token: str):
"""检查token是否有效"""
if token != "my-secret-token":
raise HTTPException(
status_code=401,
detail="无效的token"
)
return "user_123" # 返回用户ID
# 在路由中使用依赖注入
@app.get("/profile")
def get_profile(
user_id: str = Depends(verify_token)
):
# user_id 已由 verify_token 验证并返回
return {"user_id": user_id}
# 另一个使用相同依赖的路由
@app.get("/orders")
def get_orders(
user_id: str = Depends(verify_token)
):
return {"orders": [], "user": user_id}

依赖注入的好处:

六、实战:待办事项API

让我们把所有知识组合起来,实现一个完整的待办事项API,包含完整的CRUD操作。

Python todo_api.py - 完整待办事项API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
app = FastAPI(title="待办事项API",
description="一个简单的待办事项管理API",
version="1.0.0")
# ──── 数据模型 ────
class TodoCreate(BaseModel):
"""创建待办时需要的字段"""
title: str
description: Optional[str] = None
class TodoUpdate(BaseModel):
"""更新待办时可选的字段"""
title: Optional[str] = None
description: Optional[str] = None
completed: Optional[bool] = None
class TodoResponse(BaseModel):
"""返回给前端的待办数据"""
id: int
title: str
description: Optional[str]
completed: bool
# 模拟数据库(内存字典)
todos_db: dict = {}
next_id: int = 1
# ──── CREATE: 创建待办 ────
@app.post("/todos", response_model=TodoResponse,
status_code=201)
def create_todo(todo: TodoCreate):
global next_id
new_todo = {
"id": next_id,
"title": todo.title,
"description": todo.description,
"completed": False,
}
todos_db[next_id] = new_todo
next_id += 1
return new_todo
# ──── READ: 获取所有待办 ────
@app.get("/todos", response_model=list[TodoResponse])
def list_todos():
return list(todos_db.values())
# ──── READ: 获取单个待办 ────
@app.get("/todos/{todo_id}", response_model=TodoResponse)
def get_todo(todo_id: int):
if todo_id not in todos_db:
raise HTTPException(status_code=404,
detail="待办不存在")
return todos_db[todo_id]
# ──── UPDATE: 更新待办 ────
@app.put("/todos/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, update: TodoUpdate):
if todo_id not in todos_db:
raise HTTPException(status_code=404,
detail="待办不存在")
todo = todos_db[todo_id]
if update.title is not None:
todo["title"] = update.title
if update.description is not None:
todo["description"] = update.description
if update.completed is not None:
todo["completed"] = update.completed
return todo
# ──── DELETE: 删除待办 ────
@app.delete("/todos/{todo_id}", status_code=204)
def delete_todo(todo_id: int):
if todo_id not in todos_db:
raise HTTPException(status_code=404,
detail="待办不存在")
del todos_db[todo_id]
return None

这个API提供了5个端点:

方法
URL
功能
POST
/todos
创建待办
GET
/todos
获取所有待办
GET
/todos/{id}
获取单个待办
PUT
/todos/{id}
更新待办
DELETE
/todos/{id}
删除待办
Bash 用curl测试API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 创建待办
curl -X POST http://127.0.0.1:8000/todos \
-H "Content-Type: application/json" \
-d '{"title":"学习FastAPI","description":"完成教程"}'
# 获取所有待办
curl http://127.0.0.1:8000/todos
# 获取ID为1的待办
curl http://127.0.0.1:8000/todos/1
# 更新待办(标记完成)
curl -X PUT http://127.0.0.1:8000/todos/1 \
-H "Content-Type: application/json" \
-d '{"completed":true}'
# 删除待办
curl -X DELETE http://127.0.0.1:8000/todos/1
常见错误:422 Unprocessable Entity

这个错误意味着请求数据不符合Pydantic模型定义。例如:创建待办时缺少必填的 title 字段,或者 completed 传了字符串而不是布尔值。

好消息是FastAPI会自动返回详细的错误信息,告诉你哪个字段有问题。

知识回顾

API是前后端分离架构中后端提供给前端的数据接口
RESTful设计:URL是资源名词,HTTP方法是操作动词
FastAPI用Pydantic模型自动验证请求数据,类型安全
/docs 自动生成Swagger UI交互式API文档
依赖注入(Depends)实现认证、数据库连接等公共逻辑复用

下一篇预告

篇5:项目部署——让你的网站"上线"

代码写好了,但只在你的电脑上运行还不行。最后一篇将学习如何将项目打包、容器化,并部署到真正的服务器上,让你的网站对全世界可用。我们会学习Docker、Nginx和Gunicorn等生产级工具。

Python Web后端开发系列 · 篇4/5

相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书