HTTP API (liuska serve)
liuska serve runs a small HTTP server with a warm rendering engine: fonts are loaded once and renders run concurrently. It is the fastest way to generate PDFs from a backend service, and it also serves the designer.
liuska serve --addr 127.0.0.1:8080 --templates ./templates
| Method | Path | Returns |
|---|---|---|
POST |
/api/render |
application/pdf |
POST |
/api/preview?page=1&dpi=96 |
One page: image/png, or a one-page application/pdf with format=pdf |
POST |
/api/validate |
{ "issues": [...] } |
POST |
/api/layout |
Pagination: where every element lands, per page (JSON) |
GET |
/api/sample-data?file=data.json |
A template's sampleDataFile from --templates (JSON) |
GET |
/api/templates |
Names of the templates in --templates |
GET |
/api/templates/{name} |
Template JSON |
PUT |
/api/templates/{name} |
Saves a template |
GET |
/api/healthz |
200 when ready |
GET |
/ |
The designer (SPA) |
Request body
render, preview, validate and layout all take the same body: either an inline template or the name of one in the --templates directory, plus the data.
{ "template": { "version": 1, "page": { "size": "A4" }, "elements": [] }, "data": { "customer": { "name": "Acme" } } }
{ "templateName": "invoice", "data": { "invoice": { "number": "INV-1" } } }
templateName refers to <templates dir>/<name>.json. Bodies can be up to 32 MB.
POST /api/render
curl -sS -X POST http://127.0.0.1:8080/api/render \
-H "Content-Type: application/json" \
--data-binary @- -o invoice.pdf -D - <<'EOF'
{ "templateName": "invoice", "data": { "customer": { "name": "Contoso Retail Oy" }, "items": [] } }
EOF
The fastest way to build a body from existing files is to let jq assemble it:
jq -n --slurpfile t examples/invoice/template.json --slurpfile d examples/invoice/data.json \
'{template: $t[0], data: $d[0]}' |
curl -sS -X POST http://127.0.0.1:8080/api/render -H "Content-Type: application/json" --data-binary @- -o invoice.pdf
On PowerShell:
$body = @{ template = Get-Content examples/invoice/template.json -Raw | ConvertFrom-Json
data = Get-Content examples/invoice/data.json -Raw | ConvertFrom-Json } | ConvertTo-Json -Depth 50
Invoke-WebRequest -Method Post -Uri http://127.0.0.1:8080/api/render -ContentType application/json -Body $body -OutFile invoice.pdf
Response headers:
| Header | Meaning |
|---|---|
Content-Type: application/pdf |
|
X-Liuska-Pages |
Number of pages |
X-Liuska-Duration-Ms |
Render time on the server |
Note: an inline template has no directory, so relative image, font and snippet paths can't be resolved. Use templateName for templates that reference files, or inline images as data: URIs.
POST /api/preview
Renders one page. format=png (default) returns a PNG at dpi. format=pdf returns that page alone as a one-page PDF (dpi is ignored): the layout still covers the whole document, so page numbers and table continuations are right, but PDF/A, tagging, signing and encryption are not applied. The designer uses format=pdf for its live preview and draws it in the browser with pdf.js, which costs the server about a tenth of the CPU and bandwidth of a PNG.
curl -sS -X POST "http://127.0.0.1:8080/api/preview?page=2&dpi=110" \
-H "Content-Type: application/json" -d '{"templateName":"sales","data":{}}' -o page2.png
curl -sS -X POST "http://127.0.0.1:8080/api/preview?page=2&format=pdf" \n -H "Content-Type: application/json" -d '{"templateName":"sales","data":{}}' -o page2.pdf
It returns the same X-Liuska-Pages and X-Liuska-Duration-Ms headers, so a client can show "page 2 of 5".
POST /api/validate
curl -sS -X POST http://127.0.0.1:8080/api/validate \
-H "Content-Type: application/json" -d '{"templateName":"sales","data":{"report":{}}}'
{ "issues": [
{ "path": "elements[7].data", "message": "\"report.rows\" not found in data", "severity": "warning" }
] }
POST /api/layout
Lays the template out with the data, exactly as render would, and returns where everything landed instead of drawing it. The designer uses it for its multi-page canvas; it is also handy for tests ("does the totals row still fit on page 1?").
{
"width": 841.89, "height": 595.28, "margins": { "top": 30, "right": 30, "bottom": 30, "left": 30 },
"headerHeight": 50, "footerHeight": 24, "bodyTop": 80, "bodyBottom": 541.28,
"pageCount": 6,
"sectionStarts": [0],
"pages": [
{ "index": 1, "bodyTop": 132, "bodyBottom": 541.28, "boxes": [
{ "id": "kpis", "path": "elements[0]", "type": "group", "zone": "body", "x": 30, "y": 84, "w": 781.89, "h": 40, "repeat": true },
{ "id": "sales", "path": "elements[3]", "type": "table", "zone": "body", "x": 30, "y": 132, "w": 781.89, "h": 405.6,
"segment": { "index": 1, "count": 6, "fromRow": 11, "toRow": 36, "rows": 120, "header": true, "totals": false } },
{ "id": "pageNo", "path": "footer.elements[2]", "type": "text", "zone": "footer", "x": 612, "y": 551.28, "w": 200, "h": 12 }
] }
],
"warnings": [],
"durationMs": 1.03
}
- Coordinates are absolute page points, origin top-left. Pages are 0-based.
boxeslists the top-level elements on that page: header/footer elements (zone), repeated copies ("repeat": true, see templates.md "Repeating elements"), and one box per table segment with its body-row range[fromRow, toRow)and whether the header/totals rows are drawn there. Group children are not listed; they keep their offsets inside the group.sectionStarts[i]is the page on which the elements after the i-thpageBreakstart.bodyTop/bodyBottomper page are the body area after space reserved by repeated elements.- Errors are as for
/api/render.
The engine call behind it is Engine.Layout(ctx, template, data) (renderer/layoutinfo.go). It runs the normal layout and nothing else, so it costs about as much as a render minus drawing.
GET /api/sample-data
curl -sS "http://127.0.0.1:8080/api/sample-data?file=sales.sample.json"
Returns the file as JSON (.csv/.tsv files are converted as with liuska render -d: rows under "rows"). The designer calls it to load a template's sampleDataFile. file is resolved relative to the --templates directory and must stay inside it: absolute paths, .. and symlinks pointing out are refused (400), and only .json, .csv and .tsv are served. Without --templates the endpoint answers 404 and the designer asks the user to pick the file.
Templates
The templates endpoints are available when the server was started with --templates dir.
curl -sS http://127.0.0.1:8080/api/templates # ["invoice","sales"]
curl -sS http://127.0.0.1:8080/api/templates/invoice -o invoice.json
curl -sS -X PUT http://127.0.0.1:8080/api/templates/invoice \
-H "Content-Type: application/json" --data-binary @invoice.json
Errors
Errors are returned as JSON with a non-2xx status:
{ "error": "template is invalid", "issues": [ { "path": "elements[2].type", "message": "unknown element type \"circle\"", "severity": "error" } ] }
| Status | When |
|---|---|
| 400 | Malformed JSON, both or neither of template / templateName |
| 404 | templateName not found |
| 413 | Body over the size limit |
| 422 | Template failed validation (issues filled) |
| 500 | Render error |
Health
curl -fsS http://127.0.0.1:8080/api/healthz
Use it for container liveness and readiness probes. GET /healthz is an alias. Neither needs an API key. Without a key, the answer is just {"ok":true,"authRequired":…}.
CORS
CORS is off by default. The designer's Vite dev server proxies /api, so it does not need CORS. To call the API from a browser app on another origin, allow that exact origin with --cors-origin https://app.example.com. Usually it is better to call the API from your backend. See security.md.
Authentication
When the server is started with API keys (--api-key-file, LIUSKA_API_KEYS), every /api/ route except GET /api/healthz needs Authorization: Bearer <key>. Missing or wrong keys get 401. With --read-only, PUT /api/templates/{name} returns 403. Other status codes: 413 (body over --max-body), 421 (Host not allowed), 422 with a render limit exceeded message (--max-pages, --max-rows, preview size), 503 (timeout or busy; retry). See security.md.
Integrating from a backend
Run liuska serve as a sidecar or internal service. Keep templates in a directory that ships with your app and refer to them by name. Your service only has to send data.
Node.js (fetch)
const res = await fetch("http://liuska:8080/api/render", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ templateName: "invoice", data: invoice }),
});
if (!res.ok) throw new Error(`liuska: ${res.status} ${await res.text()}`);
const pdf = Buffer.from(await res.arrayBuffer());
Go
body, _ := json.Marshal(map[string]any{"templateName": "sales", "data": report})
resp, err := http.Post("http://liuska:8080/api/render", "application/json", bytes.NewReader(body))
if err != nil { return err }
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(resp.Body)
return fmt.Errorf("liuska: %s: %s", resp.Status, msg)
}
_, err = io.Copy(w, resp.Body) // stream the PDF to the client or to storage
Python (requests)
r = requests.post("http://liuska:8080/api/render", json={"templateName": "sales", "data": report}, timeout=30)
r.raise_for_status()
open("sales.pdf", "wb").write(r.content)
C# (HttpClient)
var res = await http.PostAsJsonAsync("http://liuska:8080/api/render", new { templateName = "invoice", data = invoice });
res.EnsureSuccessStatusCode();
await using var pdf = await res.Content.ReadAsStreamAsync();
Go, in process. A Go service can skip HTTP altogether and use the engine package directly:
eng, _ := renderer.NewEngine(renderer.Options{}) // once, at startup; safe for concurrent use
tmpl, _ := renderer.ParseFile("templates/invoice.json") // parse once, reuse
res, err := eng.Render(ctx, tmpl, data, w) // per request; res.Pages, res.Duration
Deployment notes:
- The server binds to
127.0.0.1by default. In a container, use--addr 0.0.0.0:8080together with API keys (--api-key-file), or with--no-authif the port stays internal. The server refuses a non-loopback address without either. See security.md. - One process handles concurrent requests. Scale out by running more replicas behind your load balancer.
X-Liuska-Duration-Msis handy to log, because it separates render time from network time.