Skip to content

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())
NameMeaning
create(options: any = nil)Create a client with defaults and a cookie jar.
baseReady-to-use default client.
instanceClient struct type; use create() to initialize a usable client.

Options are dictionaries. The old http.config() struct is no longer exported.

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)”
OptionAccepted valueDefault / behavior
baseUrlstring or nilCreation only. Base for relative URLs.
bodySupported body valueRequest only. Omitted means no body.
headersDictionary with string keysMerge with defaults by header name. Values can be scalars or lists; nil disables a header.
queryDictionary with string keysMerge with client defaults and URL query parameters. Lists repeat a key; nil removes it.
cookiesDictionary with string keysCookie values; nil removes a configured override.
timeoutNon-negative integerSeconds; default 10, 0 disables the client timeout.
followRedirectsboolDefault true.
cookieJarboolDefault 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.

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.

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.

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.

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.

FieldTypeMeaning
urlstringFinal request URL, after redirects.
statusintHTTP status code.
statusTextstringStatus text such as OK.
okboolTrue for status codes from 200 through 299.
headersdict[string, any]A header value is a string or list of strings.
cookiesdict[string, string]Cookies set by this response, indexed by name.
MethodResult
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))
}