Zie619/n8n-workflows · error · HTTPException

Error fetching stats: {str(e)}

Error message

Error fetching stats: {str(e)}

What it means

A 500 response from GET /api/stats in api_server.py. The handler wraps db.get_stats() in a broad except and re-raises as HTTPException(500) with the original exception text. It means the workflow database (SQLite) could not be opened, is empty, or its schema does not match what WorkflowDB.get_stats() expects.

Source

Thrown at api_server.py:235

        """
        )
    return FileResponse(str(index_file))


@app.get("/health")
async def health_check():
    """Health check endpoint."""
    return {"status": "healthy", "message": "N8N Workflow API is running"}


@app.get("/api/stats", response_model=StatsResponse)
async def get_stats():
    """Get workflow database statistics."""
    try:
        stats = db.get_stats()
        return StatsResponse(**stats)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error fetching stats: {str(e)}")


@app.get("/api/workflows", response_model=SearchResponse)
async def search_workflows(
    q: str = Query("", description="Search query"),
    trigger: str = Query("all", description="Filter by trigger type"),
    complexity: str = Query("all", description="Filter by complexity"),
    active_only: bool = Query(False, description="Show only active workflows"),
    page: int = Query(1, ge=1, description="Page number"),
    per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
    """Search and filter workflows with pagination."""
    try:
        offset = (page - 1) * per_page

        workflows, total = db.search_workflows(
            query=q,
            trigger_filter=trigger,

View on GitHub (pinned to 94007c1445)

Solutions

  1. Run the indexer once to build the database before serving requests (python api_server.py or the indexing entrypoint used by this repo).
  2. Start the server from the repository root so the relative SQLite/DB path and 'workflows' directory resolve correctly.
  3. Delete the stale workflows.db and reindex if the schema was created by an incompatible version.
  4. Reproduce the root cause by reading the server console: the underlying exception text is embedded in the detail string.

Example fix

# before
stats = db.get_stats()

# after (guard with a friendly message when DB is unindexed)
try:
    stats = db.get_stats()
except Exception:
    raise HTTPException(status_code=503, detail="Database not initialized. Run the workflow indexer first.")
Defensive patterns

Strategy: try-catch

Validate before calling

import urllib.request, json

def stats_ok(base):
    try:
        with urllib.request.urlopen(base + '/api/stats', timeout=5) as r:
            return r.status == 200 and 'total_workflows' in json.load(r)
    except Exception:
        return False

Try / catch

try:
    stats = client.get('/api/stats').json()
except (ConnectionError, Timeout):
    print('API unreachable')
except KeyError:
    print('Unexpected stats payload — reindex the database')

Prevention

When it happens

Trigger: Calling GET /api/stats when workflows.db does not exist (server started from a directory without an initialized database), when the DB file was created by an older schema version, or when get_stats() throws on empty/NULL aggregates after a partial index.

Common situations: Starting uvicorn from a different working directory so the relative DB path resolves elsewhere; cloning the repo and running the API before running the indexer; a crashed first indexing run leaving a schema-initialized but data-less DB.

Related errors


AI-assisted analysis of Zie619/n8n-workflows@94007c1445 (2026-08-15). Data as JSON: /api/errors/0aa3e4fb2fec2136. Report an issue: GitHub.