Skip to content

Get Notification Count (Admin)

Get the count of unread chat notifications for the authenticated admin.

Endpoint

GET /v1/chat/admin/notifications/count/

Authentication

Required: Admin authentication token

Authorization: Token <admin_token>

Request

No request body required.

Response

Success (200 OK)

{
  "success": true,
  "message": "Notification count retrieved successfully",
  "data": {
    "count": 5
  }
}

No Unread Notifications

{
  "success": true,
  "message": "Notification count retrieved successfully",
  "data": {
    "count": 0
  }
}

Error (401 Unauthorized)

{
  "success": false,
  "message": "Unauthorized"
}

Error (403 Forbidden)

{
  "success": false,
  "message": "Access denied. Admin role required."
}

Response Fields

Field Type Description
count integer Number of unread notifications

Example Usage

JavaScript/Fetch

async function getNotificationCount() {
  const response = await fetch('/v1/chat/admin/notifications/count/', {
    method: 'GET',
    headers: {
      'Authorization': `Token ${adminToken}`
    }
  });

  const data = await response.json();

  if (data.success) {
    console.log('Unread notifications:', data.data.count);
    updateBadge(data.data.count);
  }
}

Axios

import axios from 'axios';

const getNotificationCount = async () => {
  try {
    const response = await axios.get('/v1/chat/admin/notifications/count/', {
      headers: {
        'Authorization': `Token ${adminToken}`
      }
    });

    return response.data.data.count;
  } catch (error) {
    console.error('Failed to get notification count:', error);
    return 0;
  }
};

cURL

curl -X GET "http://localhost:8000/v1/chat/admin/notifications/count/" \
  -H "Authorization: Token your_admin_token_here"

Usage in UI

Display Badge on Bell Icon

async function updateNotificationBadge() {
  const count = await getNotificationCount();

  const badge = document.getElementById('notification-badge');

  if (count > 0) {
    badge.textContent = count > 99 ? '99+' : count;
    badge.style.display = 'flex';
  } else {
    badge.style.display = 'none';
  }
}

// Update on page load
updateNotificationBadge();

// Update periodically
setInterval(updateNotificationBadge, 30000); // Every 30 seconds

React Component

import { useEffect, useState } from 'react';
import axios from 'axios';

function NotificationBell() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const fetchCount = async () => {
      try {
        const response = await axios.get('/v1/chat/admin/notifications/count/', {
          headers: { 'Authorization': `Token ${adminToken}` }
        });
        setCount(response.data.data.count);
      } catch (error) {
        console.error('Failed to fetch count:', error);
      }
    };

    fetchCount();
    const interval = setInterval(fetchCount, 30000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div className="notification-bell">
      <BellIcon />
      {count > 0 && (
        <span className="badge">
          {count > 99 ? '99+' : count}
        </span>
      )}
    </div>
  );
}

Real-time Updates via WebSocket

For real-time notification count updates, use the Admin WebSocket:

ws.onmessage = (event) => {
  const payload = JSON.parse(event.data);

  if (payload.type === "new_notification") {
    const count = payload.payload.count;
    updateBadge(count);
  }
};

This is more efficient than polling the REST endpoint.

Notes

  • This endpoint only counts notifications where is_read=false
  • It's faster than fetching all notifications when you only need the count
  • For real-time updates, use the WebSocket new_notification event
  • Call this endpoint on page load to initialize the badge
  • Optionally poll this endpoint every 30-60 seconds as a fallback

Typical Usage Pattern

  1. On app load: Call this endpoint to initialize notification badge
  2. WebSocket connected: Listen for new_notification events for real-time updates
  3. WebSocket disconnected: Fall back to polling this endpoint every 30 seconds
  4. User clicks notification: Mark as read, decrement badge count
  5. User clicks "Mark all as read": Set badge to 0