HTTP
@std/http is an outbound HTTP client. For incoming requests and route handlers, see the server guide.
import http from "@std/http"
let result = http.base.request("GET", "https://example.com")
println(result.status)println(result.body())Exports
Section titled “Exports”| Name | Meaning |
|---|---|
create(options: any = nil) | Create a client with defaults and a cookie jar. |
base | Ready-to-use default client. |
instance | Client struct type; use create() to initialize a usable client. |
Options are dictionaries. The old http.config() struct is no longer exported.
Client defaults
Section titled “Client defaults”import http from "@std/http"
let client = http.create({ baseUrl: "https://api.example.com/v1", timeout: 20, headers: {Accept: "application/json"}, query: {language: "en"}, followRedirects: true, cookieJar: true})
let result = client.request("GET", "/users", { query: {page: 2}})
println(result.url)println(result.status)This joins the base URL path with /users, producing /v1/users, and adds the configured query parameters. An absolute request URL overrides the base URL. You can also assign client.baseUrl after creation.
client.request(method, url, options = nil)
Section titled “client.request(method, url, options = nil)”| Option | Accepted value | Default / behavior |
|---|---|---|
baseUrl | string or nil | Creation only. Base for relative URLs. |
body | Supported body value | Request only. Omitted means no body. |
headers | Dictionary with string keys | Merge with defaults by header name. Values can be scalars or lists; nil disables a header. |
query | Dictionary with string keys | Merge with client defaults and URL query parameters. Lists repeat a key; nil removes it. |
cookies | Dictionary with string keys | Cookie values; nil removes a configured override. |
timeout | Non-negative integer | Seconds; default 10, 0 disables the client timeout. |
followRedirects | bool | Default true. |
cookieJar | bool | Default true; retain server cookies between calls on this client. |
Unknown option names and invalid types raise a Nubo error. Per-request settings override defaults for that call. Headers start with User-Agent: Nubo/<version>; headers: {"User-Agent": nil} suppresses it.
The examples using api.example.com below illustrate a remote API; replace that host and its paths with your service.
JSON bodies
Section titled “JSON bodies”Dictionaries, lists, and struct instances become JSON automatically when no content type is specified:
import http from "@std/http"
let result = http.base.request("POST", "https://api.example.com/users", { body: {name: "Ada", active: true}})
println(result.status)println(result.body())You can explicitly select JSON encoding. A string with Content-Type: application/json is encoded as a JSON string, rather than treated as pre-serialized JSON:
import http from "@std/http"
let result = http.base.request("POST", "https://api.example.com/messages", { headers: {"Content-Type": "application/json"}, body: {message: "Hello"}})An explicit body: nil with JSON content type sends JSON null. Without an explicit body option, no body is sent. Strings without a content type are sent as text. Supported byte bodies use application/octet-stream by default.
URL-encoded forms
Section titled “URL-encoded forms”import http from "@std/http"
let result = http.base.request("POST", "https://api.example.com/login", { headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: {username: "Ada", remember: true}})
println(result.status)List values become repeated form fields. A string body under this content type is used as already encoded form data.
Multipart forms
Section titled “Multipart forms”Set the content type and let the client generate the boundary:
import http from "@std/http"
let result = http.base.request("POST", "https://api.example.com/upload", { headers: {"Content-Type": "multipart/form-data"}, body: { description: "A text attachment", attachment: { filename: "hello.txt", contentType: "text/plain", data: "Hello, Nubo" } }})
println(result.status)A file field uses filename and data, with optional contentType. Lists can supply repeated fields. Supported objects with a zero-argument __read__() method are resolved before body encoding.
Cookies and redirects
Section titled “Cookies and redirects”Each client has its own cookie jar. Cookies received from servers are reused according to normal cookie rules, including public-suffix checks. Request-level cookie overrides apply to that request and are not written directly into the session jar.
import http from "@std/http"
let client = http.create({cookieJar: true})
let result = client.request("GET", "https://example.com", { followRedirects: false, cookies: {theme: "dark"}})
println(result.status)println(result.cookies)followRedirects: false returns the redirect response. cookieJar: false disables automatic jar use for that request; explicitly supplied cookies can still be sent.
Responses
Section titled “Responses”| Field | Type | Meaning |
|---|---|---|
url | string | Final request URL, after redirects. |
status | int | HTTP status code. |
statusText | string | Status text such as OK. |
ok | bool | True for status codes from 200 through 299. |
headers | dict[string, any] | A header value is a string or list of strings. |
cookies | dict[string, string] | Cookies set by this response, indexed by name. |
| Method | Result |
|---|---|
body() | Body text as a string. |
bytes() | Body as []byte. |
json() | Parsed JSON value. |
The body is buffered, so these methods can be called repeatedly. JSON parsing keeps representable whole numbers as integers and other numbers as floats; malformed JSON or multiple JSON values raise an error.
A 404 or 500 response does not itself throw. Check ok or status; use catch for transport, options, or parsing failures:
import http from "@std/http"
catch err { let result = http.base.request("GET", "https://example.com")
if !result.ok { println("HTTP status:", result.status) } else { println(result.body()) }}
if !isNil(err) { println(string(err))}