The Lua Script policy in API Studio for the DataPower Nano Gateway: worked examples

This post runs eight Lua scripts against a real DataPower Nano 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.
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:
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
os.date and os.time worked in the examples below. Three preset globals appear in them:
| Global | Used for |
|---|---|
context |
get_message, create_message, get, set and run_action |
json |
encode(value, pretty) |
console |
info, to write to the gateway log |
A message has status, headers and body. headers:get(name) returns a string or nil. For a repeated request header it returns the first value only (see Example 5). headers:set(name, table) sets a repeated header in Example 5. body:read() and body:write(value) read and write the body.
Each script creates a response message with context:create_message('response') and writes to that.
Example 1: audit stamp
Add the facts only the gateway knows to the caller’s document and leave one log line.
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', so the or 'unset' fallback did not fire.
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 script uses 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. trim wraps the call in parentheses to keep the string.
Nano Gateway 1.2 JSONata has $trim, $split and $join, so a clean-up this simple can also be done in a set policy. See the JSONata post.
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 skew is 60 seconds.
Example 5: repeated headers
This script reads one header and writes a repeated 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 raw ~= nil then
for value in tostring(raw):gmatch('[^,]+') do
table.insert(tags, string.lower(trim(value)))
end
end
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. headers:get() returns the first value of a repeated request header and there is no way to read the rest. The OpenShift router is not the cause. Reading every value needs an RFE, so raise one if you depend on it.
Example 6: answer without a backend
Service metadata, feature flags and migration shims do not need a backend. json.encode(value, true) gives formatted output. A table passed to body:write() came back compact, as in the earlier examples.
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.
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.
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.
Summary
- A bare
returnafter settingresp.statusreturned a 4xx with my own body (Example 4). error()returned a plain500(Example 8).- A table passed to
resp.headers:setcame back as repeated response headers. Of two repeated request header lines, only the first reached the script (Example 5). Reading all of them needs an RFE.
Limitations and Notes
- Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
headers:get()returns only the first value of a repeated request header.
