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

相关推荐
钢铁男儿25 分钟前
C# 方法(栈帧)
开发语言·c#
Amo Xiang1 小时前
《100天精通Python——基础篇 2025 第18天:正则表达式入门实战,解锁字符串处理的魔法力量》
python·正则表达式·re
忆源2 小时前
【Qt】之音视频编程1:QtAV的背景和安装篇
开发语言·qt·音视频
敲键盘的小夜猫2 小时前
Python核心数据类型全解析:字符串、列表、元组、字典与集合
开发语言·python
李匠20243 小时前
C++GO语言微服务之图片、短信验证码生成及存储
开发语言·c++·微服务·golang
apcipot_rain3 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
小彭律师4 小时前
门禁人脸识别系统详细技术文档
笔记·python
鸿业远图科技4 小时前
分式注记种表达方式arcgis
python·arcgis
别让别人觉得你做不到5 小时前
Python(1) 做一个随机数的游戏
python