The Lua Script policy in API Studio for the DataPower Nano Gateway: worked examples
Draft!!
The Nano Gateway Lua Script reference lists the extension functions and stops there. This post runs eight scripts against a real gateway, with the YAML from API Studio code view and the response that came back.
The companion posts cover the invoke policy, the switch policy and JSONata. Every script here does something the Nano Gateway JSONata subset cannot do: read a clock, loop, split a string or write to the log.
The test project
One API Studio project, one API called nano-luascript, one operation per script. There is no backend. Every response is built by the script.
ExtractIdentity, Authenticate and Authorize enforce client credentials, then an OperationSwitch sends each operation to its own policies. The POST operations run a parse policy first, because body:read() throws on a body that has not been parsed:
kind: OperationSwitch
spec:
cases:
- conditions:
- verbPath:
path: /audit/enrich
verb: POST
execute:
- $ref: nanogw-policy-samples:nano-luascript-parse-request:1.0.0
- $ref: nanogw-policy-samples:nano-luascript-audit-enrich:1.0.0
kind: Parse
spec:
input: request
documentType:
json: {}
The GET operations skip the parse and read the live request.
Every call goes to the published product URL with the client credentials of a subscribed application:
curl -s \
-H "X-IBM-Client-Id: <client-id>" \
-H "X-IBM-Client-Secret: <client-secret>" \
"https://<product>-<catalog>-<org>.nanogw.<ingress-domain>/1.0.0/nano-luascript/response/pretty"
Without credentials the same call returns 401 Unauthorized.
What the policy gives you
The reference says Lua 5.1 is supported, minus io.*, load, dofile, debug.* and a few os functions (os.execute, os.exit, os.getenv and others). os.date and os.time are not on the excluded list, and both work in the examples below. Some LuaJIT and Lua 5.2 extensions are included.
Four globals are preset:
| Global | Use |
|---|---|
context |
get/set variables, get_message, create_message, run_action |
json |
encode(value, pretty) and decode(string) |
console |
write to the gateway log |
buffer |
create Buffer objects for unparsed bodies |
A message has status, status_text, headers and body. headers:get(name) returns a string or nil. headers:set(name, nil) deletes the header, and a table sets a repeated header. body:read() and body:write(value) do what they say.
One rule runs through every example. Writing to the request message does not produce a reply. To answer the caller, create a response message with context:create_message('response') and write to that.
Example 1: audit stamp
Add the facts only the gateway knows to the caller’s document and leave one log line. JSONata has no clock and cannot change a value it has read, so this is a Lua job.
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local resp = context:create_message('response')
local body = req.body:read() or {}
if type(body) ~= 'table' then
body = { payload = body }
end
local correlation = req.headers:get('X-Correlation-Id')
if correlation == nil or correlation == '' then
correlation = context:get('correlationId') or 'unset'
end
-- '!' means UTC. Lua 5.1 has no %F or %T, so spell the format out.
local receivedAt = os.date('!%Y-%m-%dT%H:%M:%SZ')
body.gateway = {
receivedAt = receivedAt,
correlationId = correlation,
clientId = req.headers:get('X-Caller-Id'),
auditVersion = 1,
}
resp.body:write(body)
resp.headers:set('X-Gateway-Audit', 'v1')
context:set('auditedAt', receivedAt)
console.info('audit correlation=%s client=%s at=%s',
tostring(correlation), tostring(body.gateway.clientId), receivedAt)
curl ... -X POST -H 'Content-Type: application/json' \
-H 'X-Correlation-Id: cid-42' -H 'X-Caller-Id: abc123' \
-d '{"orderId":"ORD-1001","amount":42.5}' \
"https://<gateway-host>/1.0.0/nano-luascript/audit/enrich"
HTTP/2 200
x-gateway-audit: v1
{"amount":42.5,"gateway":{"auditVersion":1,"clientId":"abc123","correlationId":"cid-42","receivedAt":"2026-12-02T15:32:09Z"},"orderId":"ORD-1001"}
The optional header values go through tostring() before they reach console.info, so a missing header does not break the format call.
Now the same call with neither header:
{"amount":42.5,"gateway":{"auditVersion":1,"correlationId":null,"receivedAt":"2026-12-02T15:32:09Z"},"orderId":"ORD-1001"}
clientId is gone, which is right: a nil table value is not serialised. correlationId is null, not 'unset'. I expected the or 'unset' fallback to fire, so context:get('correlationId') must return something that is not nil when the variable was never set. I did not dig further. Test the missing-input path of every script you write.
Example 2: text clean-up
A legacy client sends a padded name, a mixed-case email and a comma-separated tag string with empty entries. The JSONata subset has no $trim, $split or $join. Lua has gsub and gmatch.
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local resp = context:create_message('response')
local body = req.body:read() or {}
local function trim(s)
return (s:gsub('^%s+', ''):gsub('%s+$', ''))
end
local function collapse(s)
return trim(s:gsub('%s+', ' '))
end
local name = collapse(tostring(body.name or ''))
local tags = {}
for tag in tostring(body.tags or ''):gmatch('[^,]+') do
local t = trim(tag)
if t ~= '' then
table.insert(tags, string.lower(t))
end
end
local words = 0
if name ~= '' then
local _, spaces = name:gsub(' ', '')
words = spaces + 1
end
resp.body:write({
name = name,
nameLength = string.len(name),
wordCount = words,
email = string.lower(trim(tostring(body.email or ''))),
tags = tags,
tagCount = #tags,
})
resp.headers:set('X-Normalised', 'true')
Request body:
{ "name": " Ada Lovelace ", "email": " ADA@Example.COM ", "tags": "a, b ,, c" }
HTTP/2 200
x-normalised: true
{"email":"ada@example.com","name":"Ada Lovelace","nameLength":12,"tagCount":3,"tags":["a","b","c"],"wordCount":2}
gsub returns two values: the string and the number of substitutions. Wrap the call in parentheses, as trim does, or the count leaks into whatever receives the result.
Example 3: parse a log line
Legacy services write text logs. To index them you need the level, the logger and the key=value tail as fields, with numbers as numbers.
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local resp = context:create_message('response')
local body = req.body:read() or {}
local line = tostring(body.line or '')
local tokens = {}
for token in line:gmatch('%S+') do
table.insert(tokens, token)
end
local parsed = {
timestamp = tokens[1],
level = tokens[2],
logger = tokens[3],
fields = {},
}
for i = 4, #tokens do
local key, value = string.match(tokens[i], '^([%w_%.%-]+)=(.*)$')
if key then
parsed.fields[key] = tonumber(value) or value
else
parsed.fields['arg' .. (i - 3)] = tonumber(tokens[i]) or tokens[i]
end
end
parsed.tokenCount = #tokens
parsed.fieldCount = 0
for _ in pairs(parsed.fields) do
parsed.fieldCount = parsed.fieldCount + 1
end
resp.body:write(parsed)
Request body:
{ "line": "2026-12-01T19:00:00Z WARN payment.retry attempt=3 delay=1.5 note=timeout" }
HTTP/2 200
{"fieldCount":3,"fields":{"attempt":3,"delay":1.5,"note":"timeout"},"level":"WARN","logger":"payment.retry","timestamp":"2026-12-01T19:00:00Z","tokenCount":6}
tonumber(value) or value is the idiom to remember. tonumber returns nil for text, so attempt=3 stays a number and note=timeout stays a string without a type test.
Example 4: reject early with a status code
Reject stale requests before they reach a backend. The check needs a clock. A bare return at the top level ends the script and keeps whatever response has been written so far:
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local resp = context:create_message('response')
local body = req.body:read() or {}
local SKEW_SECONDS = 60
local expiresAt = tonumber(body.expiresAt)
local now = os.time()
if expiresAt == nil then
resp.status = 400
resp.headers:set('Content-Type', 'application/json')
resp.body:write({ error = 'expiresAt (epoch seconds) is required',
code = 'MISSING_EXPIRY' })
return
end
if expiresAt < now - SKEW_SECONDS then
resp.status = 401
resp.headers:set('Content-Type', 'application/json')
resp.body:write({ error = 'request token has expired',
code = 'TOKEN_EXPIRED',
expiredSecondsAgo = now - expiresAt,
allowedSkewSeconds = SKEW_SECONDS })
return
end
resp.body:write({ fresh = true,
expiresInSeconds = expiresAt - now,
allowedSkewSeconds = SKEW_SECONDS })
Three calls. A token that expires in 2100:
HTTP/2 200
{"allowedSkewSeconds":60,"expiresInSeconds":2306219270,"fresh":true}
A token that expired in 2001:
HTTP/2 401
content-type: application/json
{"allowedSkewSeconds":60,"code":"TOKEN_EXPIRED","error":"request token has expired","expiredSecondsAgo":796225530}
No expiresAt at all:
HTTP/2 400
content-type: application/json
{"code":"MISSING_EXPIRY","error":"expiresAt (epoch seconds) is required"}
This is how a Lua policy returns a 4xx with a body of your choosing. error() gives a 500 (see Example 8). The 60 second skew is deliberate. Client and gateway clocks never line up exactly, and rejecting on a millisecond turns a clock blip into an outage.
Example 5: repeated headers
$header() in JSONata returns one scalar. Lua can read a list and write one back.
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local resp = context:create_message('response')
local function trim(s)
return (s:gsub('^%s+', ''):gsub('%s+$', ''))
end
local raw = req.headers:get('X-Tag')
local tags = {}
if type(raw) == 'table' then
for _, value in ipairs(raw) do
table.insert(tags, string.lower(trim(tostring(value))))
end
elseif raw ~= nil then
for value in tostring(raw):gmatch('[^,]+') do
table.insert(tags, string.lower(trim(value)))
end
end
req.headers:set('X-Debug', nil) -- nil deletes the header
req.headers:set('X-Tag-Count', tostring(#tags))
resp.headers:set('X-Tag', tags) -- a table sets a repeated header
resp.body:write({ tags = tags, count = #tags })
A comma-separated list:
curl ... -H 'X-Tag: Alpha, beta ' "https://<gateway-host>/1.0.0/nano-luascript/headers/multi"
HTTP/2 200
x-tag: alpha
x-tag: beta
{"count":2,"tags":["alpha","beta"]}
The table written to resp.headers came back as two x-tag response headers. Now two separate header lines:
curl ... -H 'X-Tag: Alpha' -H 'X-Tag: Beta' "https://<gateway-host>/1.0.0/nano-luascript/headers/multi"
HTTP/2 200
x-tag: alpha
{"count":1,"tags":["alpha"]}
Only the first line reached the script. On my cluster the request goes through the OpenShift router first, and I do not know where the second line was lost. Do not build anything that depends on repeated request header lines. Use the comma-separated form, and keep the type(raw) == 'table' branch for a gateway that does pass a list.
Example 6: answer without a backend
Service metadata, feature flags and migration shims do not need a backend. json.encode(value, true) is the only way to get formatted output. If you body:write() a table, the runtime serialises it compactly.
kind: LuaScript
spec:
source: |
local resp = context:create_message('response')
local payload = {
service = 'nano-luascript',
pattern = 'inline response from a Lua Script policy',
generatedAt = os.date('!%Y-%m-%dT%H:%M:%SZ'),
patterns = {
'audit enrichment',
'text normalisation',
'log parsing',
'token freshness',
'header normalisation',
},
}
payload.patternCount = #payload.patterns
resp.status = 200
resp.headers:set('Content-Type', 'application/json')
resp.headers:set('X-Body-Source', 'lua-script-policy')
resp.body:write(json.encode(payload, true))
HTTP/2 200
content-type: application/json
x-body-source: lua-script-policy
{
"generatedAt": "2026-12-02T15:23:35Z",
"pattern": "inline response from a Lua Script policy",
"patternCount": 5,
"patterns": [
"audit enrichment",
"text normalisation",
"log parsing",
"token freshness",
"header normalisation"
],
"service": "nano-luascript"
}
Example 7: run another policy from a script
The policy has an actions map. Each entry is a reference to another policy in the project, and context:run_action(name) runs it at that point in the script. That lets you reuse a set or invoke without repeating it in the assembly.
The referenced policy is a set that writes X-Trace-Id onto the request using JSONata. It is not in any execute list. It exists as a file in the project and as an actions entry:
kind: Set
spec:
valueType: jsonata
messageHeader:
messageName: request
action: set
headerName: X-Trace-Id
value: $gtid()
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local resp = context:create_message('response')
context:run_action('set-trace-header')
resp.body:write({
traceHeader = req.headers:get('X-Trace-Id'),
tenantHeader = req.headers:get('X-Tenant'),
actionRan = true,
})
actions:
set-trace-header:
$ref: nanogw-policy-samples:nano-luascript-set-trace:1.0.0
curl ... -X POST -H 'Content-Type: application/json' -H 'X-Tenant: acme' \
-d '{"note":"run the set policy"}' \
"https://<gateway-host>/1.0.0/nano-luascript/action/run"
HTTP/2 200
{"actionRan":true,"tenantHeader":"acme","traceHeader":"8790700e-8773-4015-9c89-a6372cf71d48"}
The caller never sent X-Trace-Id. The header was created by the action, and the script read it back straight away.
The reference says not every policy is a valid action. Check the “Options for actions” table on the LuaScript page before you rely on one.
Example 8: an uncaught error
kind: LuaScript
spec:
source: |
local req = context:get_message('request')
local body = req.body:read() or {}
error('deliberate Lua error: amount=' .. tostring(body.amount))
HTTP/2 500
Internal Server Error
The caller gets a plain 500 and the canonical text. The Lua message is not returned. If you need to know what went wrong, call console.error before the statement that can fail. There is no way to choose the status or body from error(). For a business rejection use the early return in Example 4, or a throw policy.
Summary
- Build the reply in a
responsemessage created withcontext:create_message. Writing torequestdoes not answer the caller. - Put a
parsepolicy in front of any script that callsbody:read()on a request body. - Use a bare
returnafter settingresp.statusto send a 4xx. Useerror()only for faults you want to be a500. - Reach for Lua when the job needs a clock, a loop, a split or a mutable document. Use JSONata for everything else.
Limitations and Notes
- Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
- The runtime does not compile a script until the operation is called. In my earlier testing on this project, a broken script passed
apic lint,apic buildand publish, and only the caller of that one operation saw the failure. I did not re-run that test for this post. Call every operation after you publish. - Not tested:
body:extract,body:redact,body:remove,buffer,json.decodeandBuffermethods. I did not look at the runtime log, so I cannot show whatconsole.infowrote. - The missing-header
correlationId: nullresult in Example 1 is unexplained. I have not found it in the documentation. - The Nano Gateway only validates JSON schemas, so keep the response schema in the OpenAPI document to JSON media types.
