Skip to main content
In this lesson we’ll finish wiring the tool to a persistent backend by replacing Faker-based generation with real rows read from a local SQLite database (fakedata.db). This demonstrates a simple repository pattern with FastAPI, how to keep endpoints thin, and common pitfalls to watch for (file paths, imports, and SQL parameter bindings). It also shows how GitHub Copilot can speed refactors — but you should review structural suggestions before applying them. We began with an existing FastAPI endpoint that used Faker:
We replaced the Faker logic with a small repository module that encapsulates the SQLite access and returns rows as dictionaries. Before implementing, I inspected the DB with DB Browser for SQLite to confirm the table name and columns.
A screenshot of DB Browser for SQLite showing a "fake_data" table with columns like first_name, last_name, email_address, age, city and occupation populated with sample records. A code editor/IDE (Visual Studio Code) project is visible in the background.
Summary of the approach
  • Add a repository module to encapsulate DB operations and SQL queries.
  • Replace Faker-based generation in the endpoint with a call to the repository.
  • Keep the FastAPI endpoint focused on request validation and delegation.
  • Troubleshoot common issues: DB path, relative imports, and SQL parameter binding.
Below are the consolidated, cleaned-up artifacts used to perform the swap. Files overview

data/fake_data_repository.py

This module contains the DB connection helper and the query that returns randomly sampled rows. It returns rows as dictionaries.
Notes and best practices
  • Use an explicit DB_PATH so it’s easy to change if fakedata.db lives elsewhere.
  • Use parameterized queries with ? placeholders to avoid SQL injection and binding issues.
  • Convert sqlite3.Row to dict before returning for JSON serialization.

api/endpoints/router.py

Keep the endpoint small: validate the request via Pydantic, call the repository, and return results.
Important: ensure imports reflect your package layout. Running the app from the project root (so src is on the import path) or adjusting PYTHONPATH may be necessary. If you run into import errors such as “ModuleNotFoundError: No module named ‘src’” or “attempted relative import beyond top-level package”, prefer imports that match how you run the application (absolute imports from the package root are usually clearer).

api/models/fake_data_request.py

Simplify the request model to match the endpoint’s contract (we’re only using count now).
When you change the request model, remember to update any clients (Postman, frontends) to only include count (and optionally locale) so FastAPI doesn’t return a 422 Unprocessable Entity. Example request body:
Example response (successful):

Troubleshooting highlights and fixes

Common issues are file path mismatches and import errors. Verify that DB_PATH points to the actual fakedata.db file and that your Python import paths match how you run the server (e.g., run from src or adjust PYTHONPATH).
  • Relative import problems
    • Error: ImportError: attempted relative import beyond top-level package or ModuleNotFoundError: No module named 'src'.
    • Fix: Use imports consistent with how you launch the app. For a layout like src/api/... and starting the server from src, prefer from api.models.fake_data_request import FakeDataRequest and from data.fake_data_repository import get_fake_data. Alternatively, run python -m from the project root or set PYTHONPATH appropriately.
  • Database file location
    • Error: Database error: no such table: fake_data
    • Fix: Verify fakedata.db exists at the path your code expects. DB Browser can open a copy of that file in a different folder — confirm the absolute path or move the DB file.
  • SQL parameter binding
    • Error: Incorrect number of bindings supplied. The current statement uses ?, and there are 0 supplied.
    • Cause: Calling cursor.execute(query) when query has ? placeholders requires passing a tuple/list of parameters. Use cursor.execute(query, (count,)).
    • If you remove LIMIT temporarily and still use parameter binding, update the call accordingly.
  • Debugging tip
    • Print or inspect the DB schema: execute PRAGMA table_info(fake_data); and SELECT COUNT(*) FROM fake_data; to validate columns and row count. Example quick script:

Lessons learned

  • GitHub Copilot can accelerate refactors (for example, creating a repository module and replacing Faker usage with DB access), but it may also propose new files, folders, or import styles that don’t match your project layout. Review suggestions before applying them.
  • Keep FastAPI endpoints thin — move DB and business logic into a repository or service layer for testability and clarity.
  • With local SQLite files, be explicit about the DB path and run the server from a location that matches your import layout.
  • Make small, iterative changes and test frequently. Errors encountered while developing (database or import errors) are useful signals that your new code paths are exercised.
Tip: Use GitHub Copilot to suggest code and comments, but keep control over structure and imports. Small, deliberate edits reduce the chance of the assistant creating mismatched files or confusing folder structures.

Next steps
  • Add in-code documentation and unit tests for data/fake_data_repository.py.
  • Expand the repository to optionally return specific fields (e.g., only name or email) for a granular data_type filter.
  • Consider adding pagination or cursor-based retrieval for large datasets.
Links and references

Watch Video