2026-01-11 17:31:58 -05:00

62 lines
1.5 KiB
Python

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from sqlalchemy import insert
from sqlalchemy.exc import SQLAlchemyError
from db import check_database_connection, create_database_tables, engine, items_table
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ItemCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
class ItemResponse(BaseModel):
id: int
name: str
@app.on_event("startup")
def on_startup() -> None:
create_database_tables()
@app.get("/hello")
def hello():
return {"message": "Hello from FastAPI bro"}
@app.get("/db/health")
def db_health():
try:
check_database_connection()
except SQLAlchemyError as exc:
raise HTTPException(status_code=500, detail="Database connection failed") from exc
return {"status": "ok"}
@app.post("/items", response_model=ItemResponse, status_code=201)
def create_item(payload: ItemCreate):
try:
with engine.begin() as connection:
result = connection.execute(
insert(items_table)
.values(name=payload.name)
.returning(items_table.c.id, items_table.c.name)
)
row = result.one()
except SQLAlchemyError as exc:
raise HTTPException(status_code=500, detail="Failed to create item") from exc
return {"id": row.id, "name": row.name}