Skip to main content

Scripted API reference

How to write, test and publish a pack is on Scripted API. This page lists what a pack and its callers can use.

Requests​

{METHOD} https://sapi.blazium.online/v1/{game_uid}/{logic}
{METHOD} https://sapi.blazium.online/v1/{game_uid}/{logic}/{action}

The optional {action} (it can have slashes, like custom/craft) is what comes after the logic name. The logic reads it as req.action, and it is part of what a signed request and an Idempotency-Key cover. The ready-made features use it.

Inside a Discord activity the same path is under https://{applicationId}.discordsays.com/.proxy/blazium/sapi. The request body is at most 64 KiB. A JSON body is decoded into req.body. Any other body is in req.raw.

HeaderMeaning
Authorization: Bearer <token>A scoped token for this game and the sapi audience, requested for the signed-in player. Required by auth = "user". A login session token is not accepted, and a token for another game is refused. See Tokens.
X-Sapi-KeyA game server key. Runs any logic as the service caller.
X-Sapi-UserWith X-Sapi-Key, the player id the call acts for (at most 64 characters).
X-Sapi-Timestamp, X-Sapi-Nonce, X-Sapi-SignatureA signed request.
X-Blazium-ChannelRelease channel. ?channel= works too. Default stable.
Idempotency-KeyReplays the first answer for the same game, logic, caller and key for 24 hours.

Every answer carries X-Request-Id and X-Blazium-Server-Time, the server clock in Unix seconds. A replayed answer adds Idempotent-Replayed: true. 429 and most 503 answers carry Retry-After in seconds.

Browsers may call from the origins listed in the game's settings. Other origins get no Access-Control-Allow-Origin header. The web player and Discord proxy are same-origin and need no entry.

GET /v1/{game_uid}/_config returns the public remote config values for a channel as { "ok": true, "channel": "stable", "config": { } }. It needs no sign-in and is cached for 30 seconds.

Signed requests​

Logic with auth = "signed" names a secret: signed = { secret = "shop_hook" }. Store that secret for every channel. The caller sends:

HeaderValue
X-Sapi-TimestampUnix seconds, within 5 minutes of now
X-Sapi-Nonce8 to 128 characters, never reused
X-Sapi-SignatureLowercase hex HMAC-SHA256 of the string below, keyed with the secret
{timestamp}\n{nonce}\n{METHOD}\n/v1/{game_uid}/{logic}\n{body}

The path has no query string. A repeated nonce is refused.

Logic table​

FieldTypeMeaning
handlerfunctionRequired. Called with the request; returns the reply.
authstringanonymous, user (default), service or signed.
methodslistAny of GET, POST, PUT, PATCH, DELETE. Default GET and POST.
datatable{ read = { ... }, write = { ... } } with global, channel and user. Write implies read.
useslistboards, secrets, progress, items, http, webhook, lobby.
ratetable{ per_user = 30, per_ip = 0, window = 60 }. Zero means no extra limit. Window 1 to 86400 seconds.
scheduletable{ cron = "*/15 * * * *", channel = "stable" }. Five-field cron in UTC.
httptable{ allow = { "api.example.com", "*.example.com" } }. Required by uses http or webhook.
signedtable{ secret = "name" }. Required by auth = "signed".
descriptionstringShown in the pack list.

An unknown field, scope, use or method fails validation.

The request​

FieldMeaning
req.method, req.logic, req.action, req.game, req.channel, req.request_id, req.ipThe call.
req.calleranonymous, user, service, signed, schedule, admin or test.
req.planfree, premium or business.
req.query, req.headersStrings. Header names are lowercase.
req.body, req.rawDecoded JSON and the raw text.
req.user{ id, username, avatar_url, owns_game } for a signed-in player, or nil.

The reply​

A returned table or value becomes a 200 JSON body. A table with a numeric status is a full reply: { status = 201, headers = { ["x-thing"] = "1" }, body = { ... } }. A string body is sent as text. Returning nothing sends 204.

Data​

data.global, data.channel and data.user each have:

MethodMeaning
get(key)The value, or nil.
get_versioned(key)The value and its version number.
get_many(keys)Up to 100 keys at once, as a table.
set(key, value, { ttl = seconds, sync = true })Store a JSON value. ttl up to 400 days.
delete(key)Remove a key.
incr(key, delta)Add to a number (default 1) and return it.
cas(key, version, value)Set only if the version still matches; returns whether it did.
list({ prefix, after, limit })Rows of { key, value } in key order, and the key to continue after.

Keys are 1 to 128 characters of letters, digits and _ - . : /. data.user("id") and data.channel("beta") open another player's or channel's scope, for service calls and schedules only.

Leaderboards​

board(name, { channel = "beta" }) needs "boards" in uses. Without channel it uses the caller's channel.

MethodMeaning
submit(score, { user, mode })Record a score. mode is best (default), lowest, latest or sum. user is for service calls.
top(n, { offset, ascending })Ranked { rank, user, score } entries.
rank(user)One entry, or nil.
around(user, n)Entries around a player.
count()Number of entries.
reset()Clear the board. Schedules and service calls only.

Platform​

FunctionNeedsMeaning
secrets.get(name)secretsThe value for the channel, or for every channel. Never logged.
config.get(name, default)A remote config value.
progress.unlock(slug, { user })progressUnlock an achievement as the scripted_api writer.
progress.stat(slug, value, { user, mode })progressmode is set, add, max or min.
progress.event(name, fields, { user })progressA funnel event. Fields up to 4 KiB.
items.grant(item, quantity, { user })itemsGive 1 to 1000 of an item definition.
items.list({ user })itemsThe player's items.
webhook.send(url, body, { secret, headers })webhookPOST to an allowed host. secret signs it.
api.http(request)httpAn HTTPS call to an allowed host. Returns { ok, status, body, headers, json, error }.
api.call(logic, body, { method, query })Run another logic in the pack, nested up to 4 deep. logic can be "logic/action".
lobby.list(), lobby.get(id)lobbyOpen lobbies of the game, and one lobby with its peers, public data and tags.
lobby.broadcast(id, event, data), lobby.send_user(user, event, data)lobbySend an event to a lobby or to one player. Players see it as sapi.<event>.
lobby.kick(id, user, { ban_seconds }), lobby.set_data(id, key, value)lobbyRemove a player, or change one key of the lobby's public data (32 keys of 2 KiB).
lobby.call(id, name, body)lobbyRun a handler the lobby script registered with lobby.rpc.register(name, fn).

lobby needs the lobby capability, which needs the Grow plan or above (see features). Each of these calls waits for the lobby service, so keep them few. Calls between a Scripted API script and a lobby script are not counted against the plan again, and they cannot loop without end: a chain of calls stops after a few steps with deadline_exceeded. The Scripted API's data and a lobby script's data are separate stores. A lobby script reads one value from the Scripted API with sapi.read(scope, key, user, fn) and runs a logic with sapi.call(logic, { action, body, user }, fn).

progress, items.grant and webhook.send are sent after the handler returns without an error. Without user they act for the signed-in player. Achievements, stats and events must list scripted_api among their writers.

A signed webhook carries X-Blazium-Timestamp, X-Blazium-Game and X-Blazium-Signature, the lowercase hex HMAC-SHA256 of {timestamp}.{body} keyed with the secret.

Standard library​

NameContents
std.timenow, now_ms, date, iso, start_of_day, start_of_week, start_of_month, add_days. UTC.
std.cryptosha256, hmac_sha256, uuid, random_hex, equal (constant time), base64_encode, base64_decode.
std.randomint, float, and new(seed) for a repeatable generator with int, float, pick and shuffle.
std.validate(value, schema)Returns true or false and a message. Schemas use type, optional, enum, min, max, min_len, max_len, items, fields and extra.
std.ratelimit(key, limit, window_sec)true while under the limit.
std.json, api.jsonencode and decode.
log.debug, log.info, log.warn, log.errorA message and optional fields, kept per the plan's log retention.
api.game, api.channel, api.plan, api.request_idThe current call.

os, debug, loadstring, getfenv, setfenv and collectgarbage are removed. There is no file access, and the network is reached only through api.http and webhook.send.

Errors in Luau​

A failing platform call raises a table { ok = false, code, message, scope }. Catch it with pcall:

local ok, err = pcall(function()
data.user:set("inventory", inv)
end)
if not ok and type(err) == "table" and err.code == "over_plan_limit" then
return { status = 402, body = { error = "storage is full" } }
end

An uncaught over_plan_limit, forbidden, unauthorized, rate_limited, db_unavailable or unknown channel becomes the matching HTTP error below. Anything else becomes 4310, and only the request id is shown to the caller. If the handler fails, none of its data writes are kept.

Error codes​

Errors use { "ok": false, "error": { "code": 4307, "key": "rate_limited", "message": "..." } }.

CodeKeyHTTPMeaning
4300bad_request400The request is malformed.
4301unknown_game404No such game.
4302unknown_logic404No such logic, or no pack is active on the channel.
4303method_not_allowed405The logic's methods do not include this one.
4304unauthorized401Missing, expired or invalid token or key. A client asks for a new token once and retries.
4305forbidden403The caller cannot reach that data.
4306game_disabled403The Scripted API is off, or staff turned it off.
4307rate_limited429Over a game, player, address or logic rate.
4308over_plan_limit402Over a plan limit, or writes are blocked while over a data limit.
4309pack_loading503The pack is loading or failed to load.
4310script_error500The logic raised an error. See the logs.
4311budget_exceeded402The logic ran past its time or memory budget.
4312body_too_large413The body is over 64 KiB.
4313db_unavailable503Data could not be loaded. Try again.
4314lease_held503The game's data is moving between servers. Try again.
4315signature_invalid401A signed request did not verify.
4316anonymous_disabled401Anonymous calls are off for the game.
4317channel_unknown400The game has no such release channel.
4318idempotency_conflict409A request with this Idempotency-Key is still running.
4319internal500Server error.
4320conflict409Data kept changing during the request. Try again.
4321not_found404No such route.
4322service_unavailable503Busy, restarting, or sign-in cannot be checked. Try again.
4323feature_disabled403The feature or capability is not turned on for the game. Nothing ran and the call was not counted against the plan. The error names it in feature.
4324deadline_exceeded504A call that waited on another part of the platform ran out of time.

The same codes come back through api.blazium.online when the website, chauffeur or MCP reach the Scripted API for you.

Limits​

LimitFreeGrowScale
Value size4 KiB32 KiB128 KiB
Global data256 KiB, 250 keys4 MiB, 4,000 keys16 MiB, 16,000 keys
Data per channel256 KiB, 250 keys2 MiB, 2,000 keys8 MiB, 8,000 keys
Channels with data2825
Data per player16 KiB, 32 keys128 KiB, 200 keys512 KiB, 1,000 keys
Stored data per game50 MiB2 GiB25 GiB
Calls per minute per game6006,00030,000
Calls per minute per player30120300
Calls running at once41648
Data operations per call1664128
Time per call250 ms1 s2.5 s
Memory per call2 MiB8 MiB16 MiB
Outbound calls per call248
Outbound calls per hour1205,00050,000
Outbound timeout3 s5 s8 s
Outbound response64 KiB256 KiB1 MiB
Pack size256 KiB2 MiB8 MiB
Logic files20100250
Packs kept31025
Schedules21050
Shortest schedule interval1 hour5 minutes1 minute
Secrets525100
Config values505002,000
Leaderboards220100
Entries per leaderboard1,00050,000250,000
Log lines kept1,00020,000100,000
Log retention1 day7 days30 days

A pack that is over the plan's pack, file or schedule limits is refused when it is published. When a plan ends, stored data stays readable and deletable, and writes are refused with 4308 while the game is over a data limit.