Streaming

Some APIs do not hand back a response in one piece. A chat completion arrives a token at a time, an activity feed pushes events as they happen, a log endpoint emits lines for as long as you care to listen. Waiting for the whole body defeats the point: you want each piece as it lands, and you want to start acting on it before the next one arrives.

RestClient models this with another response disposition, Stream, alongside List. A streaming endpoint yields a lazy iterator of decoded elements; you iterate it, and each step blocks until the next element has been read off the wire and parsed. The disposition is a type, selected through the endpoint's output type, exactly as List is.

How streaming fits together

A streamed body has two layers, and RestClient keeps them separate.

Framing is how the byte stream is divided into messages. Server-Sent Events (text/event-stream) separate events with a blank line; NDJSON (newline-delimited JSON) puts one record per line. RestClient supports both.

Interpretation is how each message's payload becomes a typed value. This is the same machinery that parses a buffered response. A @jsondef type is decoded identically whether it arrives whole, in an SSE event, or as an NDJSON line, and a message that can't be decoded ends the stream with a MalformedResponse holding its payload.

The framing is a property of the stream; the element type is a property of the payload. They are independent, so the same element type can appear in a buffered endpoint and a streaming one with no change. A Stream{T, F} carries the framing F as a symbol (:SSE or :NDJSON), defaulting to :SSE.

Declaring a streaming endpoint

Name Stream{T} as the output type and the endpoint streams. The element type is an ordinary @jsondef struct:

@jsondef struct DeltaText
    text::Union{String, Nothing} = nothing
end

@jsondef struct Delta
    type::String
    delta::Union{DeltaText, Nothing} = nothing
end

# SSE is the default framing
@endpoint chat(; messages) -> "messages" -> Stream{Delta}

For a newline-delimited endpoint, name the framing as the second type parameter:

@endpoint generate(; prompt) -> "api/generate" -> Stream{Token, :NDJSON}

With a Stream result type, whatever the endpoint's supertype, its requests are read incrementally, just as a ListResponse result is wrapped in a List. The Accept header is set from the framing automatically (text/event-stream for SSE, application/x-ndjson for NDJSON), so you need not set it yourself.

When one stream carries several kinds of event, make the element type abstract, with a @jsondef subtype for each kind, chosen per event by JSON.jl's @choosetype. An abstract type has no format of its own, so declare it JSON:

abstract type Event end

@jsondef struct Message <: Event
    type::String
    text::String
end

@jsondef struct Ping <: Event
    type::String
end

JSON.@choosetype Event event -> if event.type[] == "message" Message else Ping end
RestClient.dataformat(::Type{Event}) = RestClient.JSONFormat()

@endpoint events() -> "events" -> Stream{Event}

Consuming a stream

A Stream is iterable. Each iteration blocks until the next element is available, so a for loop processes elements as the server sends them:

for delta in chat(messages = msgs)
    isnothing(delta.text) || print(delta.text)
end

It works anywhere an iterator does: collect gathers the stream into a vector once it completes, and reduce folds it as it arrives:

collect(chat(messages = msgs))            # Vector{Delta}, once the stream ends
reduce(merge_delta, chat(messages = msgs)) # you supply merge_delta

Combining the elements into a final answer is up to you, since every API shapes its deltas differently.

Knowing when to stop

By default a stream ends when the connection closes, which is all the SSE specification promises. Many APIs also mark the end in band, with a sentinel value or a terminal event, and expect the client to stop there. You declare that rule by defining isstreamend for your endpoint:

# An API that feels special might decide to shove event type information into the data
RestClient.isstreamend(::ChatEndpoint, fr::SSEvent) = fr.data == codeunits("[DONE]")

# Another API might have paid more attention to WHATWG and used a dedicated event type
RestClient.isstreamend(::MessagesEndpoint, fr::SSEvent) = fr.event == "message_stop"

Each frame is checked twice: before it is decoded, with fr.data still the raw payload bytes, and after, as the stream's element. A method sees whichever its type matches, so the two above see both and stop at the raw frame, before it is decoded. One that reads a decoded field types its payload:

RestClient.isstreamend(changes::ChangesEndpoint, fr::SSEvent{<:Change}) = fr.data.time >= changes.until

Either way, the frame that ends a stream never reaches your loop. Frames to leave out, such as keep-alives or an API's monitoring events, are declared the same way with isstreamskip, and one skipped as a raw frame is never decoded:

RestClient.isstreamskip(::FeedEndpoint, fr::SSEvent) = fr.event == "heartbeat"
Warning

The endpoint type a method dispatches on must match the one @endpoint generated. The function form chat(...) creates a struct named ChatEndpoint (the function name, capitalised, with Endpoint appended), so the isstreamend method must be written on ChatEndpoint, as above. If you want a name you control, use the explicit struct form @endpoint struct MessagesEndpoint ... end and dispatch on that.

Reading SSE event types and ids

By default each element is the decoded payload, which is what most consumers want. When you need the surrounding SSE metadata — the event type an API dispatches on, or the id used for resumption — name SSEvent as the element type. Each element is then the whole event, which both destructures and exposes named fields:

@endpoint chat(; messages) -> "messages" -> Stream{SSEvent{Delta}}

for (event, delta) in chat(messages = msgs)
    event == "message_stop" && break
    isnothing(delta) || print(delta.text)
end

# or by field, with the id also available:
for ev in chat(messages = msgs)
    ev.event == "content_block_delta" && handle(ev.data)
end

SSEvent follows the WHATWG event model: event is reset for each event, while id is sticky and carries forward until the server changes it. RestClient does not reconnect on your behalf, so it never sends Last-Event-ID itself; an endpoint that wants to resume reads ev.id and supplies it on a fresh request. SSEvent is SSE-specific: NDJSON elements have no event metadata and stay the bare decoded value.

Silence and slow consumers

A stream runs for as long as the server keeps it going, and by default waits as long as it takes for each frame (TCP keepalive still notices a server that has gone). For a stream, timeout sets the longest silence allowed, which suits an API that sends heartbeats, or one you'd rather not wait on indefinitely:

chat(RequestConfig("https://api.example.com"; timeout = 300); messages = msgs)

Past it, the stream is abandoned with a TransportError whose reason is :silence. That is raised while iterating, or by the call itself when the server is silent before its response begins, so handle it around both.

The body is read off the network as it arrives, however quickly you iterate, so a consumer that falls well behind holds the backlog in memory. Iterate promptly, and close a stream you no longer need.

Cancellation

A Stream holds an open connection and a couple of background tasks, so it must be closed when you are done. Draining it to completion closes it for you. To stop early, close it; and because a Stream is a plain value, you can hand it to another task and close it from there:

stream = chat(messages = msgs)
@spawn (stop_requested() && close(stream))  # a UI button, a timeout, a supervisor
for delta in stream
    print(delta.text)
end

Closing a stream ends a blocked iteration the way break would, without raising, so cancelling needs no try~/~catch. A failure is another matter: a server that drops the connection partway, or a payload that fails to parse, raises an exception when you next iterate, so a truncated stream is never mistaken for a complete one. A stream you stop iterating and drop is eventually reclaimed by its finaliser, but closing it frees the connection straight away.

Info

Streams are never cached, as there is no complete body to store. Retries still apply, but only to the response status: a 429 is retried before the first element reaches you, as for a buffered request, and once elements flow there is nothing to retry.

Beyond SSE and NDJSON

A framing of your own, such as a length-prefixed binary protocol, is added from outside the package by defining RestClient.readframe and its companions for a new framing symbol, with no change to Stream, the transport, or cancellation. Few clients will need one; it's there for libraries built on RestClient.