Skip to content

Conversation

@scriptogre
Copy link

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.

Explicitly set response_class=JSONResponse for debug toolbar API route to prevent conflicts when FastAPI apps override default_response_class (e.g., to HTMLResponse). 

Without this, the toolbar returns 
  JSON data but inherits HTMLResponse, causing encoding errors.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant