Guides

Streaming (SSE)

Show the document to your user as it is written, instead of a spinner. The stream is server-sent events over plain HTTP.

Start a stream

Send Accept: text/event-stream when you create the document, and the response is the stream instead of the queued document. Or open GET /v1/documents/{document}/stream for a document you already created.

cURL
curl -N https://api.129.212.147.181.sslip.io/v1/documents \  -H "Authorization: Bearer $DOCGEN_API_KEY" \  -H "Docgen-Subject: wp_user:48213" \  -H "Accept: text/event-stream" \  -H "Idempotency-Key: lease-0001" \  -d '{ "session": "ses_01JBA2M8K3Q4R5S6T7V8W9X0YZ", "formats": ["pdf"] }'

Events

text/event-stream
id: 1event: document.statusdata: {"status": "queued"}id: 2event: document.statusdata: {"status": "generating"}id: 3event: document.deltadata: {"text": "<h1>RESIDENTIAL LEASE AGREEMENT</h1>\n<p>This Residential Lease Agreement is "}id: 9event: document.statusdata: {"status": "rendering"}id: 10event: document.readydata: {"id": "doc_01JB8ZQ0R7XKQ5V3M4N2P8T6WY", "status": "succeeded", "files": {…}}
  • document.status: {"status"}, as the document moves through queued → generating → rendering. generating means the text starts from empty: if writing is interrupted on our side (we restart a server), we start the document over and send generating again, so clear what you have shown when it arrives.
  • document.delta: {"text"}, the next piece of the document, as HTML. Append it.
  • document.ready: the full Document with its files. The stream ends.
  • document.failed: {"error"}, the same error object as everywhere else. The stream ends.

Exactly one of document.ready or document.failed ends every stream. Comment lines keep the connection alive while the model thinks; ignore them.

Reconnect and resume

The job runs whether or not anyone is listening, so a dropped connection loses nothing. Reconnect with the last id you saw in Last-Event-ID and the stream continues after it. A stream also closes after ten minutes; reconnect the same way.

cURL
curl -N https://api.129.212.147.181.sslip.io/v1/documents/doc_01JB8ZQ0R7XKQ5V3M4N2P8T6WY/stream \  -H "Authorization: Bearer $DOCGEN_API_KEY" \  -H "Last-Event-ID: 9"

Showing it in a browser

Your key must stay on your server, and requests from a browser are refused (secret_key_in_browser), so the browser can't call us directly. Open the stream from your server and pass the events through to your page on your own endpoint (also as server-sent events, or over a WebSocket you already have).