Debian Codegraph @

docs/subscribe/api.md

raw
1 # Subscribe via API
2 You can create and subscribe to a topic in the [web UI](web.md), via the [phone app](phone.md), via the [ntfy CLI](cli.md),
3 or in your own app or script by subscribing the API. This page describes how to subscribe via API. You may also want to
4 check out the page that describes how to [publish messages](../publish.md).
5
6 You can consume the subscription API as either a **[simple HTTP stream (JSON, SSE or raw)](#http-stream)**, or
7 **[via WebSockets](#websockets)**. Both are incredibly simple to use.
8
9 ## HTTP stream
10 The HTTP stream-based API relies on a simple GET request with a streaming HTTP response, i.e **you open a GET request and
11 the connection stays open forever**, sending messages back as they come in. There are three different API endpoints, which
12 only differ in the response format:
13
14 * [JSON stream](#subscribe-as-json-stream): `<topic>/json` returns a JSON stream, with one JSON message object per line
15 * [SSE stream](#subscribe-as-sse-stream): `<topic>/sse` returns messages as [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events), which
16 can be used with [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
17 * [Raw stream](#subscribe-as-raw-stream): `<topic>/raw` returns messages as raw text, with one line per message
18
19 ### Subscribe as JSON stream
20 Here are a few examples of how to consume the JSON endpoint (`<topic>/json`). For almost all languages, **this is the
21 recommended way to subscribe to a topic**. The notable exception is JavaScript, for which the
22 [SSE/EventSource stream](#subscribe-as-sse-stream) is much easier to work with.
23
24 === "Command line (curl)"
25 ```
26 $ curl -s ntfy.sh/disk-alerts/json
27 {"id":"SLiKI64DOt","time":1635528757,"event":"open","topic":"mytopic"}
28 {"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Disk full"}
29 {"id":"DGUDShMCsc","time":1635528787,"event":"keepalive","topic":"mytopic"}
30 ...
31 ```
32
33 === "ntfy CLI"
34 ```
35 $ ntfy subcribe disk-alerts
36 {"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Disk full"}
37 ...
38 ```
39
40 === "HTTP"
41 ``` http
42 GET /disk-alerts/json HTTP/1.1
43 Host: ntfy.sh
44
45 HTTP/1.1 200 OK
46 Content-Type: application/x-ndjson; charset=utf-8
47 Transfer-Encoding: chunked
48
49 {"id":"SLiKI64DOt","time":1635528757,"event":"open","topic":"mytopic"}
50 {"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Disk full"}
51 {"id":"DGUDShMCsc","time":1635528787,"event":"keepalive","topic":"mytopic"}
52 ...
53 ```
54
55 === "Go"
56 ``` go
57 resp, err := http.Get("https://ntfy.sh/disk-alerts/json")
58 if err != nil {
59 log.Fatal(err)
60 }
61 defer resp.Body.Close()
62 scanner := bufio.NewScanner(resp.Body)
63 for scanner.Scan() {
64 println(scanner.Text())
65 }
66 ```
67
68 === "Python"
69 ``` python
70 resp = requests.get("https://ntfy.sh/disk-alerts/json", stream=True)
71 for line in resp.iter_lines():
72 if line:
73 print(line)
74 ```
75
76 === "PHP"
77 ``` php-inline
78 $fp = fopen('https://ntfy.sh/disk-alerts/json', 'r');
79 if (!$fp) die('cannot open stream');
80 while (!feof($fp)) {
81 echo fgets($fp, 2048);
82 flush();
83 }
84 fclose($fp);
85 ```
86
87 ### Subscribe as SSE stream
88 Using [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) in JavaScript, you can consume
89 notifications via a [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events) stream. It's incredibly
90 easy to use. Here's what it looks like. You may also want to check out the [full example on GitHub](https://github.com/binwiederhier/ntfy/tree/main/examples/web-example-eventsource).
91
92 === "Command line (curl)"
93 ```
94 $ curl -s ntfy.sh/mytopic/sse
95 event: open
96 data: {"id":"weSj9RtNkj","time":1635528898,"event":"open","topic":"mytopic"}
97
98 data: {"id":"p0M5y6gcCY","time":1635528909,"event":"message","topic":"mytopic","message":"Hi!"}
99
100 event: keepalive
101 data: {"id":"VNxNIg5fpt","time":1635528928,"event":"keepalive","topic":"test"}
102 ...
103 ```
104
105 === "HTTP"
106 ``` http
107 GET /mytopic/sse HTTP/1.1
108 Host: ntfy.sh
109
110 HTTP/1.1 200 OK
111 Content-Type: text/event-stream; charset=utf-8
112 Transfer-Encoding: chunked
113
114 event: open
115 data: {"id":"weSj9RtNkj","time":1635528898,"event":"open","topic":"mytopic"}
116
117 data: {"id":"p0M5y6gcCY","time":1635528909,"event":"message","topic":"mytopic","message":"Hi!"}
118
119 event: keepalive
120 data: {"id":"VNxNIg5fpt","time":1635528928,"event":"keepalive","topic":"test"}
121 ...
122 ```
123
124 === "JavaScript"
125 ``` javascript
126 const eventSource = new EventSource('https://ntfy.sh/mytopic/sse');
127 eventSource.onmessage = (e) => {
128 console.log(e.data);
129 };
130 ```
131
132 ### Subscribe as raw stream
133 The `/raw` endpoint will output one line per message, and **will only include the message body**. It's useful for extremely
134 simple scripts, and doesn't include all the data. Additional fields such as [priority](../publish.md#message-priority),
135 [tags](../publish.md#tags-emojis) or [message title](../publish.md#message-title) are not included in this output
136 format. Keepalive messages are sent as empty lines.
137
138 === "Command line (curl)"
139 ```
140 $ curl -s ntfy.sh/disk-alerts/raw
141
142 Disk full
143 ...
144 ```
145
146 === "HTTP"
147 ``` http
148 GET /disk-alerts/raw HTTP/1.1
149 Host: ntfy.sh
150
151 HTTP/1.1 200 OK
152 Content-Type: text/plain; charset=utf-8
153 Transfer-Encoding: chunked
154
155 Disk full
156 ...
157 ```
158
159 === "Go"
160 ``` go
161 resp, err := http.Get("https://ntfy.sh/disk-alerts/raw")
162 if err != nil {
163 log.Fatal(err)
164 }
165 defer resp.Body.Close()
166 scanner := bufio.NewScanner(resp.Body)
167 for scanner.Scan() {
168 println(scanner.Text())
169 }
170 ```
171
172 === "Python"
173 ``` python
174 resp = requests.get("https://ntfy.sh/disk-alerts/raw", stream=True)
175 for line in resp.iter_lines():
176 if line:
177 print(line)
178 ```
179
180 === "PHP"
181 ``` php-inline
182 $fp = fopen('https://ntfy.sh/disk-alerts/raw', 'r');
183 if (!$fp) die('cannot open stream');
184 while (!feof($fp)) {
185 echo fgets($fp, 2048);
186 flush();
187 }
188 fclose($fp);
189 ```
190
191 ## WebSockets
192 You may also subscribe to topics via [WebSockets](https://en.wikipedia.org/wiki/WebSocket), which is also widely
193 supported in many languages. Most notably, WebSockets are natively supported in JavaScript. You may also want to
194 check out the [full example on GitHub](https://github.com/binwiederhier/ntfy/tree/main/examples/web-example-websocket).
195 On the command line, I recommend [websocat](https://github.com/vi/websocat), a fantastic tool similar to `socat`
196 or `curl`, but specifically for WebSockets.
197
198 The WebSockets endpoint is available at `<topic>/ws` and returns messages as JSON objects similar to the
199 [JSON stream endpoint](#subscribe-as-json-stream).
200
201 === "Command line (websocat)"
202 ```
203 $ websocat wss://ntfy.sh/mytopic/ws
204 {"id":"qRHUCCvjj8","time":1642307388,"event":"open","topic":"mytopic"}
205 {"id":"eOWoUBJ14x","time":1642307754,"event":"message","topic":"mytopic","message":"hi there"}
206 ```
207
208 === "HTTP"
209 ``` http
210 GET /disk-alerts/ws HTTP/1.1
211 Host: ntfy.sh
212 Upgrade: websocket
213 Connection: Upgrade
214
215 HTTP/1.1 101 Switching Protocols
216 Upgrade: websocket
217 Connection: Upgrade
218 ...
219 ```
220
221 === "Go"
222 ``` go
223 import "github.com/gorilla/websocket"
224 ws, _, _ := websocket.DefaultDialer.Dial("wss://ntfy.sh/mytopic/ws", nil)
225 messageType, data, err := ws.ReadMessage()
226 ...
227 ```
228
229 === "JavaScript"
230 ``` javascript
231 const socket = new WebSocket('wss://ntfy.sh/mytopic/ws');
232 socket.addEventListener('message', function (event) {
233 console.log(event.data);
234 });
235 ```
236
237 ## Advanced features
238
239 ### Poll for messages
240 You can also just poll for messages if you don't like the long-standing connection using the `poll=1`
241 query parameter. The connection will end after all available messages have been read. This parameter can be
242 combined with `since=` (defaults to `since=all`).
243
244 ```
245 curl -s "ntfy.sh/mytopic/json?poll=1"
246 ```
247
248 ### Fetch cached messages
249 Messages may be cached for a couple of hours (see [message caching](../config.md#message-cache)) to account for network
250 interruptions of subscribers. If the server has configured message caching, you can read back what you missed by using
251 the `since=` query parameter. It takes a duration (e.g. `10m` or `30s`), a Unix timestamp (e.g. `1635528757`),
252 a message ID (e.g. `nFS3knfcQ1xe`), or `all` (all cached messages).
253
254 ```
255 curl -s "ntfy.sh/mytopic/json?since=10m"
256 curl -s "ntfy.sh/mytopic/json?since=1645970742"
257 curl -s "ntfy.sh/mytopic/json?since=nFS3knfcQ1xe"
258 ```
259
260 ### Fetch latest message
261 If you only want the most recent message sent to a topic and do not have a message ID or timestamp to use with
262 `since=`, you can use `since=latest` to grab the most recent message from the cache for a particular topic.
263
264 ```
265 curl -s "ntfy.sh/mytopic/json?poll=1&since=latest"
266 ```
267
268 ### Fetch scheduled messages
269 Messages that are [scheduled to be delivered](../publish.md#scheduled-delivery) at a later date are not typically
270 returned when subscribing via the API, which makes sense, because after all, the messages have technically not been
271 delivered yet. To also return scheduled messages from the API, you can use the `scheduled=1` (alias: `sched=1`)
272 parameter (makes most sense with the `poll=1` parameter):
273
274 ```
275 curl -s "ntfy.sh/mytopic/json?poll=1&sched=1"
276 ```
277
278 ### Filter messages
279 You can filter which messages are returned based on the well-known message fields `id`, `message`, `title`, `priority` and
280 `tags`. Here's an example that only returns messages of high or urgent priority that contains the both tags
281 "zfs-error" and "error". Note that the `priority` filter is a logical OR and the `tags` filter is a logical AND.
282
283 ```
284 $ curl "ntfy.sh/alerts/json?priority=high&tags=zfs-error"
285 {"id":"0TIkJpBcxR","time":1640122627,"event":"open","topic":"alerts"}
286 {"id":"X3Uzz9O1sM","time":1640122674,"event":"message","topic":"alerts","priority":4,
287 "tags":["error", "zfs-error"], "message":"ZFS pool corruption detected"}
288 ```
289
290 Available filters (all case-insensitive):
291
292 | Filter variable | Alias | Example | Description |
293 |-----------------|---------------------------|-----------------------------------------------|-------------------------------------------------------------------------|
294 | `id` | `X-ID` | `ntfy.sh/mytopic/json?poll=1&id=pbkiz8SD7ZxG` | Only return messages that match this exact message ID |
295 | `message` | `X-Message`, `m` | `ntfy.sh/mytopic/json?message=lalala` | Only return messages that match this exact message string |
296 | `title` | `X-Title`, `t` | `ntfy.sh/mytopic/json?title=some+title` | Only return messages that match this exact title string |
297 | `priority` | `X-Priority`, `prio`, `p` | `ntfy.sh/mytopic/json?p=high,urgent` | Only return messages that match *any priority listed* (comma-separated) |
298 | `tags` | `X-Tags`, `tag`, `ta` | `ntfy.sh/mytopic/json?tags=error,alert` | Only return messages that match *all listed tags* (comma-separated) |
299
300 ### Subscribe to multiple topics
301 It's possible to subscribe to multiple topics in one HTTP call by providing a comma-separated list of topics
302 in the URL. This allows you to reduce the number of connections you have to maintain:
303
304 ```
305 $ curl -s ntfy.sh/mytopic1,mytopic2/json
306 {"id":"0OkXIryH3H","time":1637182619,"event":"open","topic":"mytopic1,mytopic2,mytopic3"}
307 {"id":"dzJJm7BCWs","time":1637182634,"event":"message","topic":"mytopic1","message":"for topic 1"}
308 {"id":"Cm02DsxUHb","time":1637182643,"event":"message","topic":"mytopic2","message":"for topic 2"}
309 ```
310
311 ### Authentication
312 Depending on whether the server is configured to support [access control](../config.md#access-control), some topics
313 may be read/write protected so that only users with the correct credentials can subscribe or publish to them.
314 To publish/subscribe to protected topics, you can:
315
316 * Use [basic auth](../publish.md#authentication), e.g. `Authorization: Basic dGVzdHVzZXI6ZmFrZXBhc3N3b3Jk`
317 * or use the [`auth` query parameter](../publish.md#query-param), e.g. `?auth=QmFzaWMgZEdWemRIVnpaWEk2Wm1GclpYQmhjM04zYjNKaw`
318
319 Please refer to the [publishing documentation](../publish.md#authentication) for additional details.
320
321 ## JSON message format
322 Both the [`/json` endpoint](#subscribe-as-json-stream) and the [`/sse` endpoint](#subscribe-as-sse-stream) return a JSON
323 format of the message. It's very straight forward:
324
325 **Message**:
326
327 | Field | Required | Type | Example | Description |
328 |---------------|----------|---------------------------------------------------------------------------------|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|
329 | `id` | ✔️ | *string* | `hwQ2YpKdmg` | Randomly chosen message identifier |
330 | `time` | ✔️ | *number* | `1635528741` | Message date time, as Unix time stamp |
331 | `expires` | (✔)️ | *number* | `1673542291` | Unix time stamp indicating when the message will be deleted, not set if `Cache: no` is sent |
332 | `event` | ✔️ | `open`, `keepalive`, `message`, `message_delete`, `message_clear`, `poll_request` | `message` | Message type, typically you'd be only interested in `message` |
333 | `topic` | ✔️ | *string* | `topic1,topic2` | Comma-separated list of topics the message is associated with; only one for all `message` events, but may be a list in `open` events |
334 | `sequence_id` | - | *string* | `my-sequence-123` | Sequence ID for [updating/deleting notifications](../publish.md#updating-deleting-notifications) |
335 | `message` | - | *string* | `Some message` | Message body; always present in `message` events |
336 | `title` | - | *string* | `Some title` | Message [title](../publish.md#message-title); if not set defaults to `ntfy.sh/<topic>` |
337 | `tags` | - | *string array* | `["tag1","tag2"]` | List of [tags](../publish.md#tags-emojis) that may or not map to emojis |
338 | `priority` | - | *1, 2, 3, 4, or 5* | `4` | Message [priority](../publish.md#message-priority) with 1=min, 3=default and 5=max |
339 | `click` | - | *URL* | `https://example.com` | Website opened when notification is [clicked](../publish.md#click-action) |
340 | `actions` | - | *JSON array* | *see [actions buttons](../publish.md#action-buttons)* | [Action buttons](../publish.md#action-buttons) that can be displayed in the notification |
341 | `attachment` | - | *JSON object* | *see below* | Details about an attachment (name, URL, size, ...) |
342
343 **Attachment** (part of the message, see [attachments](../publish.md#attachments) for details):
344
345 | Field | Required | Type | Example | Description |
346 |-----------|----------|-------------|--------------------------------|-----------------------------------------------------------------------------------------------------------|
347 | `name` | ✔️ | *string* | `attachment.jpg` | Name of the attachment, can be overridden with `X-Filename`, see [attachments](../publish.md#attachments) |
348 | `url` | ✔️ | *URL* | `https://example.com/file.jpg` | URL of the attachment |
349 | `type` | -️ | *mime type* | `image/jpeg` | Mime type of the attachment, only defined if attachment was uploaded to ntfy server |
350 | `size` | -️ | *number* | `33848` | Size of the attachment in bytes, only defined if attachment was uploaded to ntfy server |
351 | `expires` | -️ | *number* | `1635528741` | Attachment expiry date as Unix time stamp, only defined if attachment was uploaded to ntfy server |
352
353 Here's an example for each message type:
354
355 === "Notification message"
356 ``` json
357 {
358 "id": "sPs71M8A2T",
359 "time": 1643935928,
360 "expires": 1643936928,
361 "event": "message",
362 "topic": "mytopic",
363 "priority": 5,
364 "tags": [
365 "warning",
366 "skull"
367 ],
368 "click": "https://homecam.mynet.lan/incident/1234",
369 "attachment": {
370 "name": "camera.jpg",
371 "type": "image/png",
372 "size": 33848,
373 "expires": 1643946728,
374 "url": "https://ntfy.sh/file/sPs71M8A2T.png"
375 },
376 "title": "Unauthorized access detected",
377 "message": "Movement detected in the yard. You better go check"
378 }
379 ```
380
381
382 === "Notification message (minimal)"
383 ``` json
384 {
385 "id": "wze9zgqK41",
386 "time": 1638542110,
387 "expires": 1638543112,
388 "event": "message",
389 "topic": "phil_alerts",
390 "message": "Remote access to phils-laptop detected. Act right away."
391 }
392 ```
393
394 === "Open message"
395 ``` json
396 {
397 "id": "2pgIAaGrQ8",
398 "time": 1638542215,
399 "event": "open",
400 "topic": "phil_alerts"
401 }
402 ```
403
404 === "Keepalive message"
405 ``` json
406 {
407 "id": "371sevb0pD",
408 "time": 1638542275,
409 "event": "keepalive",
410 "topic": "phil_alerts"
411 }
412 ```
413
414 === "Poll request message"
415 ``` json
416 {
417 "id": "371sevb0pD",
418 "time": 1638542275,
419 "event": "poll_request",
420 "topic": "phil_alerts"
421 }
422 ```
423
424 ## List of all parameters
425 The following is a list of all parameters that can be passed **when subscribing to a message**. Parameter names are **case-insensitive**,
426 and can be passed as **HTTP headers** or **query parameters in the URL**. They are listed in the table in their canonical form.
427
428 | Parameter | Aliases (case-insensitive) | Description |
429 |-------------|----------------------------|---------------------------------------------------------------------------------|
430 | `poll` | `X-Poll`, `po` | Return cached messages and close connection |
431 | `since` | `X-Since`, `si` | Return cached messages since timestamp, duration or message ID |
432 | `scheduled` | `X-Scheduled`, `sched` | Include scheduled/delayed messages in message list |
433 | `id` | `X-ID` | Filter: Only return messages that match this exact message ID |
434 | `message` | `X-Message`, `m` | Filter: Only return messages that match this exact message string |
435 | `title` | `X-Title`, `t` | Filter: Only return messages that match this exact title string |
436 | `priority` | `X-Priority`, `prio`, `p` | Filter: Only return messages that match *any priority listed* (comma-separated) |
437 | `tags` | `X-Tags`, `tag`, `ta` | Filter: Only return messages that match *all listed tags* (comma-separated) |