从零构建你的第一个RESTful API:HTTP协议与API设计超图解指南 🌐
title: 从零构建你的第一个RESTful API:HTTP协议与API设计超图解指南 🌐
POST /orders HTTP/1.1 📦 寄件动作
Content-Type: application/json 📝 物品清单格式
Authorization: Bearer token123 🔑 安全印章
{"item": "芝士汉堡", "quantity": 2} 📦 包裹内容
HTTP/1.1 201 Created ✅ 签收成功
Location: /orders/1001 📍 新订单位置
X-RateLimit-Remaining: 99 ⏳ 剩余请求次数
{"id": 1001, "status": "烹饪中"} 📦 返回的包裹
状态码 | 比喻 | 常见场景 |
---|---|---|
200 | 包裹完好送达 | 成功获取资源 |
404 | 收件地址不存在 | 请求路径错误 |
422 | 包裹内容不符合要求 | 参数校验失败 |
GET / 菜单 # 查看菜单
POST / 订单 # 下单
PUT / 订单 / 1001 # 修改订单
DELETE / 订单 / 1001 # 退单
from fastapi import FastAPI
app = FastAPI()
fake_menu = [
{"id": 1, "name": "经典汉堡", "price": 30},
{"id": 2, "name": "辣味汉堡", "price": 35}
]
# 获取全部汉堡
@app.get("/hamburgers")
async def get_hamburgers():
return fake_menu
# 创建新汉堡
@app.post("/hamburgers")
async def create_hamburger(name: str, price: float):
new_item = {"id": len(fake_menu) + 1, "name": name, "price": price}
fake_menu.append(new_item)
return {"message": "汉堡已加入菜单", "data": new_item}
from pydantic import BaseModel
class Hamburger(BaseModel):
name: str # 必须填写名称
price: float # 必须填写价格
spicy: bool = False # 可选参数
@app.post("/v2/hamburgers")
async def safe_create(hb: Hamburger):
if hb.price < 0:
raise HTTPException(422, "价格不能为负数")
# 保存到数据库...
# 你的代码在这里!
@app.get("/orders/{order_id}")
async def get_order(order_id: int):
# 实现根据ID查订单
pass
@app.post("/orders")
async def create_order(items: list):
# 实现创建订单
pass
# 危险代码(可被SQL注入)
def get_user(input):
cursor.execute(f"SELECT * FROM users WHERE name = '{input}'")
# 你的任务:改写为安全代码(使用参数化查询)
评论
发表评论