Skip to main content

Command Palette

Search for a command to run...

Debug function in Fastapi like Laravel

Updated
2 min read
Debug function in Fastapi like Laravel
M

I am Mandeep Singh, a full-stack developer. I created this Blog to bestow my coding experience and love to write on JavaScript, Next.js, Laravel and little bit Unity Game development.

In FastAPI / Python, there is no die() or dd() like PHP/Laravel —
but you can achieve the same thing very easily.

Here are the 4 best methods depending on what you want.


1. Hard Stop (exact equivalent of die('dd'))

Use raise with a custom message:

raise Exception("STOP HERE (dd)")

This will immediately stop the request and show the message in logs + API response (500 error).


2. Pretty Debug Dump (like Laravel dd($var))

Use print() + raise:

import pprint
pprint.pprint(room)
raise Exception("DD STOP")

This prints the value like Laravel dd() and stops execution.


3. Return debug JSON directly (like return dd())

return {"debug": str(room)}

or pretty version:

from fastapi.responses import JSONResponse
return JSONResponse({"debug": room.__dict__})

4. Use assert False (quick & dirty debugging)

assert False, room

This instantly stops execution and prints room in logs.


⭐ Best method for debugging inside your current code

You have:

logger.info(f"session_data={session_data}")
logger.info(f"room_query={room_query}")
logger.info(f"room={room}")

Add:

raise Exception(f"DD: room={room}")

So your final block becomes:

room_query = select(ChatRoom).where(ChatRoom.id == session_data.chat_room_id)
room_result = await db.execute(room_query)
room = room_result.scalar_one_or_none()

print("DD ROOM =", room)
raise Exception("STOP EXECUTION HERE")

👍 Want an even cleaner Laravel-style dd() for FastAPI?

I can give you a small helper:

def dd(*values):
    import pprint
    for v in values:
        pprint.pprint(v)
    raise Exception("DD STOP")

Then use:

dd(room, session_data)

Works exactly like Laravel 🙂


More from this blog

Mandeep Singh Blog

117 posts