Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from typing import List | |
| app = FastAPI( | |
| title="FastAPI CRUD Example", | |
| description="A simple CRUD API with FastAPI", | |
| version="1.0.0", | |
| docs_url="/docs", | |
| redoc_url="/redoc" | |
| ) | |
| items = [] | |
| class Item(BaseModel): | |
| id: int | |
| name: str | |
| description: str = None | |
| async def root(): | |
| return {"message": "Welcome to FastAPI CRUD API! Visit /docs for Swagger UI."} | |
| async def get_items(): | |
| return items | |
| async def add_item(item: Item): | |
| if any(i.id == item.id for i in items): | |
| raise HTTPException(status_code=400, detail="Item ID already exists") | |
| items.append(item) | |
| return item | |
| async def update_item(item_id: int, updated_item: Item): | |
| for index, item in enumerate(items): | |
| if item.id == item_id: | |
| items[index] = updated_item | |
| return updated_item | |
| raise HTTPException(status_code=404, detail="Item not found") | |
| async def delete_item(item_id: int): | |
| for item in items: | |
| if item.id == item_id: | |
| items.remove(item) | |
| return {"message": "Item deleted"} | |
| raise HTTPException(status_code=404, detail="Item not found") |