I already have: - dp_messages table with: - message_id - conversation_id - direction - channel - sender - message_body - template_key - mode - created_at - insert_message() in app/db.py - POST /api/messages in app/main.py I now want to be able to fetch the message history for a conversation. 1) In app/db.py: Add: async def fetch_messages_for_conversation(conversation_id: str, limit: int = 50): """ Return the most recent messages for a conversation, ordered oldest → newest. """ import uuid conv_uuid = uuid.UUID(conversation_id) conn = await get_conn() try: rows = await conn.fetch( """ select message_id, direction, channel, sender, message_body, template_key, mode, created_at from dp_messages where conversation_id = $1 order by created_at asc limit $2 """, conv_uuid, limit, ) return [ { "message_id": str(r["message_id"]), "direction": r["direction"], "channel": r["channel"], "sender": r["sender"], "message_body": r["message_body"], "template_key": r["template_key"], "mode": r["mode"], "created_at": r["created_at"].isoformat() if r["created_at"] else None, } for r in rows ] finally: await release_conn(conn) 2) In app/main.py: - Import the helper: from app.db import fetch_messages_for_conversation - Add a GET endpoint: @app.get("/api/messages") async def api_get_messages( conversation_id: str, limit: int = 50, user: dict = Depends(require_auth), ): """ Return the latest messages for a conversation. """ try: msgs = await fetch_messages_for_conversation(conversation_id, limit=limit) except Exception: logger.exception("Failed to fetch messages") return JSONResponse({"error": "Failed to fetch messages"}, status_code=500) return { "conversation_id": conversation_id, "messages": msgs, } 3) After implementing, restart the server and test: - GET /api/messages?conversation_id=&limit=20 Should return JSON with messages (if any). - For a conversation with no messages, it should return an empty array for "messages".