Skip to main content

SQL Profiler for FastAPI + SQLAlchemy with HTML UI

Project description

fastapi-sqlalchemy-profiler

A lightweight SQL query profiler for FastAPI + SQLAlchemy applications.

This tool captures:

  • All SQL queries executed per request
  • Total SQL execution time
  • Average query time
  • Slowest query
  • N+1 query detection
  • Beautiful, responsive HTML dashboard at:

Perfect for diagnosing ORM performance issues, debugging inefficient queries, or validating database behavior during development.


🚀 Features

🔍 Request-Level SQL Profiling

Tracks every SQL query executed during a FastAPI request:

  • SQLAlchemy Core queries
  • SQLAlchemy ORM queries
  • Queries from async AsyncSession.execute()
  • Queries triggered by your services, repositories, dependencies, etc.

⚡ Performance Insights

  • Total query time for request
  • Average query time
  • Slowest query
  • Full query text preview

🟥 Automatic N+1 Detection

Automatically detects repeated SQL patterns, such as:

SELECT * FROM comments WHERE post_id = ?
SELECT * FROM comments WHERE post_id = ?
...

The HTML dashboard shows:

  • How many times the query repeated

  • A preview of the repeated SQL

  • 🎨 Modern HTML UI (Dark Mode)

  • Fully responsive

  • Minimalistic dark theme

  • Collapsible SQL query blocks

  • color-coded method badges

  • No external JS or CSS

  • Only builtin browser HTML/CSS

🎯 Zero Configuration

Enable with just:

app.add_middleware(SQLProfilerMiddleware, enabled=True)
app.include_router(profiler_router)
attach_sqlalchemy_listeners(engine)

📦 Installation

Install from local (development mode)

Clone/create the directory then run:
pip install -e ./fastapi-sqlalchemy-profiler

This installs the package in editable mode, meaning code updates take effect instantly without reinstalling.

🧩 Requirements

Component Supported Versions

  • Python 3.11+
  • FastAPI Any version
  • Starlette Any version
  • SQLAlchemy 1.4.x or 2.x
  • Databases PostgreSQL, MySQL, SQLite, etc.
  • Async drivers asyncpg, aiosqlite, aiomysql, etc. 🛠 Compatible Tech Stack

This profiler works great with:

Frameworks

  • FastAPI

  • Starlette

Database layers

  • SQLAlchemy ORM

  • SQLAlchemy Core

  • AsyncEngine / AsyncSession

  • Sync Engine + Session

Drivers

  • asyncpg

  • aiomysql

  • aiosqlite

  • psycopg2 / pg8000 (for sync engines)

🛠 Example Usage (FastAPI + SQLAlchemy Async)

Here is how to integrate it in your existing app:

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import create_async_engine

from fastapi_sqlalchemy_profiler import (
    SQLProfilerMiddleware,
    attach_sqlalchemy_listeners,
    profiler_router
)

DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/db"

engine = create_async_engine(DATABASE_URL, echo=False)

# Attach SQLAlchemy event listeners
attach_sqlalchemy_listeners(engine)

app = FastAPI()

# Add profiler middleware (recommended only in DEBUG mode)
app.add_middleware(SQLProfilerMiddleware, enabled=True)

# Add HTML profiler UI
app.include_router(profiler_router)

Start your app:

uvicorn main:app --reload

Then open: http://localhost:8000/debug/sql-profiler

🧪 Example Output (HTML)

🔥 Request Summary

GET /api/v1/productions
Queries: 18 • Total: 32.4 ms • Avg: 1.8 ms • Slowest: 4.1 ms

🟥 N+1 Warning

⚠️ N+1 queries detected

× 12
SELECT comments.id, comments.text, comments.post_id
FROM comments
WHERE comments.post_id = ?

📄 Full Query List (collapsible)

  • Per-query execution time

  • SQL text pretty-printed

  • Expand/collapse blocks

⚠️ Recommended: Use Only in Development

This tool is intended for:

  • local debugging

  • performance tuning

  • verifying ORM behavior

  • diagnosing N+1 issues

  • Do NOT enable in production.

For safety:

app.add_middleware(SQLProfilerMiddleware, enabled=settings.DEBUG)

🤝 Contributing

PRs and feature requests welcome:

  • Add slow query highlighting

  • Add auto-refresh mode

  • Expand N+1 heuristics

  • Add JSON API export

  • Improve UI styling

📄 License

MIT License — open for personal and commercial use.

⭐ Like this tool?

Leave a star or contribute! Your support helps make FastAPI development faster and debugging easier.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_sqlalchemy_profiler-0.1.1.tar.gz (4.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_sqlalchemy_profiler-0.1.1-py3-none-any.whl (4.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_sqlalchemy_profiler-0.1.1.tar.gz.

File metadata

File hashes

Hashes for fastapi_sqlalchemy_profiler-0.1.1.tar.gz
Algorithm Hash digest
SHA256 a75646b98be6bcb0f9e92e8f63b648b0b9ad25101d1f35a0c19c692bc2f61878
MD5 2328e4980d4bc589acb707cc3140846b
BLAKE2b-256 42d2fb7e182e6cd43d491bd72a8c7e5294e5b317948df16dae48f958a589a2e0

See more details on using hashes here.

File details

Details for the file fastapi_sqlalchemy_profiler-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_sqlalchemy_profiler-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ed27f2b47643c0c3c6e3155bda72f2491b60eb7ea89896550a5758af68f80b0e
MD5 2d021fd6ee046f51ae11c3828bb6f12c
BLAKE2b-256 6d4edfa095a7710c707aa26205654807f7049f1946c362b074b51e0b4d437951

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page