Create src/data/fake_data_repository.py to centralize all SQLite interactions following the repository pattern.
Copy
Ask AI
# src/data/fake_data_repository.py"""Database operations for fake data using SQLite."""import sqlite3from typing import List, Dict, Anyfrom fastapi import HTTPExceptiondef get_db_connection() -> sqlite3.Connection: """ Establish a connection to the SQLite database. Returns: sqlite3.Connection: A connection object with row factory set. Raises: HTTPException: If the database connection fails. """ try: conn = sqlite3.connect("fakedata.db") conn.row_factory = sqlite3.Row return conn except sqlite3.Error as e: raise HTTPException( status_code=500, detail=f"Database connection error: {e}" )def get_fake_data(count: int) -> List[Dict[str, Any]]: """ Retrieve a specified number of random records from the database. Args: count (int): How many records to retrieve. Returns: List[Dict[str, Any]]: A list of dictionaries representing fake data. Raises: HTTPException: On query execution error. """ query = """ SELECT first_name, last_name, email_address, age, city, occupation FROM fake_data ORDER BY RANDOM() LIMIT ? """ conn = get_db_connection() try: cursor = conn.cursor() cursor.execute(query, (count,)) rows = cursor.fetchall() return [dict(row) for row in rows] except sqlite3.Error as e: raise HTTPException(status_code=500, detail=f"Database error: {e}") finally: conn.close()
Define a Pydantic model in src/api/models/fake_data_request.py to validate incoming JSON payloads.
Copy
Ask AI
# src/api/models/fake_data_request.pyfrom pydantic import BaseModelfrom typing import Optionalclass FakeDataRequest(BaseModel): """ Model to validate fake data retrieval requests. Attributes: count (int): Number of records to return. locale (Optional[str]): Locale code (unused in SQLite). """ count: int locale: Optional[str] = "en_US"
Include the endpoint router in your FastAPI app entry point at src/main.py.
Copy
Ask AI
# src/main.pyfrom fastapi import FastAPIfrom api.endpoints.router import router as fake_data_routerapp = FastAPI( title="FastAPI Fake Data Generator", description="API that serves random fake data from an SQLite database", version="1.0.0",)app.include_router(fake_data_router, prefix="/api")
Always close the database connection in a finally block to prevent resource leaks.