HTTP Client — POST JSON and fetch
To send data, use http.post(url, body, headers?). The body must be a string;
json.encode serializes a map literal to JSON before sending it.
json.encode + http.post with Content-Type: application/json.
// Feature: HTTP client — POST with JSON body
// Syntax: `http.post(url, body_str, headers?)`
// When to use: send data to create resources, webhooks, HTTP RPC.
//
// SKIP: live network call disabled — runs only in environments with
// outbound HTTP access. The shape below documents the request.
use std::http
use std::json
let payload = #{
name: "Zolo",
version: "0.1.0",
tags: ["lang", "scriptable"],
}
// `json.encode` serializes a map literal into a JSON string.
let body = json.encode(payload)
print("body: {body}")
// let resp, err = http.post(
// "http://httpbin.org/post",
// body,
// #{"Content-Type": "application/json"},
// )
// if resp != nil {
// print("status: {resp.status}") // 200
// print("ok? {resp.ok}") // true
// } else {
// print("failed: {err}")
// }
Requires the Zolo CLI/host — open in the playground or run locally.
When the request needs a less common method (PATCH, OPTIONS) or an explicit
timeout, http.fetch offers a more complete options API:
http.fetch with method, headers, body and timeout in milliseconds.
// Feature: HTTP client — `http.fetch` (`fetch`-style API)
// Syntax: `http.fetch(url, #{method, headers, body, timeout})`
// When to use: when you need an arbitrary method (PATCH, OPTIONS) or
// a custom timeout in a single call.
use std::http
let resp, err = http.fetch("http://httpbin.org/anything", #{
method: "PATCH",
headers: #{"X-Trace": "demo"},
body: "ping",
timeout: 5000, // ms
})
if resp != nil {
print("status: {resp.status}")
print("status_text: {resp.status_text}")
} else {
print("failed: {err}")
}
// expected when online: status: 200 / status_text: OK
Requires the Zolo CLI/host — open in the playground or run locally.
http.fetch returns the same resp, err pair as http.get and http.post, with
the fields status, status_text, ok and body in the response object.
Challenge
Use http.fetch to send a DELETE and verify that resp.status is 200
or 204 depending on the target API.
See also