Http

Send HTTP requests and decode common response bodies.

Requests are built and read with the shared roc-lang/http Request and Response types. This module adds the hosted effects plus JSON and UTF-8 conveniences.

An app that names Request or Response declares the http package in its own header, beside the platform:

app [Model, program] {
    rr: platform "../../platform/main.roc",
    http: "https://github.com/roc-lang/http/releases/download/1.0.0/6ZUwqYhCS8PU9Mo6MF7oV82ET2o7KYb57CLKDq4cq4sS.tar.zst",
}

import rr.Http
import http.Request

Http.Client.get! and Http.Client.get_utf8! take a URL and return decoded data, so an app that uses only those needs no package dependency of its own.

Http.Client.send! waits, so it belongs inside Task.spawn!:

update! = |model, input, io| {
    if input.devices.key_pressed(KeyR) {
        http = io.http()
        Task.spawn!(
            input,
            || match http.get_utf8!("http://127.0.0.1:8000/data.json") {
                Ok(body) => Loaded(body)
                Err(InvalidUrl(_)) => Failed("that is not a URL this platform will fetch")
                Err(HttpErr(Timeout)) => Failed("the request timed out")
                Err(HttpErr(_)) => Failed("the request failed at the network layer")
                Err(BadBody(_)) => Failed("the reply was not valid UTF-8")
                Err(_) => Failed("the request failed")
            },
        )
    }
    Ok(model)
}

send! is legal in init!, where it blocks startup, and in tasks, where it parks the task; it is refused in update! and render!.

Up to three redirects are followed, and the Response is the one at the end of that chain.

Every send defaults to a thirty-second deadline and an eight-MiB response limit. Use send_with!, send_json_with!, get_utf8_with!, or get_with! to override either field in Config.

The body limit is measured after decompression. A response over the limit fails with HttpErr(ResponseTooLarge). A requested limit above 64 MiB is refused with HttpErr(ResponseLimitUnsupported) before any network work.

An HTTP status is not an error. A 404 or a 503 arrives as Ok(response) with that status. Only a request that gets no complete response is HttpErr.

get! and send_json! infer the JSON type from their call site. Add a type annotation when the expected decoded or encoded type is ambiguous.

HTTPS verifies peers with the operating system's certificate store. Custom certificate authorities and disabling verification are not supported.

with_json_body : Request, _ -> Try(Request, [JsonErr(_)])

Encode a value as JSON and set it as the request body.

This uses Roc's builtin JSON encoder, so the value's type determines the encoder through static dispatch. A Content-Type: application/json header is added.

decode_json_response : Response -> Try(_, [BadBody(Str), JsonErr(_)])

Decode a response body as JSON.

This uses Roc's builtin JSON parser, so the expected result type determines the parser through static dispatch.

TransportErr : [Busy, Timeout, NetworkError, MalformedResponse, ResponseLimitUnsupported, ResponseTooLarge, Unavailable, Other(List(U8))]

Why the exchange did not produce an HTTP response.

An HTTP status is never one of these: a 404 or a 503 is an Ok response.

Timeout is the deadline expiring before the exchange finished. NetworkError is a connection that could not be made or did not survive the exchange -- a refused port, a dropped socket, an unreachable host. MalformedResponse is a reply that arrived but was not a well-formed HTTP response. ResponseTooLarge means the decoded response exceeded the request's byte limit. ResponseLimitUnsupported means the requested limit exceeds the supported 64 MiB per-response maximum. Busy means the host could not reserve room in its shared response budget. It made no network request, and the application may try again after one finishes. Unavailable means the HTTP runtime has stopped. Other carries a UTF-8 description of remaining failures.

Config

:= {
    timeout_ms : U64 ?? 30_000,
    max_response_bytes : U64 ?? 8 * 1024 * 1024,
}

Per-send props with defaults of 30 seconds and 8 MiB.

timeout_ms covers connection, request, and the complete response. A request's own TimeoutMilliseconds overrides it. Zero disables the deadline in either place.

max_response_bytes caps the decompressed response body. A zero limit accepts only an empty body.

Client

Http.Client :: # (opaque)

Opaque HTTP authority supplied by App.Io, scoped by the app's declared HttpOrigin entries.

for_host : Authority -> Client

Private platform construction; no application can manufacture the argument.

send! : Client, Request => Try(Response, [PermissionDenied, InvalidUrl(ParseErr), HttpErr(TransportErr)])

Validate and send an HTTP request under default_config.

The request URI must be an absolute HTTP or HTTPS URL accepted by Url. An invalid URL returns InvalidUrl before any host effect occurs. Fragments are removed, because they are client-side identifiers and are not sent.

The method must be one of the nine RFC methods. QUERY and any Unknown(ext) method fail as HttpErr(Other(...)) naming the method, also before any host effect occurs: the host's method type has no representation for either, and reporting it as Other keeps an app's exhaustive match over TransportErr from breaking over a request no host could send.

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

request = Request.from_method(GET).with_uri("https://www.roc-lang.org")
response = io.http().send!(request)?
send_with! : Client, Config, Request => Try(Response, [PermissionDenied, InvalidUrl(ParseErr), HttpErr(TransportErr)])

Validate and send an HTTP request under explicit limits.

The same validation, the same phases, and the same outcomes as send!; only the deadline and the body cap differ.

response = io.http().send_with!({ timeout_ms: 2_000 }, request)?

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

send_json! : Client, Request, _ => Try(Response, [PermissionDenied, JsonErr(_), InvalidUrl(ParseErr), HttpErr(TransportErr)])

Encode a value as JSON, attach it to the request body, and send it.

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

send_json_with! : Client, Config, { request : Request, value : _ } => Try(Response, [PermissionDenied, JsonErr(_), InvalidUrl(ParseErr), HttpErr(TransportErr)])

As send_json! with explicit limits.

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

get_utf8! : Client, Url => Try(Str, [PermissionDenied, BadBody(Str), InvalidUrl(ParseErr), HttpErr(TransportErr)])

Perform an HTTP GET and decode the response body as a UTF-8 Str.

The argument is a validated Url. Quoted literals work through Url.from_quote, so a URL written out in the source is checked at compile time; a string built at runtime goes through Url.parse.

A body that is not valid UTF-8 returns BadBody(Str). That is this function's own decoding failure, and is not the transport's MalformedResponse: the reply arrived and was a well-formed HTTP response, it just is not text. The status is not inspected, so an error page comes back as the Str the server sent.

hello_str = io.http().get_utf8!("http://localhost:8000")?

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

get_utf8_with! : Client, Config, Url => Try(Str, [PermissionDenied, BadBody(Str), InvalidUrl(ParseErr), HttpErr(TransportErr)])

As get_utf8! with explicit limits.

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

get! : Client, Url => Try(_, [PermissionDenied, BadBody(Str), InvalidUrl(ParseErr), HttpErr(TransportErr), JsonErr(_)])

Perform an HTTP GET and decode the response body as JSON.

The expected result type selects the parser through static dispatch. The status is not inspected, so a JSON error page decodes if it happens to fit the expected shape. Same phases as send!.

payload : Try({ foo : Str }, _)
payload = io.http().get!("http://localhost:8000")

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.

get_with! : Client, Config, Url => Try(_, [PermissionDenied, BadBody(Str), InvalidUrl(ParseErr), HttpErr(TransportErr), JsonErr(_)])

As get! with explicit limits.

Legal in init!, where it blocks startup, and in tasks, where it parks the task; refused in update! and render!.