用 Flask 写 JSON API,返回值与请求体各有哪些默认行为?哪些类型能序列化?请求头不对会返回什么?这篇用 test_client 把每种情况的状态码与响应逐个打印出来。
return {...} → 200 application/json | {"a":"\u4e2d\u6587","b":1,"c":[1,2]}
return jsonify(...) → 200 application/json | {"a":"\u4e2d\u6587","b":1}
return [...](顶层列表) → 200 application/json | [1,2,{"x":1}]
return {...}, 201, {Location} → 201 application/json | {"id":7}
Location 头: /items/7
当前默认值:app.json.sort_keys = True | ensure_ascii = True | compact = None | mimetype = application/json上一篇:数据库连接断开后的恢复;下一篇:API 错误响应统一格式。
datetime / date / Decimal / UUID → 200 application/json | {"day":"Fri, 02 Jan 2026 00:00:00 GMT","id":"12345678-1234-5678-1234-567812345678","price":"1.10","when":"Fri,
set(默认不支持) → 500 text/html; charset=utf-8
状态码 500,响应是 HTML 错误页(不是 JSON) Content-Type: application/json + 合法 JSON → 200 {"got":{"a":1}}
Content-Type: application/json + 非法 JSON → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title> <h1>Bad Request</h1> <p>The browse
Content-Type: text/plain + 合法 JSON → 415 <!doctype html> <html lang=en> <title>415 Unsupported Media Type</title> <h1>Unsupported Media T
没有 Content-Type + 合法 JSON → 415 <!doctype html> <html lang=en> <title>415 Unsupported Media Type</title> <h1>Unsupported Media T
application/json + 空请求体 → 400 <!doctype html> <html lang=en> <title>400 Bad Request</title> <h1>Bad Request</h1> <p>The browse
silent=True + 非法 JSON → 200 {"got":null}
force=True + text/plain → 200 {"got":{"a":1}}
test_client 的 json= 参数 → 200 {"got":{"a":1}} return None → 500 text/html; charset=utf-8
<!doctype html> <html lang=en> <title>500 Internal Server Error</title> <h1>Internal Server Error</h1> <p>The server encountered a
return "plain" → 200 text/html; charset=utf-8 | plain {"b":1,"a":"中文","s":[1,2]}
(默认 provider 的同一份数据: {"a":"\u4e2d\u6587","b":1,"c":[1,2]} )经 Flask 返回 0.71 ms/次,纯 json.dumps 0.51 ms/次;响应大小 59041 字节