core:http_client
HTTP client over wasi:http (core:http_client).
An HttpClient holds what belongs to one origin: the base URL, the headers
every request carries, and the timeouts. request sends one request and
answers an HttpResponse once its headers arrive; its body is read whole
(bytes, text, json), as chunks (body), or as Server-Sent Events
(events).
Headers, trailers and the query are name-value pairs in the order given,
written as an object literal ({ accept: "text/html" }). A literal cannot
repeat a key, so a name sent more than once is written as a list of pairs
([["accept", "text/html"], ["accept", "text/plain"]]) or built with
push.
A status of 4xx or 5xx is a response, not an error. The client follows no redirect and retries nothing.
See docs/wep-2026-11-24-core-http-client.md for the design.
Synopsis
struct Item {
id: i32,
}
// RFC 6761 reserves `.invalid` never to resolve, so this request fails
// before any response.
let client = HttpClient::new("https://api.example.invalid/v1", {
headers: { accept: "application/json" },
}).unwrap();
let result = client.request("/items", {
query: { limit: "10" },
});
match result {
Ok(mut res) => {
let items = res.json::<List<Item>>();
assert res.ok() && items.is_ok();
},
Err(e) => {
assert e matches { Transport([_::Request, _]) };
},
}
Structs
pub struct ClientInit
What an HttpClient applies to every request.
headers: List<[String, String]>
connect_timeout: Option<Duration>
first_byte_timeout: Option<Duration>
between_bytes_timeout: Option<Duration>
pub struct RequestInit
One request, relative to the client's base URL.
method: Method
headers: List<[String, String]>
Appended after the client's headers; a name in both keeps both values.
query: List<[String, String]>
Percent-encoded by the client. The path itself carries no query.
body: Option<ByteSlice>
trailers: List<[String, String]>
pub struct HttpClient
The settings of one origin, from which requests are sent.
Fields are private.
pub fn new<S: AsStrSlice>(base_url: S, init: ClientInit = {}) -> Result<HttpClient, HttpError>
A client for base_url, an http or https URL with no user info,
query or fragment.
pub fn request<P: AsStrSlice>(&self, path: P, init: RequestInit = {}) -> Result<HttpResponse, HttpError> with Client
Send a request for path, which starts with / and holds no ? or
#, and answer once the response headers arrive.
pub fn request_streaming<P: AsStrSlice, effect E>(&self, path: P, init: RequestInit, write: fn mut(&StreamWritable<u8>) -> List<[String, String]> with E) -> Result<HttpResponse, HttpError> with (Client, E)
contract init.body matches { null }, "a streamed request takes its body from `write`"
request with a body write streams, called once the send has
started. The trailers it returns follow the body, after those of
init, whose body must be null.
pub struct HttpFields
A header or trailer section: name-value pairs as the host handed them over. A value is read as a view over those bytes, never copied, except where a name repeats and RFC 9110 reads its values as one.
Fields are private.
pub fn header<S: AsStrSlice>(&self, name: S) -> Result<Option<StrSlice>, HttpError>
contract !name.as_str_slice().eq_ignore_ascii_case("set-cookie"), "Set-Cookie cannot be joined: read it with `headers_all`"
The value of name, compared without regard to ASCII case: its values
joined with , where it repeats, or an error where that is not UTF-8.
pub fn header_bytes<S: AsStrSlice>(&self, name: S) -> Option<ByteSlice>
contract !name.as_str_slice().eq_ignore_ascii_case("set-cookie"), "Set-Cookie cannot be joined: read it with `headers_all`"
header, as the octets themselves.
pub fn headers_all<S: AsStrSlice>(&self, name: S) -> Result<List<StrSlice>, HttpError>
Every value of name, each a view, in the order they arrived.
pub affine struct HttpResponse
A response whose headers have arrived. Reading the body in any of its ways uses up the body, not the response, which then hands out the trailers.
status: u16
pub fn ok(&self) -> bool
Whether the status is 2xx.
pub fn headers(&self) -> &HttpFields
pub fn trailers(&self) -> &HttpFields
contract self.trailers matches { Some(_) }, "the body must be read to its end first"
The trailers that followed the body, empty where none did.
pub fn bytes(&mut self) -> Result<ByteList, HttpError> with Client
contract !self.read, "a body is read once"
The whole body.
pub fn text(&mut self) -> Result<String, HttpError> with Client
contract !self.read, "a body is read once"
The whole body, which must be UTF-8.
pub fn json<T: Deserialize>(&mut self) -> Result<T, HttpError> with Client
contract !self.read, "a body is read once"
The whole body, decoded from JSON.
pub fn body(self) -> BodyChunks
contract !self.read, "a body is read once"
The body as the chunks the host hands over.
pub fn events(self) -> EventStream
contract !self.read, "a body is read once"
The body as Server-Sent Events.
pub affine struct BodyChunks
The body of a response, chunk by chunk. A body cut short ends with an
error rather than with None.
Fields are private.
pub fn response(&self) -> &HttpResponse
The response the chunks are read from, its trailers in place once they end.
impl Iterator for BodyChunks
fn next(&mut self) -> Option<Result<ByteList, HttpError>> with Client
pub struct SseEvent
One Server-Sent Event. Each field is a view into the body as it arrived.
event: StrSlice
The event type, message where the event named none.
data: StrSlice
id: StrSlice
The last event ID the stream set, empty where it set none.
pub affine struct EventStream
The body of a response as Server-Sent Events. A body cut short, or a line
that is not UTF-8, ends with an error rather than with None.
Fields are private.
pub fn response(&self) -> &HttpResponse
The response the events are read from, its trailers in place once they end.
pub fn retry(&self) -> Option<i64>
The reconnection time in milliseconds the stream last set.
impl Iterator for EventStream
fn next(&mut self) -> Option<Result<SseEvent, HttpError>> with Client
Variants
pub variant HttpError
InvalidUrl(String)
InvalidMethod(Method)
A method the host refused as no valid token.
InvalidField(HeaderError)
A header or trailer the host refused to send.
UnsupportedOption(RequestOptionsError)
A timeout the host does not support.
Transport([Stage, ErrorCode])
NotUtf8(Utf8Error)
Json(DeserializeError)
impl Display for HttpError
fn fmt(&self, f: &mut Formatter)
Enums
pub enum Stage
Where a transport failure happened.
Request
While sending the request. Before the response headers, no part of the response was seen; a request body the host failed to send is reported once the response body ends.
ResponseBody
While the response body was read: part of it may have been handed out.
