from fastapi import FastAPI, APIRouter, HTTPException from pydantic import BaseModel from typing import List app = FastAPI() # Router instance router = APIRouter() # Sample data model class Item(BaseModel): id: int name: str description: str = None price: float available: bool # In-memory database (for demonstration) items_db = [] # GET route to fetch all items @router.get("/items", response_model=List[Item]) async def get_items(): return items_db # GET route to fetch a single item by ID @router.get("/items/{item_id}", response_model=Item) async def get_item(item_id: int): item = next((item for item in items_db if item.id == item_id), None) if not item: raise HTTPException(status_code=404, detail="Item not found") return item # POST route to create a new item @router.post("/items", response_model=Item) async def create_item(item: Item): items_db.append(item) return item # PUT route to update an existing item by ID @router.put("/items/{item_id}", response_model=Item) async def update_item(item_id: int, updated_item: Item): for index, item in enumerate(items_db): if item.id == item_id: items_db[index] = updated_item return updated_item raise HTTPException(status_code=404, detail="Item not found") # DELETE route to delete an item by ID @router.delete("/items/{item_id}") async def delete_item(item_id: int): global items_db items_db = [item for item in items_db if item.id != item_id] return {"detail": "Item deleted successfully"} # Include the router in the main FastAPI app app.include_router(router, prefix="/api/v1", tags=["items"]) # Root endpoint @app.get("/") async def root(): return {"message": "Welcome to the FastAPI app!"}