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

相关推荐
Hylan_J12 分钟前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
软件黑马王子16 分钟前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
莫忘初心丶16 分钟前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
闲猫19 分钟前
go orm GORM
开发语言·后端·golang
李白同学2 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?3 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
失败尽常态5233 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447743 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农3 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿3 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法