HTTP Requests
Everything on this page needs Kamoji firmware 0.3.0 or later.
On older firmware the http table does not exist, so set
"min_firmware": "0.3.0" in a mini app that uses it.
A Kamoji Mini App can call web APIs: fetch the weather, a price, a value from your Home Assistant, or send an event to your own server. Requests never block your mini app: you pass a callback, Kamoji runs the request in the background and calls your callback with the answer.
HTTP needs Kamoji on Wi-Fi. In most cars Kamoji has no Wi-Fi, so HTTP is
for mini apps used at home, in the garage, or in a car with a hotspot Kamoji
joins. Always show something sensible when a request fails with no_network.
Manifest
Declare the permission net.http, and list the hosts your mini app talks to:
"permissions": ["net.http"],
"http": { "hosts": ["api.open-meteo.com", "*.example.org"] }
| Field | Meaning |
|---|---|
net.http in permissions | Required. Without it, the global http is nil |
http.hosts | Optional. The hosts the mini app may call. Without it, any host |
The Mini Apps store tags a mini app with net.http as HTTP and Wi-Fi
automatically (see Feature tags).
Rules for http.hosts:
"api.example.com"allows exactly that host."*.example.org"allows every subdomain ofexample.org, at any depth (a.example.org,a.b.example.org), but notexample.orgitself: list both if you need both.- Host names only: no scheme, port or path. Upper and lower case are the same.
"*"and wide wildcards such as"*.com"are refused.- At most 16 entries. An invalid entry is skipped, with a warning in the log.
"hosts": []allows no host at all.- Entries may use
{{ }}with your settings, such as"{{param.ha_host}}", so a user can point the mini app at their own server.
Listing your hosts is good practice even though it is optional: it tells users and reviewers where your mini app sends data, and it stops a mistake in a URL from reaching anywhere else.
Lua API
id = http.request(opts, callback)
id = http.get(url, [opts], callback)
id = http.post(url, body, [opts], callback)
ok = http.cancel(id)
opts key | Type | Meaning |
|---|---|---|
method | string | "GET" (the default), "POST", "PUT", "PATCH" or "DELETE", in upper case |
url | string | Required for http.request. https://host[:port]/path?query, or http://… |
headers | table | Request headers, name to value: { Authorization = "Bearer …", Accept = "application/json" }. Names and values are strings |
body | string | The request body. Not allowed with GET. Use json.encode(t) for a table |
timeout_ms | integer | How long to wait for the whole answer: default 10000, limited to 1000–15000 |
http.getandhttp.postsetmethod,url(andbody) for you;optscan be left out:http.get(url, function(res) … end).- All three return the request's id, a number.
http.cancel(id)returnstruewhen the request was still running; its callback then runs witherror = "cancelled". Otherwise it returnsfalse.- Misuse raises a Lua error right away: a
urlthat is not a string, an unknown method, a body onGET, a body that is not a string, atimeout_msthat is not a whole number, more than 8 headers, a header name or value that is not a string or has bad characters, headers over 2 KB together, or one of the headers Kamoji sets itself (below).
The callback
The callback runs exactly once for every request, on Kamoji's main loop
like any other handler (same 200 ms
CPU limit), and never inside http.request itself: even a request refused at
once, for example with no_network, gets its callback a moment later. All
bindings are refreshed right after it.
The one exception: when your mini app leaves the screen (the user switches mode, a setting changes, the mini app is updated), its unfinished requests are dropped and their callbacks never run.
The callback gets one table, res:
| Key | Meaning |
|---|---|
res.ok | true when there was no error and the status is 200–299 |
res.status | The HTTP status (a number), or 0 when no answer arrived |
res.body | The response body as a string (may be ""); nil when res.error is set |
res.headers | Some response headers, with lower-case names (below); {} when none |
res.error | nil, or a short string (below) |
An answer with a non-2xx status is not an error: res.error is nil,
res.ok is false, res.status is for example 404, and res.body holds
what the server said.
The response headers passed on are content-type, content-length, etag,
last-modified, location, retry-after, date and cache-control, each
cut at 256 bytes. Others, such as set-cookie, are not.
Errors
res.error | When |
|---|---|
no_network | Kamoji is not connected to Wi-Fi |
bad_url | Not http:// or https:// followed by a host; a user:password@ in the URL; an IPv6 address; spaces or characters outside ASCII (encode them, e.g. %20); longer than 1024 bytes |
host_not_allowed | The host is not in http.hosts, or is an address mini apps may never reach (below) |
dns | The host name could not be found |
connect | The connection was refused, reset, or dropped before the whole answer arrived |
tls | HTTPS failed: the certificate is not trusted, expired or for another name, or the handshake failed |
timeout | No complete answer within timeout_ms |
too_large | A request body over 4 KB, or a response body over 16 KB (nothing of the response is kept) |
busy | Two requests of this mini app are already running |
rate_limited | More than 30 requests started in the last 60 seconds |
cancelled | http.cancel(id) |
no_memory | Kamoji could not get the memory for the request |
Limits
| What | Limit |
|---|---|
| Requests running at once | 2 per mini app (a third gets busy) |
| Request rate | 30 started in any 60 seconds (more get rate_limited). The count starts again each time the mini app opens |
| Request body | 4 KB |
| Response body | 16 KB |
| Headers you set | 8; a name up to 64 bytes, a value up to 1024, all together up to 2048 |
| URL | 1024 bytes |
| Timeout | 10 s by default, 1 to 15 s |
How requests behave
- Foreground only. Only the mini app on screen has
http, and its requests stop when it leaves. Poll with a timer while it is on screen; nothing runs in the background. - HTTPS certificates are checked against Kamoji's built-in list of public certificate authorities (the same it uses for its firmware updates). A server with a self-signed or private certificate can't be used over HTTPS.
- Plain
http://works but is discouraged: anyone on the network path can read and change it. Use it only for devices on your own network, such as Home Assistant on the LAN. - Redirects are not followed. A
301,302,307or308comes back asres.status, with the target inres.headers.location. Request that URL yourself if you want to;http.hostsapplies to it as well. - Headers Kamoji sets. Every request carries
User-Agent: Kamoji/<firmware version> (mini-app <id>). You can't setUser-Agent,Host,Content-Length,Connection,Transfer-Encoding,TE,Upgrade,Keep-Alive,Expect,Traileror anyProxy-header. A body without aContent-Typeheader is sent asapplication/jsonwhen it starts with{or[, and astext/plain; charset=utf-8otherwise. - No cookies, no compression, and a new connection for every request: an HTTPS request takes some hundreds of milliseconds more than the server needs.
- Blocked addresses. A mini app can't reach Kamoji itself (
127.0.0.0/8, Kamoji's own Wi-Fi and hotspot addresses, also through a host name that points there),0.0.0.0/8, or multicast and broadcast addresses: those givehost_not_allowed. Private networks are allowed (192.168.x.x,10.x.x.x,172.16.x.x–172.31.x.x), so a mini app can talk to a server on the user's own network. - The timeout covers connecting, sending and receiving. Finding the host name can take as long as the network's DNS allows.
Keys and privacy
- Never put an API key or password in a URL, and never in your mini app's
files. Make it a
secretsetting and send it in a header, such asAuthorization. A secret stays on Kamoji and is never shown again in the Kamoji app. - Kamoji's log shows only the method, host, status, size and duration of each request: never the path, query string, headers or bodies.
- Only send what your mini app needs, and say in its description which services it talks to.
Examples
Outdoor temperature
Folder weather-now. The temperature at a place from
Open-Meteo (free, no key), refreshed every 15
minutes and on a tap of the top.
weather-now/manifest.json
{
"id": "weather-now",
"name": "Weather Now",
"version": "1.0.0",
"author": "Your Name",
"api_version": 1,
"min_firmware": "0.3.0",
"permissions": ["net.http", "touch"],
"http": { "hosts": ["api.open-meteo.com"] },
"params": [
{ "key": "lat", "type": "number", "label": "Latitude", "default": 1.29, "min": -90, "max": 90, "step": 0.01 },
{ "key": "lon", "type": "number", "label": "Longitude", "default": 103.85, "min": -180, "max": 180, "step": 0.01 },
{ "key": "label", "type": "string", "label": "Place", "default": "Singapore" }
]
}
weather-now/main.lua
-- Weather Now: the current temperature from api.open-meteo.com.
state.temp, state.note = nil, "Loading..."
local function refresh()
local url = fmt("https://api.open-meteo.com/v1/forecast?latitude=%.2f&longitude=%.2f¤t=temperature_2m",
param.lat, param.lon)
http.get(url, { timeout_ms = 8000 }, function(res)
if res.error == "no_network" then state.note = "Needs Wi-Fi" return end
if not res.ok then state.note = res.error or ("HTTP " .. res.status) return end
local doc = json.decode(res.body)
local t = doc and doc.current and doc.current.temperature_2m
if t then state.temp, state.note = t, "" else state.note = "No data" end
end)
end
refresh()
kamoji.every(15 * 60 * 1000, refresh)
function on_top_tap() refresh() end
weather-now/layout.json
{
"widgets": [
{ "type": "label", "font": "medium", "align": "center", "y": -60, "color": "grey",
"text": "{{ param.label }}" },
{ "type": "label", "font": "huge", "align": "center",
"text": "{{ state.temp and fmt('%.0f°', state.temp) or '--' }}" },
{ "type": "label", "font": "small", "align": "center", "y": 66, "color": "orange",
"text": "{{ state.note }}" }
]
}
POST with a key
-- permissions: "net.http", "events.drive"; params: { "key": "token", "type": "secret", "label": "API token" }
function on_bump(m)
http.post("https://api.example.com/v1/events", json.encode({ kind = "bump", g = m / 9.81 }),
{ headers = { Authorization = "Bearer " .. (param.token or "") } },
function(res) state.sent = res.ok end)
end
Home Assistant on your network
"permissions": ["net.http"],
"http": { "hosts": ["{{param.ha_host}}"] },
"params": [
{ "key": "ha_host", "type": "string", "label": "Home Assistant host", "default": "192.168.1.10" },
{ "key": "ha_token", "type": "secret", "label": "Long-lived access token" }
]
local function refresh()
http.get("http://" .. param.ha_host .. ":8123/api/states/sensor.outdoor_temperature",
{ headers = { Authorization = "Bearer " .. (param.ha_token or "") } },
function(res)
local doc = res.ok and json.decode(res.body)
if doc then state.t = doc.state end
end)
end
refresh()
kamoji.every(60000, refresh)
For data pushed to Kamoji rather than polled, see MQTT and Data.