From 3e3de2845ac181e38183eff3fb4f63ee7e71c288 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Fri, 28 Mar 2025 14:38:01 +0000 Subject: [PATCH] feat: Update endpoint routemapping --- endpoints/routemapping.post.py | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/endpoints/routemapping.post.py b/endpoints/routemapping.post.py index e69de29..245b7f9 100644 --- a/endpoints/routemapping.post.py +++ b/endpoints/routemapping.post.py @@ -0,0 +1,62 @@ +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!"}