HTTP协议与RESTful API实战手册(终章):构建企业级API的九大秘籍 🔐
title: HTTP协议与RESTful API实战手册(终章):构建企业级API的九大秘籍 🔐
from fastapi import Header
@app.get("/products/{id}")
async def get_product(
id: int,
if_none_match: str = Header(None)
):
current_etag = f"W/{hash(data)}"
if if_none_match == current_etag:
return Response(304)
return JSONResponse(
content=data,
headers={"ETag": current_etag}
)
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://your-app.com"],
allow_methods=["*"],
allow_headers=["*"],
max_age=86400
)
// 订单状态流转
{
"_embedded": {
"items": [
{
"product_id": 101,
"_links": {
"product": {
"href": "/products/101"
}
}
}
]
},
"_links": {
"next": {
"href": "/orders?page=2"
},
"payment": {
"href": "/orders/1001/payment"
}
}
}
方案 | URL路径 | 请求头 | 媒体类型 |
---|---|---|---|
示例 | /v1/orders | Accept: application/vnd.api.v1+json | application/vnd.api+json; version=1 |
适用场景 | 快速迭代 | 精确控制 | 无URL污染 |
async def list_orders(
after: str = None,
before: str = None,
limit: int = 100
):
query = "SELECT id FROM orders"
if after:
query += f" WHERE id > {after}"
elif before:
query += f" WHERE id < {before}"
query += f" ORDER BY id DESC LIMIT {limit}"
class OrderFilter(BaseModel):
status: Optional[OrderStatus]
min_total: Optional[float]
created_after: Optional[datetime]
@app.get("/orders")
async def search_orders(filter: OrderFilter):
query = build_filter_query(filter)
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
tracer = trace.get_tracer(__name__)
FastAPIInstrumentor.instrument_app(app)
async def process_order():
with tracer.start_as_current_span("order-processing"):
# 跟踪关键业务逻辑
# 要求:
# 1. 支持多语言错误消息
# 2. 实现海关申报自动化
# 3. 货物状态实时推送(WebSocket)
# 4. 分布式事务处理
@app.websocket("/shipments/{id}/tracking")
async def track_shipment(websocket: WebSocket):
await websocket.accept()
while True:
location = get_realtime_location()
await websocket.send_json(location)
评论
发表评论