http
Talk to websites and web APIs: get, post, request and download. Answers come back as a map {"status", "ok", "headers", "text", "json", "url", "elapsed"}; a 404 or 500 is an answer too (check ok or status), while a missing site, refused connection, timeout or TLS problem is an error you can catch.
This library talks to websites, so it needs the TB app on your computer. The examples here show the code; run them with tb file.tb.
import http
Example
Needs the TB app on your computer, so there is no Run button here.
import http
let answer = http.get("https://example.com", {"timeout": 10})
say(answer.status, answer.ok)
say(answer.text.slice(0, 60))
let api = http.get("https://httpbin.org/json")
if api.ok {
say(api.json.slideshow.title)
}
Functions
get(url, options?)
returns mapFetch a web page or API: let r = http.get("https://example.com"), then r.status, r.ok, r.text, r.json (the parsed JSON, or nil), r.headers (names in lower case), r.elapsed (milliseconds). options is a map with any of: "headers" (map), "params" (map added to the address as ?key=value), "json" (a value sent as JSON), "timeout" (seconds, default 15), "user_agent" (default "TB/2.0"), "max_bytes" (biggest answer to accept, default 10 MB).
post(url, body?, options?)
returns mapSend data to a web API. body is text (sent as plain text) or a map/list (sent as JSON). Gives back the same kind of map as get(). options is a map with any of: "headers" (map), "params" (map added to the address as ?key=value), "json" (a value sent as JSON), "timeout" (seconds, default 15), "user_agent" (default "TB/2.0"), "max_bytes" (biggest answer to accept, default 10 MB).
request(method, url, options?)
returns mapAny kind of request: method is "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" or "OPTIONS". options may also have "body" (text, map or list). options is a map with any of: "headers" (map), "params" (map added to the address as ?key=value), "json" (a value sent as JSON), "timeout" (seconds, default 15), "user_agent" (default "TB/2.0"), "max_bytes" (biggest answer to accept, default 10 MB).
download(url, path, options?)
returns mapSave what a web address gives back into a file, and give back {"path", "bytes", "status"}. It fails (and saves nothing) if the answer isn't OK (like 404) or is bigger than the "max_bytes" option (default 100 MB). Other options as for get().
encode_params(map)
returns textTurn a map into URL query text: encode_params({"q": "a b", "n": 2}) is "q=a+b&n=2".
Values
| Name | Value | What it is |
|---|---|---|
http.USER_AGENT | "TB/2.0" | The User-Agent header TB sends unless you choose another. |