fastapi-debug-toolbar icon indicating copy to clipboard operation
fastapi-debug-toolbar copied to clipboard

Fix compatibility with custom `default_response_class`

Open scriptogre opened this issue 2 months ago • 0 comments

Problem

When a FastAPI app has a custom default_response_class, the debug toolbar's API route inherits this default instead of properly returning JSON, causing encoding errors.

Reproduce the issue

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from debug_toolbar.middleware import DebugToolbarMiddleware

# App with custom default response class
app = FastAPI(default_response_class=HTMLResponse)
app.add_middleware(DebugToolbarMiddleware)

Error when accessing /_debug_toolbar?...:

AttributeError: 'dict' object has no attribute 'encode'

This happens because:

  1. Debug toolbar API returns a dictionary (JSON data)
  2. Route inherits HTMLResponse from app's default
  3. HTMLResponse tries to encode the dict as a string → crash

Solution

Explicitly set response_class=JSONResponse for the debug toolbar API route to ensure it returns JSON regardless of the app's default response class.

scriptogre avatar Sep 14 '25 08:09 scriptogre