Cliente HTTP — POST JSON e fetch
Nesta página
Para enviar dados usa-se http.post(url, body, headers?). O corpo precisa ser
uma string; json.encode serializa um mapa literal em JSON antes de enviá-lo.
json.encode + http.post com 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}")
// }
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Quando a requisição precisa de um método menos comum (PATCH, OPTIONS) ou de
um tempo-limite explícito, http.fetch oferece uma API de opções mais completa:
http.fetch com método, cabeçalhos, corpo e timeout em milissegundos.
// 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::{fetch}
let resp, err = 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
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
http.fetch retorna o mesmo par resp, err que http.get e http.post, com
os campos status, status_text, ok e body no objeto de resposta.
Desafio
Use http.fetch para enviar um DELETE e verifique que resp.status é 200
ou 204 dependendo da API alvo.
Veja também