python用fastapi快速写一个增删改查的接口

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客户端之类的工具来测试这些端点。

相关推荐
前端精髓35 分钟前
langchain 短期记忆(状态)动态运行时上下文
python·langchain
程序猿乐锅39 分钟前
万字详解Single-flight(单飞模式)
java·开发语言·分布式·后端·学习·single-flight
最强小杰1 小时前
DeepSeek V4 Flash + Codex CLI 接入教程:原生 Responses API 适配,从配置到跑通收藏这篇就够了(2026)
java·前端·python·ai
DeepVisionary2 小时前
为拿并网许可,OpenAI在佐治亚新园区同意高峰期断电三成
python·自动化
揽星河..2 小时前
【C语言】指针
c语言·开发语言
小小数媒成员2 小时前
UGUI原理(一)
开发语言·游戏·unity·游戏引擎
VIP_CQCRE3 小时前
内容自动化越跑越乱?先补上状态、去重和失败恢复
python·ai·工作流·幂等设计·内容自动化
速易达网络3 小时前
Three.js 动画入门教学:从场景搭建到流畅动效
开发语言·javascript·ecmascript
福大大架构师每日一题3 小时前
excelize v2.11.1发布:Go 1.26.0起步,16项安全修复与嵌入对象能力全面升级
开发语言·安全·golang