EstateHub

Messaging API and WebSocket Integration

This document explains how the frontend should integrate EstateHub messaging.

Messaging uses both REST and WebSocket:

  • REST loads conversations, message history, and persistent state.

  • WebSocket sends and receives live events for the active conversation.

Base URLs

REST base:

TEXT
http://localhost:8000/api/v1/messages

WebSocket base:

TEXT
ws://localhost:8000/ws

Use wss:// in production.

Auth

REST requests use the normal bearer token:

HTTP
Authorization: Bearer <access_token>
Content-Type: application/json

WebSocket connections pass the same access token as a query parameter:

TEXT
ws://localhost:8000/ws/conversations/<conversation_id>/?token=<access_token>

If the token is missing, expired, invalid, or the user is not a participant in the conversation, the socket closes with code 4403.

  1. Load the conversation list with REST.

  2. When the user opens a conversation, load its message history with REST.

  3. Open a WebSocket for that conversation.

  4. Send new messages through WebSocket.

  5. Listen for message.created and append/update messages in the active thread.

  6. Send message.read when the user views the conversation.

  7. Close the previous socket when switching conversations.

  8. Reconnect the socket if the network drops.

1. REST Endpoints

1.1 List Conversations

GET/messages/conversations/

Auth: Required

Query params:

TEXT
page=1
status=open
archived=false
unread=true
property_id=<uuid>
q=search text

q and search are accepted as aliases. status accepts open, in_progress, closed, or canceled.

Response shape:

JSON
{
  "success": true,
  "message": "Conversations retrieved successfully.",
  "data": {
    "conversations": {
      "count": 1,
      "next": null,
      "previous": null,
      "results": [
        {
          "id": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
          "property": {
            "id": "32bb890e-1ae3-46df-a892-25cf5a580e62",
            "title": "Downtown Condo",
            "slug": "downtown-condo",
            "address": "110 Example Lane, Austin, TX 78701",
            "city": "Austin",
            "area_name": "Downtown",
            "price": "625000.00",
            "currency": "USD",
            "primary_media": null
          },
          "buyer": {
            "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
            "full_name": "Jane Customer",
            "email": "jane@example.com",
            "avatar_url": ""
          },
          "seller": {
            "id": "ee163984-c2d6-4b69-a06f-ea109ee4b4cc",
            "full_name": "Property Seller",
            "email": "seller@example.com",
            "avatar_url": ""
          },
          "agent": null,
          "context_type": "general",
          "reference_id": null,
          "status": "open",
          "priority": "medium",
          "last_message_at": "2026-08-04T09:20:15.153000Z",
          "last_message": {
            "id": "d6cfa37e-85b8-4dfb-88dd-82297bfc2ea7",
            "conversation": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
            "sender": {
              "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
              "full_name": "Jane Customer",
              "email": "jane@example.com",
              "avatar_url": ""
            },
            "message_type": "text",
            "body": "Is this property still available?",
            "attachment_url": "",
            "read_at": null,
            "created_at": "2026-08-04T09:20:15.153000Z",
            "updated_at": "2026-08-04T09:20:15.153000Z"
          },
          "unread_count": 0,
          "participant_state": {
            "archived_at": null,
            "last_read_at": "2026-08-04T09:20:15.153000Z"
          },
          "created_at": "2026-08-04T09:18:00.000000Z",
          "updated_at": "2026-08-04T09:20:15.153000Z"
        }
      ]
    }
  }
}

1.2 Start Conversation

POST/messages/conversations/

Auth: Required

Body:

JSON
{
  "property_id": "32bb890e-1ae3-46df-a892-25cf5a580e62",
  "context_type": "general",
  "reference_id": null,
  "priority": "medium"
}

context_type accepts general, purchase, rental, auction, or investment. reference_id is optional and links the conversation to a related workflow. priority accepts low, medium, or high.

Use this when a buyer/renter clicks "Message seller" or "Contact agent" on a property.

The backend reuses an existing conversation for the same property, buyer, seller, agent, context, and reference.

1.3 Get Conversation

GET/messages/conversations/{conversation_id}/

Auth: Required

Use this to refresh conversation metadata, participant info, related property, unread count, and archive/read state.

The response message is Conversation details retrieved successfully. and the conversation is returned under data.conversation.

1.4 Update Conversation

PATCH/messages/conversations/{conversation_id}/

Auth: Required

Body:

JSON
{
  "status": "in_progress",
  "priority": "high"
}

Allowed status values:

TEXT
open
in_progress
closed
canceled

Allowed priority values:

TEXT
low
medium
high

The response message is Conversation updated successfully. The current API allows an authenticated conversation participant to update these fields.

1.5 Load Messages

GET/messages/conversations/{conversation_id}/messages/

Auth: Required

Query params:

TEXT
page=1

Response shape:

JSON
{
  "success": true,
  "message": "Messages retrieved successfully.",
  "data": {
    "messages": {
      "count": 1,
      "next": null,
      "previous": null,
      "results": [
        {
          "id": "d6cfa37e-85b8-4dfb-88dd-82297bfc2ea7",
          "conversation": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
          "sender": {
            "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
            "full_name": "Jane Customer",
            "email": "jane@example.com",
            "avatar_url": ""
          },
          "message_type": "text",
          "body": "Is this property still available?",
          "attachment_url": "",
          "attachment_upload_id": null,
          "read_at": null,
          "created_at": "2026-08-04T09:20:15.153000Z",
          "updated_at": "2026-08-04T09:20:15.153000Z"
        }
      ]
    }
  }
}

Messages are ordered oldest first.

1.6 Send Message With REST

POST/messages/conversations/{conversation_id}/messages/

Auth: Required

Body:

JSON
{
  "message_type": "text",
  "body": "Is this property still available?",
  "attachment_upload_id": null
}

Prefer WebSocket for active chat sending. Keep this endpoint as a fallback for clients that cannot open a socket.

Allowed message_type values:

TEXT
text
image
file
system

Either body or attachment_upload_id is required. Prepare and complete a managed message upload before sending an attachment. attachment_url is generated by the API and is response-only.

1.7 Mark Read

POST/messages/conversations/{conversation_id}/read/

Auth: Required

Use this when the active chat is opened or becomes visible.

1.8 Archive

POST/messages/conversations/{conversation_id}/archive/

Auth: Required

Archive state is per user. Archiving a conversation for the current user does not archive it for the other participant.

1.9 Unarchive

POST/messages/conversations/{conversation_id}/unarchive/

Auth: Required

2. WebSocket Events

2.1 Connect

JS
const socket = new WebSocket(
  `ws://localhost:8000/ws/conversations/${conversationId}/?token=${accessToken}`
);

2.2 Send Message

Client sends:

JSON
{
  "type": "message.send",
  "message_type": "text",
  "body": "Can I schedule a visit?",
  "attachment_upload_id": null
}

Server broadcasts:

JSON
{
  "type": "message.created",
  "message": {
    "id": "d6cfa37e-85b8-4dfb-88dd-82297bfc2ea7",
    "conversation": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
    "sender": {
      "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
      "full_name": "Jane Customer",
      "email": "jane@example.com",
      "avatar_url": ""
    },
    "message_type": "text",
    "body": "Can I schedule a visit?",
    "attachment_url": "",
    "attachment_upload_id": null,
    "read_at": null,
    "created_at": "2026-08-04T09:20:15.153000Z",
    "updated_at": "2026-08-04T09:20:15.153000Z"
  }
}

The broadcast is sent to every connected participant in the conversation, including the sender.

2.3 Mark Read

Client sends:

JSON
{
  "type": "message.read"
}

Server broadcasts:

JSON
{
  "type": "message.read",
  "conversation_id": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
  "user": {
    "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
    "full_name": "Jane Customer"
  }
}

2.4 Typing Start

Client sends:

JSON
{
  "type": "typing.start"
}

Server broadcasts:

JSON
{
  "type": "typing.start",
  "conversation_id": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
  "user": {
    "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
    "full_name": "Jane Customer"
  }
}

2.5 Typing Stop

Client sends:

JSON
{
  "type": "typing.stop"
}

Server broadcasts:

JSON
{
  "type": "typing.stop",
  "conversation_id": "7b5f8f4d-9f0e-4eb1-a5e4-f91a1df75a30",
  "user": {
    "id": "b6b542cc-e8fb-4dd2-a96a-6cb1fa62a498",
    "full_name": "Jane Customer"
  }
}

2.6 Error Event

Server may send:

JSON
{
  "type": "error",
  "message": "Unsupported event type."
}

For validation failures, message may be an object/list from DRF validation.

Suggested Client State

Conversation list item:

TS
type ConversationListItem = {
  id: string;
  property: {
    id: string;
    title: string;
    slug?: string;
    address: string;
    city: string;
    area_name: string;
    price?: string;
    currency?: string;
    primary_media: null | unknown;
  };
  buyer: UserSummary;
  seller: UserSummary;
  agent: null | UserSummary;
  context_type: "general" | "purchase" | "rental" | "auction" | "investment";
  reference_id: string | null;
  status: "open" | "in_progress" | "closed" | "canceled";
  priority: "low" | "medium" | "high";
  last_message_at: string | null;
  last_message: null | Message;
  unread_count: number;
  participant_state: {
    archived_at: string | null;
    last_read_at: string | null;
  } | null;
  created_at: string;
  updated_at: string;
};

Message:

TS
type Message = {
  id: string;
  conversation: string;
  sender: UserSummary;
  message_type: "text" | "image" | "file" | "system";
  body: string;
  attachment_url: string;
  attachment_upload_id: string | null;
  read_at: string | null;
  created_at: string;
  updated_at: string;
};

User summary:

TS
type UserSummary = {
  id: string;
  full_name: string;
  email: string;
  avatar_url: string;
};

Optimistic Sending

Recommended behavior:

  1. Add a temporary message to the UI immediately.

  2. Mark it as pending.

  3. Send message.send through WebSocket.

  4. When message.created returns, replace the temporary message with the server message.

  5. If the socket closes or an error event is received, mark the temporary message as failed and allow retry.

Temporary client-only shape:

TS
type PendingMessage = Message & {
  client_id: string;
  delivery_status: "pending" | "sent" | "failed";
};

The backend does not currently accept client_id, so match optimistic messages by local order or body/timestamp until a future idempotency field is added.

Typing Indicator

Recommended behavior:

  1. Send typing.start when the user starts typing.

  2. Debounce repeat typing.start events.

  3. Send typing.stop when the input is empty, the message is sent, or the user stops typing for 1-3 seconds.

  4. Ignore typing events from the current user.

  5. Auto-hide remote typing indicators if no update arrives after a few seconds.

Read State

Recommended behavior:

  1. When a conversation is opened, call REST POST /read/.

  2. Also send WebSocket message.read if the socket is connected.

  3. Set the active conversation unread_count to 0.

  4. When a message.created event arrives for a non-active conversation, increment that conversation's unread count.

  5. When a message.read event arrives from another user, update read UI if the current screen displays read receipts.

Read state is per user and based on ConversationParticipantState.last_read_at.

Reconnect Behavior

Recommended behavior:

  1. On socket close, retry with exponential backoff.

  2. Refresh the access token before reconnecting if it may be expired.

  3. After reconnecting, reload message history with REST.

  4. De-duplicate messages by server id.

  5. Re-send only failed optimistic messages after user confirmation.

Switching Conversations

Recommended behavior:

JS
let activeSocket = null;
function openConversation(conversationId, accessToken) {
  if (activeSocket) {
    activeSocket.close();
  }
  activeSocket = new WebSocket(
    `ws://localhost:8000/ws/conversations/${conversationId}/?token=${accessToken}`
  );
  return activeSocket;
}

Only keep one active conversation socket open unless the UI needs live updates for multiple open threads.

Minimal JavaScript Example

JS
async function loadMessages(conversationId, accessToken) {
  const response = await fetch(
    `http://localhost:8000/api/v1/messages/conversations/${conversationId}/messages/`,
    {
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
      },
    }
  );
  const payload = await response.json();
  return payload.data.messages.results;
}
function connectConversation(conversationId, accessToken, handlers) {
  const socket = new WebSocket(
    `ws://localhost:8000/ws/conversations/${conversationId}/?token=${accessToken}`
  );
  socket.onopen = () => {
    handlers.onOpen?.();
  };
  socket.onmessage = (event) => {
    const payload = JSON.parse(event.data);
    if (payload.type === "message.created") {
      handlers.onMessageCreated?.(payload.message);
      return;
    }
    if (payload.type === "message.read") {
      handlers.onMessageRead?.(payload);
      return;
    }
    if (payload.type === "typing.start" || payload.type === "typing.stop") {
      handlers.onTyping?.(payload);
      return;
    }
    if (payload.type === "error") {
      handlers.onError?.(payload.message);
    }
  };
  socket.onclose = () => {
    handlers.onClose?.();
  };
  socket.onerror = () => {
    handlers.onError?.("WebSocket error.");
  };
  return socket;
}
function sendMessage(socket, body) {
  socket.send(
    JSON.stringify({
      type: "message.send",
      message_type: "text",
      body,
      attachment_upload_id: null,
    })
  );
}

Local Development Notes

Install dependencies:

BASH
./venv/Scripts/python.exe -m pip install -r requirements.txt

Run migrations:

BASH
DJANGO_SETTINGS_MODULE=core.settings.dev ./venv/Scripts/python.exe manage.py migrate

Run tests:

BASH
DJANGO_SETTINGS_MODULE=core.settings.test ./venv/Scripts/python.exe manage.py test communications

The production/dev channel layer uses Redis through:

TEXT
CHANNEL_REDIS_URL

If CHANNEL_REDIS_URL is not set, it falls back to:

TEXT
CELERY_BROKER_URL

The test settings use an in-memory channel layer, so Redis is not required for messaging tests.

Current Limitations

  • No client_id idempotency field yet for optimistic message reconciliation.

  • No delivery status beyond successful message.created broadcast.

  • Attachments must be uploaded and completed through the managed upload flow first; send the resulting attachment_upload_id. The API returns a response-only delivery URL in attachment_url.

  • Only active conversation sockets receive live messages. Conversation list live updates should poll or open additional sockets until a notification-level socket exists.