Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Call lunas over HTTP

Call a handler with a plain HTTP request from any language, read the status and error body, and retry without running a call twice.

A program in a language without a Luna client can still call any luna. Each call is one POST with the arguments as JSON, and the answer is the handler’s result as JSON.

Call a handler

The URL is the environment’s URL, the luna type, the key and the handler’s name. Send a publishable key in the luna-key header. Run source .env.local first to load LUNA_URL and LUNA_KEY.

curl -X POST "$LUNA_URL/List/groceries/add" \
  -H "luna-key: $LUNA_KEY" \
  -H "content-type: application/json" \
  -d '{"text":"milk"}'

The body is a JSON object of the handler’s arguments. An empty body means no arguments. A call that succeeds answers 200 with the result as its body, and null for a handler that returns nothing.

Put the key in the URL

The key takes one path segment for each key field, in the order the luna type declares them. A Card keyed by board and card is called at /Card/<BOARD>/<CARD>/<HANDLER>.

Key field Written as
t.string() The value. Letters, digits, -, _, . and ~ need no encoding
t.int() Digits
t.bytes() URL-safe base64

A stateless luna type has no key, so its URL is /<TYPE>/<HANDLER>. A wrong number of segments answers 400 with Invalid.

Send credentials

A publishable key goes in the luna-key header, or as ?key= in the URL. It reaches only public luna types, and a private type answers 404 as if it did not exist.

Your own servers can send a secret token instead, which reaches every luna type of the environment.

curl -X POST "$LUNA_URL/List/groceries/all" -H "Authorization: Bearer <SECRET_TOKEN>"

Keys and tokens explains both.

Read the status and the error body

A failed call answers with an error body. Its code is Luna’s own code, with a message.

curl -X POST "$LUNA_URL/Lists/groceries/all" -H "luna-key: $LUNA_KEY"
{"error":{"code":"NotFound","message":"no luna type Lists"}}

A handler that fails with ctx.fail answers 422, and its body holds the declared code and its data, such as {"error":{"code":"Nope","data":{"why":"because"}}}.

Status code The call
400 Invalid Has a body that is not a JSON object, an argument of the wrong type or a wrong key
401 Unauthorized Has no valid publishable key or secret token
403 The luna’s own code Was refused by the luna type’s onBeforeConnect
404 NotFound Names no luna type or handler, or a private type with a publishable key
422 The declared code Failed with ctx.fail
429 Overloaded, QuotaExceeded Is over the key’s rate or a quota
502 OutcomeUnknown May or may not have run
503 Unavailable Could not reach the luna
504 Timeout Ran out of time

Errors lists every code and whether a retry is safe.

Set a deadline

luna-timeout-ms sets how long the call may take, in milliseconds. Without it, a call has 60 seconds.

curl -X POST "$LUNA_URL/List/groceries/all" -H "luna-key: $LUNA_KEY" -H "luna-timeout-ms: 5000"

Retry without running twice

Send an idempotency-key header with a value of your own. A second call to the same luna with the same value gets the first call’s answer, and the handler does not run again.

curl -X POST "$LUNA_URL/List/groceries/add" \
  -H "luna-key: $LUNA_KEY" \
  -H "idempotency-key: add-milk-7f3a" \
  -d '{"text":"milk"}'

Luna keeps an answer for at least 3 days. It keeps a result and a declared error, but not Luna’s own errors, so a call that failed with Unavailable runs when you retry it.

Read from a copy

A query handler may be answered by a read copy of the luna. The luna-read header says how fresh the answer must be.

luna-read The answer
latest Comes from the luna itself
max-stale=<MS> May be up to this many milliseconds behind
at-least=<POSITION> Includes every write up to a position that a handler returned from ctx.position()

The header has no effect on a handler that is not a query.

Call from Python

Python’s standard library is enough. This function calls a handler and turns an error body into an exception.

import json
import os
import urllib.error
import urllib.request


def call(path: str, args: dict) -> object:
    request = urllib.request.Request(
        f"{os.environ['LUNA_URL']}/{path}",
        data=json.dumps(args).encode(),
        headers={"luna-key": os.environ["LUNA_KEY"], "content-type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request) as response:
            return json.load(response)
    except urllib.error.HTTPError as e:
        error = json.load(e)["error"]
        raise RuntimeError(f"{e.code} {error['code']}: {error.get('message')}") from e


call("List/groceries/add", {"text": "milk"})
print(call("List/groceries/all", {}))

Python code that needs live queries can use LunaClient from luna.client in the Python SDK instead, as Python SDK describes.

Next steps

Was this page helpful?