Saltar al contenido

Cliente HTTP — POST JSON y fetch

En esta página

Para enviar datos se usa http.post(url, body, headers?). El cuerpo debe ser una cadena; json.encode serializa un mapa literal a JSON antes de enviarlo.

json.encode + http.post con Content-Type: application/json.

03-client-post-json.zolo
Playground
// 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}")

// }

Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.

Cuando la solicitud necesita un método menos común (PATCH, OPTIONS) o un tiempo límite explícito, http.fetch ofrece una API de opciones más completa:

http.fetch con método, cabeceras, cuerpo y timeout en milisegundos.

04-client-fetch.zolo
Playground
// 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

Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.

http.fetch devuelve el mismo par resp, err que http.get y http.post, con los campos status, status_text, ok y body en el objeto de respuesta.

Desafío

Usa http.fetch para enviar un DELETE y verifica que resp.status sea 200 o 204 dependiendo de la API objetivo.

Consulta también

Buscar en Zolo

9 resultados

enespt-br