Spaces:
Sleeping
Sleeping
create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
app = FastAPI(
|
| 6 |
+
title="FastAPI CRUD Example",
|
| 7 |
+
description="A simple CRUD API with FastAPI",
|
| 8 |
+
version="1.0.0",
|
| 9 |
+
docs_url="/docs",
|
| 10 |
+
redoc_url="/redoc"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
# In-memory storage
|
| 14 |
+
items = []
|
| 15 |
+
|
| 16 |
+
class Item(BaseModel):
|
| 17 |
+
id: int
|
| 18 |
+
name: str
|
| 19 |
+
description: str = None
|
| 20 |
+
|
| 21 |
+
@app.get("/")
|
| 22 |
+
async def root():
|
| 23 |
+
return {"message": "Welcome to FastAPI CRUD API! Go to /docs to test the API."}
|
| 24 |
+
|
| 25 |
+
@app.get("/items", response_model=List[Item])
|
| 26 |
+
async def get_items():
|
| 27 |
+
return items
|
| 28 |
+
|
| 29 |
+
@app.post("/items", response_model=Item)
|
| 30 |
+
async def add_item(item: Item):
|
| 31 |
+
if any(i.id == item.id for i in items):
|
| 32 |
+
raise HTTPException(status_code=400, detail="Item ID already exists")
|
| 33 |
+
items.append(item)
|
| 34 |
+
return item
|
| 35 |
+
|
| 36 |
+
@app.put("/items/{item_id}", response_model=Item)
|
| 37 |
+
async def update_item(item_id: int, updated_item: Item):
|
| 38 |
+
for index, item in enumerate(items):
|
| 39 |
+
if item.id == item_id:
|
| 40 |
+
items[index] = updated_item
|
| 41 |
+
return updated_item
|
| 42 |
+
raise HTTPException(status_code=404, detail="Item not found")
|
| 43 |
+
|
| 44 |
+
@app.delete("/items/{item_id}")
|
| 45 |
+
async def delete_item(item_id: int):
|
| 46 |
+
for item in items:
|
| 47 |
+
if item.id == item_id:
|
| 48 |
+
items.remove(item)
|
| 49 |
+
return {"message": "Item deleted"}
|
| 50 |
+
raise HTTPException(status_code=404, detail="Item not found")
|