FastAPI Full CRUD – Complete Working Code (Copy & Run)
This is the complete, runnable FastAPI project.
Your students can copy, paste, save as main.py, and run using uvicorn.
📌 main.py (Complete CRUD App)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI(title="FastAPI CRUD Demo")
# --------------------------
# 1️⃣ Pydantic Model
# --------------------------
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
in_stock: bool = True
# --------------------------
# 2️⃣ In-Memory List DB
# --------------------------
items_db: List[Item] = []
# --------------------------
# 3️⃣ CREATE Item
# --------------------------
@app.post("/items/", response_model=Item)
def create_item(item: Item):
items_db.append(item)
return item
# --------------------------
# 4️⃣ READ All Items
# --------------------------
@app.get("/items/", response_model=List[Item])
def read_items():
return items_db
# --------------------------
# 5️⃣ READ Single Item
# --------------------------
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
if item_id >= len(items_db):
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
# --------------------------
# 6️⃣ UPDATE Item
# --------------------------
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item: Item):
if item_id >= len(items_db):
raise HTTPException(status_code=404, detail="Item not found")
items_db[item_id] = item
return item
# --------------------------
# 7️⃣ DELETE Item
# --------------------------
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id >= len(items_db):
raise HTTPException(status_code=404, detail="Item not found")
deleted = items_db.pop(item_id)
return {"message": "Item deleted", "deleted_item": deleted}
# Run using:
# uvicorn main:app --reload
🚀 How to Run This FastAPI App
1️⃣ Install FastAPI + Uvicorn
pip install fastapi uvicorn
2️⃣ Save the above full code as:
main.py
3️⃣ Run the FastAPI Server
uvicorn main:app --reload
4️⃣ Test in Browser
- Swagger Docs → http://127.0.0.1:8000/docs
- Interactive API testing
- No extra tools needed
5️⃣ Students Can Test CRUD
- POST → Add item
- GET → View all
- GET /items/0 → View first item
- PUT /items/0 → Update
- DELETE /items/0 → Delete
🎉 Your Full CRUD Demo Is Ready!
This has everything: full code, syntax highlighting, and copy buttons. Paste into Blogger → HTML mode and publish.
No comments:
Post a Comment