Get notifications via the API

If you have an existing website or application and you would like to encourage discussion on your Discourse forum it can be helpful to display Discourse notifications inside of your application. This guide will show you how to use the Discourse API to fetch notifications for a user and how to mark them as read.

The recommended way of using the API is to have your application make back-end requests to Discourse and then pass that data to the front-end/presentation layer of your application.

Checkout the API Documentation for info on how to use the Discourse API.

Fetching notifications for a user

To get notifications via the API you can make an authenticated GET request to the /notifications endpoint. You can either specify the username you are fetching notifications for in the Api-Username header or as a query parameter: /notifications?username=<username>.

Optional query parameters

Parameter Description
username The username to fetch notifications for
filter Filter by read state: read or unread
filter_by_types Comma-separated list of notification type names to filter by (e.g. mentioned,replied)
offset Offset for pagination
limit Number of notifications to return (max 60)

Example request

curl -X GET "http://localhost:8080/notifications.json?username=blake.erickson" \ 
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \ 
-H "Api-Username: system"

This will return the following the JSON response

{
  "notifications": [
    {
      "id": 3,
      "user_id": 5,
      "external_id": null,
      "notification_type": 12,
      "read": true,
      "high_priority": false,
      "created_at": "2019-06-17T20:26:05.670Z",
      "post_number": null,
      "topic_id": null,
      "slug": null,
      "data": {
        "badge_id": 41,
        "badge_name": "First Emoji",
        "badge_slug": "first-emoji",
        "badge_title": false,
        "username": "blake"
      }
    },
    {
      "id": 2,
      "user_id": 5,
      "external_id": null,
      "notification_type": 6,
      "read": true,
      "high_priority": true,
      "created_at": "2019-06-17T20:26:04.305Z",
      "post_number": 1,
      "topic_id": 10,
      "fancy_title": "Greetings!",
      "slug": "greetings",
      "data": {
        "topic_title": "Greetings!",
        "original_post_id": 14,
        "original_post_type": 1,
        "original_username": "discobot",
        "revision_number": null,
        "display_username": "discobot"
      }
    }
  ],
  "total_rows_notifications": 2,
  "seen_notification_id": 3,
  "load_more_notifications": "/notifications?offset=60&username=blake"
}

This returns a notification array. If you are interested in only showing unread notifications you can pass the filter=unread query parameter to have the server return only unread notifications. For example:

curl -X GET "http://localhost:8080/notifications.json?username=blake.erickson&filter=unread" \ 
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \ 
-H "Api-Username: system"

You can visit this page for a listing of notification types. For example notification type: 12 maps to “granted_badge”.

Marking notifications as read

Now that you have fetched a user’s notifications you can mark them as read by sending a PUT request to /notifications/mark-read with the id of the notification in the request body and by specifying the username in the request header.

Example request

curl -X PUT "http://localhost:8080/notifications/mark-read" \ 
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: blake.erickson" \
-F "id=4"

You can also leave off the notification id and it will mark all notifications for that user as read.

This will return a simple “OK” JSON response:

{
  "success": "OK"
}
11 лайков

Привет, @blake!
Спасибо за отличную инструкцию!
У меня один вопрос: когда я получаю уведомление с типом, отличным от 6, рядом с аватаром появляется светло-голубой пузырёк. После нажатия на аватар пузырёк исчезает, но в файле notifications.json ничего не меняется. Как в notifications.js определить, какое уведомление больше не отображается в виде светло-голубого пузырька?

С уважением,
Сыюань

О, это будет полезно для работы с темами Discourse, задачами, коммитами, запросами на слияние и другими элементами GitLab.

@blake У меня тот же вопрос. Я хочу отображать счетчик значка уведомлений из Discourse на своём сайте — так пользователь сможет видеть, когда есть новые уведомления, перейти в Discourse и продолжить работу там. Однако счетчик значка в Discourse не отображает количество непрочитанных уведомлений. Если нажать на значок, счетчик исчезает, даже если непрочитанные уведомления ещё остались.

Как можно определить число в светло-голубом значке уведомлений Discourse и доступно ли оно через API?

  1. Я поставил реакцию на пост с аккаунта A, и в Notification API поступили данные об этом уведомлении. Затем, когда я поставил реакцию на тот же пост с аккаунта B, данные в Notification API не появились. Однако, когда я убрал свою реакцию с аккаунта A, данные уведомления от аккаунта B начали поступать в Notification API. После того как я снова поставил реакцию на пост с аккаунта A, данные уведомления появились в API. А когда я убрал реакцию с аккаунта B, данные уведомления от аккаунта A снова начали поступать.

    Столкнулся с этой проблемой при получении данных уведомлений.