既存のウェブサイトやアプリケーションで、Discourseフォーラムでの議論を促進したい場合、アプリケーション内にDiscourseの通知を表示することが役立つことがあります。このガイドでは、Discourse APIを使用してユーザーの通知を取得する方法と、それらを既読としてマークする方法を説明します。
APIを使用するための推奨される方法は、アプリケーションがDiscourseに対してバックエンドリクエストを行い、そのデータをアプリケーションのフロントエンド/プレゼンテーション層に渡すことです。
Discourse APIの使用方法については、APIドキュメントを確認してください。
ユーザーの通知の取得
API経由で通知を取得するには、/notificationsエンドポイントに対して認証されたGETリクエストを行うことができます。通知を取得するユーザー名を、Api-Usernameヘッダー、またはクエリパラメータ/notifications?username=<username>のいずれかで指定できます。
オプションのクエリパラメータ
| パラメータ | 説明 |
|---|---|
username |
通知を取得するユーザー名 |
filter |
既読ステータスでフィルタリング: read または unread |
filter_by_types |
フィルタリングする通知タイプの名前をカンマ区切りで指定 (例: mentioned,replied) |
offset |
ページネーションのオフセット |
limit |
返される通知の数 (最大60) |
リクエストの例
curl -X GET "http://localhost:8080/notifications.json?username=blake.erickson" \
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: system"
これにより、次のJSONレスポンスが返されます。
{
"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"
}
これは通知の配列を返します。未読の通知のみを表示したい場合は、クエリパラメータfilter=unreadを渡すと、サーバーが未読の通知のみを返すようにできます。例えば:
curl -X GET "http://localhost:8080/notifications.json?username=blake.erickson&filter=unread" \
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: system"
通知タイプの一覧については、こちらのページをご覧ください: notification types。例えば、通知タイプ12は「granted_badge」に対応します。
通知を既読としてマークする
ユーザーの通知を取得したら、通知のidをリクエストボディに含め、リクエストヘッダーにユーザー名を指定して/notifications/mark-readにPUTリクエストを送信することで、それらを既読としてマークできます。
リクエストの例
curl -X PUT "http://localhost:8080/notifications/mark-read" \
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: blake.erickson" \
-F "id=4"
通知IDを省略すると、そのユーザーのすべての通知が既読としてマークされます。
これはシンプルな “OK” JSONレスポンスを返します。
{
"success": "OK"
}