Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ uvicorn app.main:app
[Public RESTful API](https://nx-ai.onrender.com)


A clean, production-ready Python FastAPI app for [NX](https://goldlabel.pro?s=nx-ai) AI services and more
Production-ready Python FastAPI app for [NX](https://goldlabel.pro?s=nx-ai) AI services and more

- **Python 3.11+**
- **FastAPI** — RESTful API framework
Expand Down
2 changes: 1 addition & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""NX AI - FastAPI"""

# Version tracking
__version__ = "1.0.0"
__version__ = "1.0.2"
55 changes: 45 additions & 10 deletions app/api/routes.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
"""API route definitions for NX AI."""

from fastapi import APIRouter
import os
import time

import psycopg2
Comment on lines +3 to +6
Copy link

Copilot AI Mar 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This module now hard-depends on python-dotenv and psycopg2, but the repo's requirements.txt currently doesn't include them. Add the corresponding dependencies (e.g., python-dotenv and psycopg2-binary/psycopg2) so imports don't fail at runtime.

Copilot uses AI. Check for mistakes.
from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from pydantic import BaseModel

from app import __version__

load_dotenv()

router = APIRouter()


def get_db_connection(): # type: ignore[return]
"""Create and yield a PostgreSQL connection for use as a FastAPI dependency."""
conn = psycopg2.connect(
host=os.getenv('DB_HOST'),
port=os.getenv('DB_PORT', '5432'),
dbname=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
)
try:
yield conn
finally:
conn.close()


class EchoRequest(BaseModel):
"""Request body for the echo endpoint."""

Expand All @@ -18,23 +42,34 @@ class EchoResponse(BaseModel):
echo: str



import time
import sys
from app import __version__

@router.get("/")
def root() -> dict:
"""Return a structured welcome message for the API root."""
def root(conn=Depends(get_db_connection)) -> dict:
"""Return a structured welcome message for the API root, including product data."""
cur = conn.cursor()
try:
cur.execute('SELECT id, name, description, price, in_stock, created_at FROM product;')
products = [
{
"id": row[0],
"name": row[1],
"description": row[2],
"price": str(row[3]) if row[3] is not None else None,
"in_stock": row[4],
"created_at": row[5].isoformat() if row[5] else None,
}
for row in cur.fetchall()
]
finally:
cur.close()
epoch = int(time.time() * 1000)
meta = {
"version": __version__,
"time": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
"epoch": epoch,
"severity": "success",
"message": "NX AI says hello.",
"message": f"NX AI says hello. Returned {len(products)} products.",
}
return {"meta": meta}
return {"meta": meta, "data": products}
Copy link

Copilot AI Mar 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root response shape changed from the previous simple welcome message to {meta, data} and now depends on a live DB connection; the existing tests/test_routes.py::test_root_returns_welcome_message will fail (and CI may fail without a DB). Update tests and/or make DB access injectable/mockable so unit tests don't require external PostgreSQL.

Copilot uses AI. Check for mistakes.


@router.get("/health")
Expand Down
5 changes: 3 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

from fastapi import FastAPI

from app import __version__
from app.api.routes import router

app = FastAPI(
title="NX AI",
description="A clean, modular FastAPI application for AI services.",
version="1.0.0",
description="Production-ready Python FastAPI app for NX",
version=__version__,
)
Comment on lines 8 to 12
Copy link

Copilot AI Mar 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FastAPI(..., version="1.0.0") is now out of sync with app.__version__ (bumped to 1.0.1). Consider sourcing the FastAPI version from app.__version__ so API docs and metadata stay consistent.

Copilot uses AI. Check for mistakes.

app.include_router(router)
29 changes: 29 additions & 0 deletions app/print_products.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import os

import psycopg2
from dotenv import load_dotenv


def main() -> None:
load_dotenv()

conn = psycopg2.connect(
host=os.getenv('DB_HOST'),
port=os.getenv('DB_PORT', '5432'),
dbname=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
)
cur = conn.cursor()
try:
cur.execute('SELECT * FROM product;')
rows = cur.fetchall()
for row in rows:
print(row)
finally:
cur.close()
conn.close()


if __name__ == "__main__":
main()
48 changes: 48 additions & 0 deletions app/seed_product_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import os

import psycopg2
from dotenv import load_dotenv


def main() -> None:
load_dotenv()

conn = psycopg2.connect(
host=os.getenv('DB_HOST'),
port=os.getenv('DB_PORT', '5432'),
dbname=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
)
cur = conn.cursor()
try:
# Create product table with a unique constraint on name for idempotent seeding
cur.execute('''
CREATE TABLE IF NOT EXISTS product (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE,
description TEXT,
price NUMERIC(10, 2) NOT NULL,
in_stock BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
''')

# Insert seed data; skip rows whose name already exists
cur.execute('''
INSERT INTO product (name, description, price, in_stock) VALUES
('Widget', 'A useful widget', 19.99, TRUE),
('Gadget', 'A fancy gadget', 29.99, TRUE),
('Thingamajig', 'An interesting thingamajig', 9.99, FALSE)
ON CONFLICT (name) DO NOTHING;
''')

conn.commit()
print("Product table created and seeded.")
finally:
cur.close()
conn.close()


if __name__ == "__main__":
main()
40 changes: 40 additions & 0 deletions app/test_db_connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import os
import sys

import psycopg2
from dotenv import load_dotenv


def main() -> int:
load_dotenv()

db_host = os.getenv('DB_HOST')
db_port = os.getenv('DB_PORT', '5432')
db_name = os.getenv('DB_NAME')
db_user = os.getenv('DB_USER')
db_password = os.getenv('DB_PASSWORD')

print("Attempting connection with:")
print(f"Host: {db_host}")
print(f"Port: {db_port}")
print(f"Database: {db_name}")
print(f"User: {db_user}")

try:
conn = psycopg2.connect(
host=db_host,
port=db_port,
dbname=db_name,
user=db_user,
password=db_password,
)
print("Connection successful!")
conn.close()
return 0
except Exception as e:
print(f"Connection failed: {e}")
return 1


if __name__ == "__main__":
sys.exit(main())
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ fastapi>=0.110.0
uvicorn[standard]>=0.29.0
httpx>=0.27.0
pytest>=8.1.0
python-dotenv>=1.0.0
psycopg2-binary>=2.9.0
58 changes: 57 additions & 1 deletion tests/test_routes.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,73 @@
"""Unit and integration tests for NX AI routes."""

from unittest.mock import MagicMock

from fastapi.testclient import TestClient

from app.api.routes import get_db_connection
from app.main import app

client = TestClient(app)


<<<<<<< copilot/sub-pr-7
def _mock_db_dependency(rows=None):
"""Return a FastAPI dependency override that yields a mock DB connection."""
if rows is None:
rows = []

def override():
mock_conn = MagicMock()
mock_cursor = MagicMock()
mock_conn.cursor.return_value = mock_cursor
mock_cursor.fetchall.return_value = rows
yield mock_conn

return override


def test_root_returns_product_data() -> None:
"""GET / should return meta and data with product list."""
app.dependency_overrides[get_db_connection] = _mock_db_dependency(rows=[])
try:
response = client.get("/")
assert response.status_code == 200
body = response.json()
assert "meta" in body
assert "data" in body
assert body["meta"]["severity"] == "success"
assert isinstance(body["data"], list)
finally:
app.dependency_overrides.clear()


def test_root_returns_products_from_db() -> None:
"""GET / should include product rows returned by the database."""
from datetime import datetime
from decimal import Decimal
mock_row = (1, "Widget", "A useful widget", Decimal("19.99"), True, datetime(2024, 1, 1, 0, 0, 0))
app.dependency_overrides[get_db_connection] = _mock_db_dependency(rows=[mock_row])
try:
response = client.get("/")
assert response.status_code == 200
body = response.json()
assert len(body["data"]) == 1
assert body["data"][0]["name"] == "Widget"
assert body["data"][0]["price"] == "19.99"
assert "Returned 1 products" in body["meta"]["message"]
finally:
app.dependency_overrides.clear()
=======
def test_root_returns_welcome_message() -> None:
"""GET / should return a welcome message."""
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Welcome to NX AI!"}
json_data = response.json()
assert "meta" in json_data
assert "data" in json_data
assert "message" in json_data["meta"]
assert "NX AI" in json_data["meta"]["message"]
>>>>>>> staging


def test_health_returns_ok() -> None:
Expand Down
Loading