72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from typing import List
|
|
|
|
from app.models import Item, dummy_items
|
|
|
|
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=["*"],
|
|
)
|
|
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {"message": "FastAPI Server is running!"}
|
|
|
|
|
|
@app.get("/items", response_model=List[Item])
|
|
async def get_items():
|
|
return dummy_items
|
|
|
|
|
|
@app.get("/items/{item_id}", response_model=Item)
|
|
async def get_item(item_id: int):
|
|
item = next((item for item in dummy_items 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 dummy_items):
|
|
raise HTTPException(status_code=400, detail="Item ID already exists")
|
|
dummy_items.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(dummy_items):
|
|
if existing_item.id == item_id:
|
|
dummy_items[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(dummy_items):
|
|
if item.id == item_id:
|
|
deleted_item = dummy_items.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)
|