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

相关推荐
飞翔的佩奇2 小时前
【完整源码+数据集+部署教程】表盘指针检测系统源码和数据集:改进yolo11-CA-HSFPN
python·yolo·计算机视觉·数据集·yolo11·表盘指针检测
larance2 小时前
SQLAlchemy 的异步操作来批量保存对象列表
数据库·python
搏博3 小时前
基于Python3.10.6与jieba库的中文分词模型接口在Windows Server 2022上的实现与部署教程
windows·python·自然语言处理·flask·中文分词
麦兜*4 小时前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3
lxmyzzs4 小时前
pyqt5无法显示opencv绘制文本和掩码信息
python·qt·opencv
萧鼎5 小时前
Python pyzmq 库详解:从入门到高性能分布式通信
开发语言·分布式·python
艾伦~耶格尔6 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
yujkss6 小时前
Python脚本每天爬取微博热搜-终版
开发语言·python
yzx9910136 小时前
小程序开发APP
开发语言·人工智能·python·yolo
飞翔的佩奇6 小时前
【完整源码+数据集+部署教程】二维码与查找模式检测系统源码和数据集:改进yolo11-CSwinTransformer
python·yolo·计算机视觉·数据集·yolo11·二维码与查找模式检测