later / app.py
GVAmaresh
dev: to check working
0932d40
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Item(BaseModel):
id: int
name: str
description: str
price: float
quantity: int
items_db: List[Item] = [
Item(id=1, name="Laptop", description="A powerful laptop", price=1200.50, quantity=10),
Item(id=2, name="Smartphone", description="A high-end smartphone", price=800.00, quantity=20),
Item(id=3, name="Headphones", description="Noise-canceling headphones", price=150.00, quantity=50),
]
@app.get("/")
def read_root():
return {"message": "Welcome to the FastAPI application!"}
@app.get("/items/", response_model=List[Item])
def get_items():
"""
Get all items.
"""
return items_db
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int):
"""
Get an item by its ID.
"""
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
@app.post("/items/", response_model=Item)
def create_item(item: Item):
"""
Add a new item.
"""
if any(existing_item.id == item.id for existing_item in items_db):
raise HTTPException(status_code=400, detail="Item with this ID already exists")
items_db.append(item)
return item
@app.get("/health")
def health_check():
return {"status": "OK"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=1200)