为 JSON 响应设置状态码
将 JSON 正文与 201、404 等状态码配对
为 JSON 响应设置状态码 是 CoddyKit 上的免费 Flask Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flask Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flask Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Status Codes Tell the Story
Every HTTP response carries a status code that signals success or failure. Your JSON body explains the details, but the code sets the tone first. 🚦
The Default Is 200
When you return jsonify alone, Flask sends 200 OK. That is perfect for a successful read, but other actions deserve their own code.
Return a Tuple
To choose a code, return a tuple of the JSON response and the number. Flask reads the second element as the HTTP status to send.
return jsonify(message="created"), 201201 for Created
When a request creates a new record, reply with 201 Created. It tells the client the resource now exists, which 200 alone would not convey.
return jsonify(id=new_id), 201404 for Not Found
If the requested item does not exist, return a JSON body with 404. The client learns the resource is missing, not that the server broke.
return jsonify(error="user not found"), 404400 for Bad Input
When a client sends invalid data, answer with 400 Bad Request. Pair it with a JSON message that explains exactly what went wrong.
return jsonify(error="name is required"), 400The 2xx Family
Codes in the 2xx range mean success. 200 reads, 201 creates, and 204 signals success with no body to send back.
The 4xx Family
Codes in the 4xx range blame the client. 400 means bad input, 401 means unauthenticated, and 403 means forbidden.
The 5xx Family
Codes in the 5xx range blame the server. A 500 means your code raised an unhandled error while processing an otherwise valid request.
Adding Headers Too
You can extend the tuple to three parts: body, status, and a headers dict. That lets you attach extra metadata in one clean return.
return jsonify(ok=True), 201, {"X-Created": "now"}Consistency Builds Trust
Pick the right code for every outcome and use it everywhere. Consistent status codes make your API predictable and a joy to integrate.
Quick Check
Match the action to the most fitting HTTP status code.
Recap
You learned to pair JSON bodies with the right status code by returning a tuple, using 201, 404, and 400 to make your API clear and honest. ✅
常见问题解答
「为 JSON 响应设置状态码」课时是免费的吗?
是的 — 「为 JSON 响应设置状态码」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flask Academy 课程的其余内容,请升级到 CoddyKit PRO。 Flask Academy 课程共包含 4 节课。
「为 JSON 响应设置状态码」这节课中我会学到什么?
将 JSON 正文与 201、404 等状态码配对 你通过在浏览器中直接运行的动手代码来练习 Flask Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flask Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flask Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「为 JSON 响应设置状态码」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flask Academy 课中编写并运行代码吗?
能。每节 Flask Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 将字典 jsonify
- 返回列表与嵌套数据
- 为 JSON 响应设置状态码
- Content-Type 与 Accept 标头