python用fastapi快速写一个增删改查的接口
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict
app = FastAPI()
# Mock database
db = {}
# Model for the data
class Item(BaseModel):
name: str
description: str
# Create operation
@app.post("/items/")
def create_item(item: Item):
if item.name in db:
raise HTTPException(status_code=400, detail="Item already exists")
db[item.name] = item.description
return {"message": "Item created successfully"}
# Read operation
@app.get("/items/{name}")
def read_item(name: str):
if name not in db:
raise HTTPException(status_code=404, detail="Item not found")
return {"name": name, "description": db[name]}
# Update operation
@app.put("/items/{name}")
def update_item(name: str, item: Item):
if name not in db:
raise HTTPException(status_code=404, detail="Item not found")
db[name] = item.description
return {"message": "Item updated successfully"}
# Delete operation
@app.delete("/items/{name}")
def delete_item(name: str):
if name not in db:
raise HTTPException(status_code=404, detail="Item not found")
del db[name]
return {"message": "Item deleted successfully"}
这段代码设置了一个FastAPI应用程序,其中包含用于创建、读取、更新和删除物品的端点。数据以简单的内存数据库形式存储在字典(db)中。您可以使用诸如curl、Postman或任何其他HTTP客户端之类的工具来测试这些端点。