11"""API route definitions for NX AI."""
22
3- from fastapi import APIRouter
3+ import os
4+ import time
5+
6+ import psycopg2
7+ from dotenv import load_dotenv
8+ from fastapi import APIRouter , Depends
49from pydantic import BaseModel
510
11+ from app import __version__
12+
13+ load_dotenv ()
14+
615router = APIRouter ()
716
817
18+ def get_db_connection (): # type: ignore[return]
19+ """Create and yield a PostgreSQL connection for use as a FastAPI dependency."""
20+ conn = psycopg2 .connect (
21+ host = os .getenv ('DB_HOST' ),
22+ port = os .getenv ('DB_PORT' , '5432' ),
23+ dbname = os .getenv ('DB_NAME' ),
24+ user = os .getenv ('DB_USER' ),
25+ password = os .getenv ('DB_PASSWORD' ),
26+ )
27+ try :
28+ yield conn
29+ finally :
30+ conn .close ()
31+
32+
933class EchoRequest (BaseModel ):
1034 """Request body for the echo endpoint."""
1135
@@ -18,23 +42,34 @@ class EchoResponse(BaseModel):
1842 echo : str
1943
2044
21-
22- import time
23- import sys
24- from app import __version__
25-
2645@router .get ("/" )
27- def root () -> dict :
28- """Return a structured welcome message for the API root."""
46+ def root (conn = Depends (get_db_connection )) -> dict :
47+ """Return a structured welcome message for the API root, including product data."""
48+ cur = conn .cursor ()
49+ try :
50+ cur .execute ('SELECT id, name, description, price, in_stock, created_at FROM product;' )
51+ products = [
52+ {
53+ "id" : row [0 ],
54+ "name" : row [1 ],
55+ "description" : row [2 ],
56+ "price" : str (row [3 ]) if row [3 ] is not None else None ,
57+ "in_stock" : row [4 ],
58+ "created_at" : row [5 ].isoformat () if row [5 ] else None ,
59+ }
60+ for row in cur .fetchall ()
61+ ]
62+ finally :
63+ cur .close ()
2964 epoch = int (time .time () * 1000 )
3065 meta = {
3166 "version" : __version__ ,
3267 "time" : time .strftime ('%Y-%m-%d %H:%M:%S' , time .localtime ()),
3368 "epoch" : epoch ,
3469 "severity" : "success" ,
35- "message" : "NX AI says hello." ,
70+ "message" : f "NX AI says hello. Returned { len ( products ) } products ." ,
3671 }
37- return {"meta" : meta }
72+ return {"meta" : meta , "data" : products }
3873
3974
4075@router .get ("/health" )
0 commit comments