编辑模式 · 点击文字即可修改 · Ctrl+S 导出 再次按 E 或点击左上角退出
模块 5.4 · 后端第四课

FastAPI 入门

从手搓到框架,感受效率和幸福感的提升

这一节的成果 · 两个接口

用 FastAPI 实现两个 API

上一节手搓版 · 重写
GET
/api/profile
换成 FastAPI,几行就够
本节新增
POST
/api/analyze
提交一段文字,返回分析结果

做完这两个,前端就有真接口可以调了。

1
为什么需要框架

摆平底层环节,聚焦核心业务

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/api/profile":
self.send_response(200)
self.send_header("Content-Type", ...)
self.end_headers()
body = json.dumps(profile, ...)
self.wfile.write(body.encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
我们真正想做的
GET /api/profile
返回 profile 这份数据

每个项目都差不多的事,自然有人整理好、封装好、给大家复用——这就是后端框架

12
Python 常见的后端框架

不需要背,先混个脸熟

Flask
老牌 · 轻量
长期的入门经典
生态成熟
Django
大而全
后台管理、用户系统、操作数据库的 ORM 都自带
适合功能完整的网站项目
FastAPI
年轻 · 为 API 而生
字段和类型写清楚,剩下的它来
代码少校验直接自动文档

框架之间概念相通:路由、请求、响应、参数、校验——学明白一个,其他都是熟面孔

1
FastAPI 和 uvicorn · 两个角色

上一节的 main.py,其实干着两类活

定义接口
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/api/profile":
self.send_response(200)
self.send_header("Content-Type", ...)
self.end_headers()
self.wfile.write(body.encode("utf-8"))
else:
self.send_response(404)
运行服务器 · 监听端口
HTTPServer(("", 8000), Handler).serve_forever()
FastAPI
定义接口
uvicorn
运行服务器 · 监听端口
123
手搓版 vs FastAPI 版

使用 FastAPI 前后的对照

手搓版 · handmade.py
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/api/profile":
self.send_response(200)
self.send_header("Content-Type", ...)
self.end_headers()
body = json.dumps(profile, ...)
self.wfile.write(body.encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
FastAPI 版 · main.py
@app.get("/api/profile")
def get_profile():
return profile
1234
💻
请求方
请求体 request body
{ "text": "今天的风很轻" }
请求 request
响应 response
响应体 response body
{ "text": "今天的风很轻", "score": 0.5, "label": "偏平静", "pinyin": "(模块 6 再说)" }
🗄️
被请求方
POST /api/analyze · 请求先过校验这道门

不合规的请求,进不了门

请求体 request body
{ … }
合格请求 · request body
{ "text": "今天的风很轻" }
不合格请求 · request body
{ "txt": "…" }
请求 request
🚦
校验闸门
text: str
✓ 通过 ✗ 拦下
放行
⚙️
处理逻辑
analyze()
✓ 运行 · 返回结果 — 这次没被执行

校验这道门,是 FastAPI 照着声明自动把守的——通过才进处理,不通过直接 422 打回。

12
后端之旅 · 下一步

下一节,
前后端联调

让前端真正去调用 API,把数据显示在页面上。