75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from pydantic import BaseModel
|
|
from typing import List, Optional
|
|
|
|
app = FastAPI(title="FastAPI Server", version="1.0.0")
|
|
|
|
# CORS middleware to allow client requests
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["http://localhost:3000", "http://client:3000"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
class Item(BaseModel):
|
|
id: int
|
|
name: str
|
|
description: Optional[str] = None
|
|
price: float
|
|
|
|
# In-memory database
|
|
items_db = [
|
|
Item(id=1, name="Laptop", description="High-performance laptop", price=999.99),
|
|
Item(id=2, name="Mouse", description="Wireless mouse", price=29.99),
|
|
Item(id=3, name="Keyboard", description="Mechanical keyboard", price=79.99),
|
|
]
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {"message": "FastAPI Server is running!"}
|
|
|
|
@app.get("/items", response_model=List[Item])
|
|
async def get_items():
|
|
return items_db
|
|
|
|
@app.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 item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return item
|
|
|
|
@app.post("/items", response_model=Item)
|
|
async def create_item(item: Item):
|
|
if any(existing_item.id == item.id for existing_item in items_db):
|
|
raise HTTPException(status_code=400, detail="Item ID already exists")
|
|
items_db.append(item)
|
|
return item
|
|
|
|
@app.put("/items/{item_id}", response_model=Item)
|
|
async def update_item(item_id: int, item: Item):
|
|
if item.id != item_id:
|
|
raise HTTPException(status_code=400, detail="Item ID mismatch")
|
|
|
|
for idx, existing_item in enumerate(items_db):
|
|
if existing_item.id == item_id:
|
|
items_db[idx] = item
|
|
return item
|
|
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
@app.delete("/items/{item_id}")
|
|
async def delete_item(item_id: int):
|
|
for idx, item in enumerate(items_db):
|
|
if item.id == item_id:
|
|
deleted_item = items_db.pop(idx)
|
|
return {"message": f"Item {deleted_item.name} deleted successfully"}
|
|
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(app, host="0.0.0.0", port=8000) |