Flask - Restful API 开发
这篇讲什么
- REST 是把「对资源的操作」映射到 HTTP 方法的一套架构风格,这篇按资源 + GET / POST / PUT / PATCH / DELETE 把接口一层层写出来。
- 主路径用 Flask 自带的
MethodView(类里没写的方法自动 405),Flask-RESTful降为备选并给出Resource、reqparse、marshal的实测行为。 - 认证两节:
Flask-HTTPAuth的 Basic 与 token,token 部分给itsdangerous.URLSafeTimedSerializer和 PyJWT 两种签发、校验写法。
RESTful 是什么
- REST(Representational State Transfer,表述性状态传递)是 Roy Fielding 2000 年博士论文里提出的一种架构风格。
- 它是一种风格、一组设计原则和约束条件,不是标准,主要用于客户端与服务器交互的软件。按这个风格写的接口更简洁、更有层次,也更容易做缓存。
- 满足 REST 风格的 API 就叫 RESTful API;开发时一切都是围绕「资源」和对资源的操作展开的。
资源与操作
-
资源就是网络上存在的任意实体,哪怕只是一条信息。
-
对资源的操作本质上是 CRUD,而 RESTful 把它映射到 HTTP 方法上:
方法 行为 示例 GET获取所有资源 http://127.0.0.1:5002/postsGET获取指定资源 http://127.0.0.1:5002/posts/250POST创建新资源 http://127.0.0.1:5002/postsPUT整体更新指定资源 http://127.0.0.1:5002/posts/250PATCH局部更新指定资源 http://127.0.0.1:5002/posts/250DELETE删除指定资源 http://127.0.0.1:5002/posts/250 -
老笔记这张表少了
PATCH。约定是:PUT要求客户端给出完整资源表示(幂等),PATCH只提交要改的字段。 -
URL 用名词复数、不要带动词(
GET /posts而不是/getPosts),这一点比用哪个库重要得多。
数据格式
-
请求体和响应体都用 JSON。服务端要显式声明:
1
Content-Type: application/json
-
实测 Flask 3.1.3 里视图直接
return一个 dict 就会自动转 JSON 并带上这个头(见 Flask-基本入门 的「响应(response)」)。 -
JSON 只能用双引号、末尾不能有多余逗号——这是老笔记里唯一说对的注意点。
-
客户端不带
Content-Type: application/json时,request.get_json()直接抛 415,实测错误体是:1
415 {'error': 'UnsupportedMediaType', 'detail': '415 Unsupported Media Type: Did not attempt to load JSON data because ...'}
调试工具
-
手写 curl 最直接,本机实测:
1
curl -X POST http://127.0.0.1:5002/posts -H "Content-Type: application/json" -d "{\"title\":\"t\",\"content\":\"c\"}"
-
图形界面用 Postman 或 Bruno(Bruno 是开源的、集合存在本地文件里);VS Code 的 REST Client 插件也行,仓库里放一个
test.http就能点着发。 -
老笔记「一路 next 傻瓜式安装」那句已经过时,Postman 现在要登录账号才能同步集合。
MethodView 实现
-
老笔记这节叫「原生实现」,用一堆
@app.route加methods手写分派。Flask 自带的MethodView才是官方推荐的写法:一个资源一个类,方法名就是 HTTP 动词。 -
完整可跑的示例:
app.py 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
60from flask import Flask, abort, jsonify, request
from flask.views import MethodView
app = Flask(__name__)
POSTS = [
{"id": 1, "title": "Python基础", "content": "语法简单,问题都出在语法上"},
{"id": 2, "title": "Web前端", "content": "不就是几个标签,但要细心"},
]
class PostList(MethodView):
def get(self):
return jsonify({"posts": POSTS})
def post(self):
data = request.get_json() # Content-Type 不对会抛 415
if not data or "title" not in data or "content" not in data:
return jsonify({"error": "Bad Request", "need": ["title", "content"]}), 400
p = {"id": (POSTS[-1]["id"] + 1) if POSTS else 1,
"title": data["title"], "content": data["content"]}
POSTS.append(p)
return jsonify({"post": p}), 201, {"Location": f"/posts/{p['id']}"}
class PostItem(MethodView):
def get(self, pid):
for p in POSTS:
if p["id"] == pid:
return jsonify({"post": p})
abort(404)
def put(self, pid):
for p in POSTS:
if p["id"] == pid:
data = request.get_json(silent=True) or {}
p.update({k: v for k, v in data.items() if k in ("title", "content")})
return jsonify({"post": p})
abort(404)
def delete(self, pid):
for p in POSTS:
if p["id"] == pid:
POSTS.remove(p)
return jsonify({"result": "已删除"})
abort(404)
app.add_url_rule("/posts", view_func=PostList.as_view("post_list"))
app.add_url_rule("/posts/<int:pid>", view_func=PostItem.as_view("post_item"))
def not_found(e):
return jsonify({"error": "Page Not Found"}), 404
def not_allowed(e):
return jsonify({"error": "Method Not Allowed"}), 405 -
实测每个分支的行为:
请求 状态码 响应 POST /posts带全字段201 {'post': {'content': 'y', 'id': 3, 'title': 't2'}},另有Location: /posts/3POST /posts缺 content400 {'error': 'Bad Request', 'need': ['title', 'content']}POST /posts不带 JSON 头415 {'error': 'UnsupportedMediaType', ...}GET /posts/1200 那条资源 GET /posts/999404 {'error': 'Page Not Found'}PUT /posts/1200 title 改成「改过了」 DELETE /posts/2200 {'result': '已删除'}再 DELETE /posts/2404 {'error': 'Page Not Found'}PATCH /posts/1(类里没写patch)405 {'error': 'Method Not Allowed'} -
类里没实现的方法自动 405,不用自己判断请求方式,这是
MethodView相对手写if request.method == ...的最大收益。 -
错误处理一定要定制:默认的 404/405 页面是 HTML,接口客户端拿到会一头雾水。
-
老笔记里
request.json这种写法现在是个坑:它等价于严格的get_json(),实测 Content-Type 不是 JSON 时抛UnsupportedMediaType(415),而if not request.json这句在判断之前就已经炸了。要容错就写request.get_json(silent=True),实测返回None。 -
settings.py里那句ENV = 'development'是 flask-script 时代遗留,Flask 2.3 起FLASK_ENV已删除,这个自定义变量也没人读。
参数校验与输出裁剪
-
MethodView只给了「按方法分派」,reqparse和marshal那两件事要自己写,各一个函数就够。参数校验:app.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25REQUIRED = {"title": str, "content": str}
OPTIONAL = {"views": int}
def parse_json(required, optional):
data = request.get_json(silent=True)
if not isinstance(data, dict):
return None, {"_body": "需要 JSON 请求体,Content-Type 要写 application/json"}
errors, out = {}, {}
for name, typ in required.items():
value = data.get(name)
if value is None:
errors[name] = "必填"
continue
try:
out[name] = typ(value)
except (TypeError, ValueError):
errors[name] = "类型不对,期望 %s" % typ.__name__
for name, typ in optional.items():
if name not in data:
continue
try:
out[name] = typ(data[name])
except (TypeError, ValueError):
errors[name] = "类型不对,期望 %s" % typ.__name__
return (None if errors else out), errors -
视图里两行就用上了,返回结构也照着
reqparse的{'message': {...}}来:app.py 1
2
3
4
5
6class PostList(MethodView):
def post(self):
data, errors = parse_json(REQUIRED, OPTIONAL)
if errors:
return jsonify({"message": errors}), 400
# data 里只有校验过的 title / content / views -
实测这四种输入的区别(Flask 3.1.3):
1
2
3
4
5POST /posts 带全字段 -> 201 {"post": {"content": "y", "id": 3, "title": "t2"}}
POST /posts 缺 content -> 400 {"message": {"content": "必填"}}
views 写成 "abc" -> 400 {"message": {"views": "类型不对,期望 int"}}
不带 JSON 头 -> 400 {"message": {"_body": "需要 JSON 请求体,Content-Type 要写 application/json"}}
空 body {} -> 400 {"message": {"content": "必填", "title": "必填"}}注意最后两条:因为这里用的是
get_json(silent=True),Content-Type 不对时是我们自己给的 400,而不是request.json那种 415。 -
输出裁剪就是一个字段白名单投影,作用是别把
secret、views这类内部字段跟着返回:app.py 1
2
3
4
5
6POST_FIELDS = ("id", "title", "content")
def render(obj, fields):
if isinstance(obj, list):
return [render(o, fields) for o in obj]
return {k: obj.get(k) for k in fields}1
2render({'id': 9}, POST_FIELDS) -> {'id': 9, 'title': None, 'content': None}
GET /posts/1 -> {"post": {"content": "语法简单,问题都出在语法上", "id": 1, "title": "Python基础"}}列表和单条都能用,缺失的键补
None,这点和marshal的行为一致。 -
整个类的方法都要过一道装饰器时,
MethodView也支持decorators列表,写法与Resource同名同用法:app.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14def audit(view):
def wrapper(*args, **kwargs):
print("命中", request.method)
return view(*args, **kwargs)
return wrapper
class AuditAPI(MethodView):
decorators = [audit]
def get(self, pid):
return jsonify({"audit": "GET", "pid": pid})
def delete(self, pid):
return jsonify({"audit": "DELETE", "pid": pid})1
2GET /audit/1 -> 200,装饰器命中 ['GET']
DELETE /audit/1 -> 200,装饰器命中 ['GET', 'DELETE'] -
方法签名要接住 URL 里的参数:规则写了
/audit/<int:pid>,get就必须是def get(self, pid)。实测漏掉参数会直接TypeError: AuditAPI.get() got an unexpected keyword argument 'pid',而且这个异常发生在分派之后,errorhandler(404)一类都拦不住,只会变成 500。
Flask-RESTful
-
Flask-RESTful 是第三方库,比
MethodView多了reqparse参数解析和fields/marshal输出裁剪。本机实测 0.3.10 在 Flask 3.1.3 上仍然可用(它最后一次发版是 2023 年,属于能用但不再演进的那一类),所以主路径建议用上一节的MethodView(那节末尾给了reqparse、marshal两件事的等价写法),这个库当备选。 -
用法:
app.py 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
28from flask_restful import Api, Resource
api = Api()
class UserAPI(Resource):
def get(self, uid):
return {"USER": "GET", "uid": uid}
def put(self, uid):
return {"USER": "PUT"}
def delete(self, uid):
return {"USER": "DELETE"}
class UserListAPI(Resource):
def get(self):
return {"UserList": "GET"}
def post(self):
return {"UserList": "POST"}
api.add_resource(UserAPI, "/users/<int:uid>", "/u/<int:uid>")
api.add_resource(UserListAPI, "/users/")
# 建 Api() 时没给 app,就要在 add_resource 之后 init_app
api.init_app(app) -
实测:
1
2
3
4
5GET /users/5 -> 200 {'USER': 'GET', 'uid': 5}
GET /u/5(第二条路由)-> {'USER': 'GET', 'uid': 5}
POST /users/ -> 200 {'UserList': 'POST'}
PATCH /users/5(未实现)-> 405
返回 dict 的 Content-Type -> 'application/json' -
「一个资源类对应两个 URL(列表 + 单条)」这件事仍然成立,但老笔记强调的「
init_app必须放在add_resource之后」已经不必要——实测按上面这个顺序写就正常。不想分两步就一步到位:app.py 1
2api = Api(app) # 建对象时就绑 app,后面不用再 init_app
api.add_resource(UserAPI, '/users/<int:uid>', '/u/<int:uid>') -
reqparse的错误信息比手写校验整齐,实测:app.py 1
2
3
4
5from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument("title", type=str, required=True, help="title 必填")
parser.add_argument("age", type=int, location="json")1
2
3缺必填 -> 400 {'message': {'title': 'title 必填'}}
类型不对 -> 400 {'message': {'age': "invalid literal for int() with base 10: 'abc'"}}
正常 -> 201 {'got': {'title': 'hi', 'age': 3}} -
输出裁剪用
fields+marshal,实测缺失的键会被补成None:1
2marshal({'id': 1, 'title': 't'}, {'id': Integer, 'title': String, 'secret': String})
-> OrderedDict({'id': 1, 'title': 't', 'secret': None}) -
不用这个库时,参数校验的官方生态选择是 WTForms(见 Flask-表单使用)或直接 Pydantic。
身份认证
-
Flask-HTTPAuth 提供 Basic / Digest / Token 三种认证骨架,本机 4.8.1 实测可用。
-
Basic 认证:
app.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from flask import jsonify
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
USERS = {"admin": "123456"}
def verify(username, password):
if username in USERS and USERS[username] == password:
return username # 返回值会交给 auth.current_user()
def unauthorized():
return jsonify({"error": "Unauthorized Access"}), 401
def private():
return jsonify({"hello": auth.current_user()}) -
实测四种情况:
1
2
3
4不带 Authorization -> 401 {'error': 'Unauthorized Access'}
WWW-Authenticate -> 'Basic realm="Authentication Required"'
带正确凭据 -> 200 {'hello': 'admin'}
带错凭据 -> 401 -
verify_password的返回值不是布尔:返回真值表示通过,而且会被记成current_user(),老笔记「返回 True 表示认证成功」那句要改。 -
Basic 认证每次请求都带账号密码(base64 只是编码不是加密),只能在 HTTPS 下用;明文 HTTP 下等于把口令裸奔。
-
整个资源类都要保护时,写
decorators = [auth.login_required];只保护某个方法就直接装饰那个方法。 -
密码不要写死在代码里,用环境变量或哈希比对,参照 Django 那篇
check_password的做法。
token 认证
-
流程是:先用账号密码换一个带有效期的 token,之后每次请求只带 token。
-
老笔记用的
itsdangerous.TimedJSONWebSignatureSerializer已经被删除,实测:1
ImportError: cannot import name 'TimedJSONWebSignatureSerializer' from 'itsdangerous'
itsdangerous 2.x 把 JWT 序列化器整个拿掉了,替代有两条路。
路线一:URLSafeTimedSerializer
-
不是标准 JWT,但够用、零依赖:
app.py 1
2
3
4
5
6
7
8
9
10
11from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
s = URLSafeTimedSerializer(app.config["SECRET_KEY"])
token = s.dumps({"username": "admin"})
try:
data = s.loads(token, max_age=3600)
except SignatureExpired:
data = None
except BadSignature:
data = None实测:
1
2
3dumps -> 'eyJ1c2VybmFtZSI6ImFkbWluIn0.au2PEA.JcaluvwJg...'
loads(max_age=3600) -> {'username': 'admin'}
乱写的 token -> BadSignature
路线二:PyJWT(标准 JWT)
-
本机 PyJWT 2.15.1 实测:
app.py 1
2
3
4
5
6
7import datetime
import jwt
payload = {"username": "admin",
"exp": datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=3600)}
token = jwt.encode(payload, app.config["SECRET_KEY"], algorithm="HS256")
data = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"])1
2
3
4encode(HS256) -> 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2V...'
decode -> {'username': 'admin', 'exp': 1793957152}
换密钥签的 token -> InvalidSignatureError
过期 token -> ExpiredSignatureError -
algorithms必须显式传,这是 PyJWT 2.x 防算法混淆的强制要求,实测漏传报:1
2jwt.decode(token, key) -> DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode().
jwt.decode(token, key, algorithms=['HS256']) -> 正常拿到 {'username': 'admin', 'exp': ...} -
实测 PyJWT 会对短密钥告警:
InsecureKeyLengthWarning: The HMAC key is 17 bytes long, which is below the minimum recommended length of 32 bytes for SHA256。所以 HS256 的密钥要 ≥32 字节,'123456'这种直接不合格。 -
exp要写成带时区的datetime(datetime.UTC),别再用datetime.utcnow(),本机 Python 3.14 上它已经报 DeprecationWarning。
接到 Flask-HTTPAuth 上
1 | from flask_httpauth import HTTPTokenAuth |
-
实测:
1
2
3
4
5不带 token -> 401 {'error': 'Token 无效'}
带正确 Bearer token -> 200 {'user': 'admin'}
带换密钥签的 token -> 401
带过期 token -> 401
只给裸 token(没有 Bearer 前缀)-> 401 -
scheme="Bearer"之后请求头必须是Authorization: Bearer <token>,少一个前缀就取不到 token——这是新接手这个项目时最常见的 401 原因。 -
token 认证仍然要走 HTTPS:token 泄露等于身份泄露,而且它没有浏览器自动重发的机制,务必设较短有效期并配刷新流程。