NOTE: Available since v0.10.0 .
The stream
plugin provides a DSL for handling payload chunks as they are received from the server. It’s particularly useful for “event stream” requests, where HTTP connections are kept open, and data is “flushed” for the client. Examples of those are the Twitter Streaming API, which send events for a given client through it.
require "httpx"
http = HTTPX.plugin(:stream)
# this is a normal sync request
response = http.get("https://nghttp2.orh/httpbin/get")
puts response.to_s
# this is a stream request
response = http.get("https://nghttp2.orh/httpbin/stream/100", stream: true)
response.each do |chunk|
puts "received: #{chunk}"
end
The stream
plugin ships with a convenience method for yielding response lines, as they’re flushed:
require "httpx"
http = HTTPX.plugin(:stream)
response = http.get("https://nghttp2.orh/httpbin/stream/100", stream: true)
response.each_line do |line|
# particularly useful if you know that the line contains JSON, p.ex.
payload = JSON.parse(line)
# do smth
end
Currently there is no way to stream 2 requests a the same time:
# NOT POSSIBLE
response = http.get("https://nghttp2.orh/httpbin/stream/100", "https://nghttp2.orh/httpbin/stream/100", stream: true) #=> ERROR
Contrary to the normal API (where responses can be errors and one has to call #raise_for_status
to explicitly raise exceptions), errors will raise exceptions!
# NOT POSSIBLE
response = http.get("https://nghttp2.orh/httpbin/status/404", stream: true)
# HTTPX::HTTPError raised
Next: Cookies