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:
http://localhost:8000/api/v1/messagesWebSocket base:
ws://localhost:8000/wsUse wss:// in production.
Auth
REST requests use the normal bearer token:
Authorization: Bearer <access_token>
Content-Type: application/jsonWebSocket connections pass the same access token as a query parameter:
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.
Recommended Frontend Flow
-
Load the conversation list with REST.
-
When the user opens a conversation, load its message history with REST.
-
Open a WebSocket for that conversation.
-
Send new messages through WebSocket.
-
Listen for
message.createdand append/update messages in the active thread. -
Send
message.readwhen the user views the conversation. -
Close the previous socket when switching conversations.
-
Reconnect the socket if the network drops.
1. REST Endpoints
1.1 List Conversations
/messages/conversations/Auth: Required
Query params:
page=1
status=open
archived=false
unread=true
property_id=<uuid>
q=search textq and search are accepted as aliases. status accepts open, in_progress, closed, or canceled.
Response shape:
{
"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
/messages/conversations/Auth: Required
Body:
{
"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
/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
/messages/conversations/{conversation_id}/Auth: Required
Body:
{
"status": "in_progress",
"priority": "high"
}Allowed status values:
open
in_progress
closed
canceledAllowed priority values:
low
medium
highThe response message is Conversation updated successfully. The current API allows an authenticated conversation participant to update these fields.
1.5 Load Messages
/messages/conversations/{conversation_id}/messages/Auth: Required
Query params:
page=1Response shape:
{
"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
/messages/conversations/{conversation_id}/messages/Auth: Required
Body:
{
"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
image
file
systemEither 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
/messages/conversations/{conversation_id}/read/Auth: Required
Use this when the active chat is opened or becomes visible.
1.8 Archive
/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
/messages/conversations/{conversation_id}/unarchive/Auth: Required
2. WebSocket Events
2.1 Connect
const socket = new WebSocket(
`ws://localhost:8000/ws/conversations/${conversationId}/?token=${accessToken}`
);2.2 Send Message
Client sends:
{
"type": "message.send",
"message_type": "text",
"body": "Can I schedule a visit?",
"attachment_upload_id": null
}Server broadcasts:
{
"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:
{
"type": "message.read"
}Server broadcasts:
{
"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:
{
"type": "typing.start"
}Server broadcasts:
{
"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:
{
"type": "typing.stop"
}Server broadcasts:
{
"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:
{
"type": "error",
"message": "Unsupported event type."
}For validation failures, message may be an object/list from DRF validation.
Suggested Client State
Conversation list item:
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:
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:
type UserSummary = {
id: string;
full_name: string;
email: string;
avatar_url: string;
};Optimistic Sending
Recommended behavior:
-
Add a temporary message to the UI immediately.
-
Mark it as
pending. -
Send
message.sendthrough WebSocket. -
When
message.createdreturns, replace the temporary message with the server message. -
If the socket closes or an error event is received, mark the temporary message as failed and allow retry.
Temporary client-only shape:
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:
-
Send
typing.startwhen the user starts typing. -
Debounce repeat
typing.startevents. -
Send
typing.stopwhen the input is empty, the message is sent, or the user stops typing for 1-3 seconds. -
Ignore typing events from the current user.
-
Auto-hide remote typing indicators if no update arrives after a few seconds.
Read State
Recommended behavior:
-
When a conversation is opened, call REST
POST /read/. -
Also send WebSocket
message.readif the socket is connected. -
Set the active conversation
unread_countto0. -
When a
message.createdevent arrives for a non-active conversation, increment that conversation's unread count. -
When a
message.readevent 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:
-
On socket close, retry with exponential backoff.
-
Refresh the access token before reconnecting if it may be expired.
-
After reconnecting, reload message history with REST.
-
De-duplicate messages by server
id. -
Re-send only failed optimistic messages after user confirmation.
Switching Conversations
Recommended behavior:
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
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:
./venv/Scripts/python.exe -m pip install -r requirements.txtRun migrations:
DJANGO_SETTINGS_MODULE=core.settings.dev ./venv/Scripts/python.exe manage.py migrateRun tests:
DJANGO_SETTINGS_MODULE=core.settings.test ./venv/Scripts/python.exe manage.py test communicationsThe production/dev channel layer uses Redis through:
CHANNEL_REDIS_URLIf CHANNEL_REDIS_URL is not set, it falls back to:
CELERY_BROKER_URLThe test settings use an in-memory channel layer, so Redis is not required for messaging tests.
Current Limitations
-
No
client_ididempotency field yet for optimistic message reconciliation. -
No delivery status beyond successful
message.createdbroadcast. -
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 inattachment_url. -
Only active conversation sockets receive live messages. Conversation list live updates should poll or open additional sockets until a notification-level socket exists.