W7 · 后端第一个 API:从 hello 到 CRUD
一句话人话:后端开发的节奏是"先通一条,再复制成套"——先让
/api/health返回一个 JSON(证明路通),然后照着予安蓝图的模式把增删改查(CRUD)写全。
第一步:健康检查(证明活着)
python
# app.py(心情日记后端)
from flask import Flask, jsonify # Flask 本体 + JSON 工具
app = Flask(__name__) # 造出应用本体,后端一切从这里开始
@app.get("/api/health") # 登记:GET /api/health 交给下面的函数
def health(): # 健康检查:证明"活着"
return {"code": 0, "message": "心情日记后端运行中", "data": None} # 统一响应格式:code/message/data
if __name__ == "__main__": # 直接运行本文件才启动服务
app.run(port=5001) # 记得避开 5000(macOS AirPlay 占用)curl http://127.0.0.1:5001/api/health 返回 JSON——路通了(予安 health 蓝图同款格式)。
第二步:CRUD 四件套(予安蓝图模式缩小版)
python
entries = [] # 第一版先用内存列表(数据库 W9 后接入)
@app.get("/api/entries") # 查:列表(倒序)
def list_entries(): # 处理函数:端出倒序后的列表
return {"code": 0, "data": list(reversed(entries))} # reversed 倒序:最新的排最前
@app.post("/api/entries") # 增:新建(带校验)
def create_entry(): # 处理函数:收一条新日记
from flask import request # 局部导入:只有这个接口用 request
data = request.get_json(silent=True) or {} # 取请求体 JSON,解析失败给空字典兜底
score = data.get("score", -1) # 取分数,没传给 -1(必然过不了校验)
if not isinstance(score, (int, float)) or not 0 <= score <= 10: # 先验类型:传个 "7"(字符串)进来,直接比较会 TypeError
return {"code": 400, "message": "score 必须在 0~10"} # 校验不过:400 打回
mobile = "demo" # W7 还没登录,先占位;W9 接上鉴权后换成从 token 里解出的手机号
data["user_id"] = mobile # 每条日记记上归属人——W9 按 user_id 过滤要用
entries.append(data) # 存进内存列表
return {"code": 0, "data": data} # 成功:把存进去的条目回显
@app.delete("/api/entries/<int:idx>") # 删:按序号
def delete_entry(idx): # 处理函数:按倒序序号删
entries.pop(len(entries) - 1 - idx) # 页面展示是 reversed 倒序,idx 是倒着数的序号,存储里得从尾部往回数,不然会删错条目
return {"code": 0} # 成功:不带数据对照 路由卡:蓝图、统一响应 code/message/data、入口校验——予安的每一条纪律都在,只是规模缩小。
动手:curl 全流程验证
bash
# 增
curl -X POST http://127.0.0.1:5001/api/entries -H "Content-Type: application/json" \
-d '{"score": 7, "note": "平稳"}'
# 查
curl http://127.0.0.1:5001/api/entries
# 删
curl -X DELETE http://127.0.0.1:5001/api/entries/0powershell
# PowerShell(拯救者)等价命令:反斜杠续行 + 单引号 JSON 是 bash 写法,PowerShell 里用 Invoke-RestMethod 更省心
Invoke-RestMethod -Method Post -Uri http://127.0.0.1:5001/api/entries -ContentType "application/json" -Body '{"score": 7, "note": "平稳"}' # 增
Invoke-RestMethod http://127.0.0.1:5001/api/entries # 查
Invoke-RestMethod -Method Delete http://127.0.0.1:5001/api/entries/0 # 删自测
相关知识点
- W6 初始化 — 上一课
- W8 前端调通第一个请求 — 下一课:前端来敲门
- 服务端怎么接住请求 — 大网站的完整版
下一课 → W8 前端调通第一个请求