http & fetch modules
Make outbound requests through the proxy. Keep payloads small and handle timeouts.
Timeouts are short (~5s). Prefer JSON APIs.
Overview
Two ways to call remote APIs: http helpers for convenience, or fetch() for a familiar minimal wrapper. Both return status, headers (limited), and body text/JSON.
Avoid large responses or binary data. Redirects may be blocked.
API
http.get(url),http.post(url, body?),http.json(url),http.form(url, data).- Responses:
{ status, text, json }wherejsonis parsed orundefined. fetch(url, options?)returns{ status, text, json }similar tohttp.
Patterns
- Check
statusbefore readingjson. - Guard against missing fields:
res && res.json && res.json.foo. - Keep bodies small; prefer GET for quick lookups.
Examples
javascript
const http = use("http");
function main() { const res = http.json("https://api.breakingbadquotes.xyz/v1/quotes"); const quote = res && res.json && res.json[0] ? res.json[0] : null; ctx.reply(quote ? '"' + quote.quote + '" — ' + quote.author : "(no data)");}javascript
const fetch = use("fetch");
function main() { const res = fetch("https://httpbin.org/status/201"); ctx.reply("Status: " + res.status);}