JSONata in API Studio for the DataPower Nano Gateway: worked examples
This post runs eleven JSONata patterns on the DataPower Nano Gateway, with the YAML from API Studio code view and the response the gateway returned.
The companion post covers the Lua Script policy.
Contents
- The test project
- How the response is built
- What the runtime supports
- Example 1: correlation IDs
- Example 2: who am I
- Example 3: inspect a bearer token
- Example 4: map one contract to another
- Example 5: a pricing rule
- Example 6: normalise query parameters
- Example 7: path parameters
- Example 8: base64
- Example 9: pass a value between policies
- Example 10: raise an error from a guard
- Example 11: a path that matches nothing
- Summary
- Limitations and Notes
The test project
One API Studio project, one API called nano-jsonata, one operation per pattern. There is no backend. Every response is built by a set policy.
ExtractIdentity, Authenticate and Authorize enforce client credentials, then an OperationSwitch sends each operation to its own policies. The POST operations run a parse policy with documentType: json first. The GET operations read the live request and need no parsing.

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-jsonata/identity"
Without credentials the same call returns 401 Unauthorized.
How the response is built
Every operation ends with one set policy. With valueType: jsonata it evaluates the expression and writes the result as the response message, so no backend is needed:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{ "correlationId": $variable('correlationId') }
valueType sits directly under spec, next to messageBody or variable. The default is not in the documentation. Leave valueType: jsonata out and the expression comes back as literal text, with one exception: the default is variable resolution, so $(myVar) in the string is replaced, and nothing else is evaluated.
An expression runs against its own message, not the request. A bare orderId in an expression that writes to response is nothing. Request data comes through the context functions: $body('request').orderId, $header('request', 'X-Foo'), $queryParameter('request', 'q').
Reading the message body is expensive, and an expression that calls $body six times pays six times. Call a context function once, use its result as the context with . [ { ... } ], and read the fields by name. Examples 6, 7 and 8 do this.
What the runtime supports
Nano Gateway 1.2 supports these built-in JSONata functions:
| Family | Functions |
|---|---|
| String | $base64encode $base64decode $contains $join $match $replace $length $lowercase $split $string $substring $substringBefore $substringAfter $uppercase $trim |
| Object | $error |
| Numeric | $floor $ceil $abs $number $random $max $min $sum $average |
| Boolean | $boolean $not $exists |
| Array | $count |
Nano also adds its own functions on top of JSONata:
| Group | Functions |
|---|---|
| Message | $body(message) $bodyType(message) $header(message, name) $headers(message) $httpMethod(message) $pathAndQuery([message]) $queryParameter(message, name) $queryParameters(message) $statusCode([message]) $statusMessage([message]) |
| Transaction and context | $gtid() $tid() $groupId() $variable(name) $requestProperty(name) $telemetry(key[, spanId[, spanName]]) |
| API mode only | $apiName() $extractIdentityTypes([namespace]) $openApiSecurityInfo() $path() $pathParameter(name) $pathParameters() $relativeUrl(message) |
| MCP server mode only | $primitiveName() $primitiveType() $sessionId() |
When you leave message out, $pathAndQuery uses the request, and $statusCode and $statusMessage use the response. $requestProperty accepts uri_scheme, client_addr, remote_addr, local_addr and host. $telemetry scopes the lookup to the policySpan or httpSpan span when you pass spanId, optionally filtered by spanName, and raises an error when telemetry is not enabled for the transaction.
Example 1: correlation IDs
Reuse the caller’s X-Correlation-Id, or make one. I made the choice with a switch policy:
kind: Switch
spec:
cases:
- condition: $exists($header('request', 'X-Correlation-Id'))
execute:
- $ref: nanogw-policy-samples:nano-jsonata-set-correlation:1.0.0
otherwise:
- $ref: nanogw-policy-samples:nano-jsonata-set-correlation-fallback:1.0.0
Each branch stores the result in the same assembly variable. The caller’s header:
kind: Set
spec:
valueType: jsonata
variable:
name: correlationId
value: $header('request', 'X-Correlation-Id')
The fallback:
kind: Set
spec:
valueType: jsonata
variable:
name: correlationId
value: $gtid()
A later set reads the variable and builds the response:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"correlationId": $variable('correlationId'),
"transactionId": $tid(),
"method": $httpMethod('request'),
"path": $path(),
"route": $relativeUrl('request'),
"bodyType": $bodyType('request'),
"orderId": $body('request').orderId
}
With the header:
curl ... -X POST -H 'Content-Type: application/json' -H 'X-Correlation-Id: caller-supplied-42' \
-d '{"orderId":"ORD-1001","action":"ship"}' \
"https://<gateway-host>/1.0.0/nano-jsonata/correlation"
HTTP/2 200
content-type: application/json
{"correlationId":"caller-supplied-42","transactionId":38,"method":"POST","path":"/correlation","route":"/correlation","bodyType":"Parsed_JSON","orderId":"ORD-1001"}
Without it:
{"correlationId":"70977ae4-b7f5-4110-8e92-267c54ed3c3f","transactionId":39,"method":"POST","path":"/correlation","route":"/correlation","bodyType":"Parsed_JSON","orderId":"ORD-1001"}
$gtid() is the global transaction ID. A third call showed the minted value is the same one the gateway returns in the x-global-transaction-id response header. $tid() is an integer, not a UUID. My calls returned 38, 39 and later 3, so do not treat it as a sequence.
Example 2: who am I
The security triple has already resolved the consumer by the time this operation runs. $telemetry exposes the result, and $requestProperty exposes read-only connection facts:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"clientId": $telemetry('client_id'),
"appName": $telemetry('app_name'),
"planName": $telemetry('plan_name'),
"apiName": $telemetry('api_name'),
"catalogName": $telemetry('catalog_name'),
"clientAddr": $requestProperty('client_addr'),
"host": $header('request', 'Host'),
"userAgent": $header('request', 'User-Agent'),
"queryParameters": $queryParameters('request')
}
HTTP/2 200
content-type: application/json
{"clientId":"<client-id>","appName":"nanogw-policy-tester","planName":"nano-jsonata-plan","apiName":"nano-jsonata","catalogName":"sandbox","clientAddr":"10.129.3.148","host":"<product>-<catalog>-<org>.nanogw.<ingress-domain>","userAgent":"curl/8.7.1"}
Hit this with your own credentials to see which app, plan and catalog the gateway thinks you are. queryParameters is absent from the output because the call had no query string.
$telemetry('catalog_name') returned sandbox on my gateway.
Example 3: inspect a bearer token
$split breaks the token into its JWT segments. The Authorization header is read once and used as the context:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
$header('request', 'Authorization') . [
{
"scheme": $substringBefore($, ' '),
"isBearer": $contains($, 'Bearer '),
"tokenLength": $length($substringAfter($, 'Bearer ')),
"jwtHeaderSegment": $split($substringAfter($, 'Bearer '), '.')[0],
"jwtPayloadSegment": $split($substringAfter($, 'Bearer '), '.')[1]
}
]
The output below came from my first version, which used $substringBefore and $substringAfter only. It has not been re-run against this version.
curl ... -X POST -H 'Content-Type: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZGEifQ.sig' \
-d '{"note":"inspect, do not trust"}' \
"https://<gateway-host>/1.0.0/nano-jsonata/auth/bearer"
HTTP/2 200
{"scheme":"Bearer","isBearer":true,"tokenLength":43,"jwtHeaderSegment":"eyJhbGciOiJIUzI1NiJ9","jwtPayloadSegment":"eyJzdWIiOiJhZGEifQ"}
This reads the token segments. It does not validate the token.
Example 4: map one contract to another
A legacy upstream sends snake_case with numbers as strings. A partner contract wants camelCase and real numbers.
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"orderId": $substringAfter($body('request').order_id, 'ORD-'),
"customerName": $uppercase($body('request').customer_name),
"quantity": $number($body('request').qty),
"unitPrice": $number($body('request').unit_price),
"total": $number($body('request').qty) * $number($body('request').unit_price),
"totalWholeUnits": $floor($number($body('request').qty) * $number($body('request').unit_price)),
"currency": $uppercase($body('request').currency),
"isPaid": $body('request').status = 'paid',
"display": $string($number($body('request').qty)) & ' x '
& $string($number($body('request').unit_price)) & ' '
& $uppercase($body('request').currency)
}
Request body:
{
"order_id": "ORD-1001",
"customer_name": "ada lovelace",
"qty": "3",
"unit_price": "12.50",
"currency": "usd",
"status": "paid"
}
HTTP/2 200
{"orderId":"1001","customerName":"ADA LOVELACE","quantity":3,"unitPrice":12.5,"total":37.5,"totalWholeUnits":37,"currency":"USD","isPaid":true,"display":"3 x 12.5 USD"}
$number() coerces to a number and $string() goes back. & joins strings, not +. status = 'paid' gives a real JSON boolean. unit_price went in as "12.50" and came out as 12.5. A missing field drops the property from the output and does not fail.
Example 5: a pricing rule
Clamp a quantity to 1..100 and price it. $min and $max take an array, not two arguments:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"requestedQty": $number($body('request').qty),
"effectiveQty": $max([$min([$number($body('request').qty), 100]), 1]),
"clamped": $max([$min([$number($body('request').qty), 100]), 1]) != $number($body('request').qty),
"segment": $uppercase($body('request').segment),
"gross": $max([$min([$number($body('request').qty), 100]), 1]) * $number($body('request').unitPrice),
"grossRounded": $floor($max([$min([$number($body('request').qty), 100]), 1])
* $number($body('request').unitPrice) * 100 + 0.5) / 100,
"floorExample": $floor(9.999)
}
Request body:
{ "qty": 250, "unitPrice": 9.99, "segment": "gold" }
HTTP/2 200
{"requestedQty":250,"effectiveQty":100,"clamped":true,"segment":"GOLD","gross":999,"grossRounded":999,"floorExample":9}
I rounded to cents with $floor(x * 100 + 0.5) / 100, and wrote the clamp out each time it was needed.
Example 6: normalise query parameters
Get the query parameters once and use them as the context. Each field is then read by name:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
$queryParameters('request') . [
{
"q": $lowercase(q),
"qLength": $length(q),
"limit": $max([$min([$number(limit), 50]), 1]),
"exact": $boolean(exact),
"page": $number(page),
"hasPage": $exists(page),
"pageSuppliedAs": page,
"queryParameters": $
}
]
The outputs below came from my first version, which called $queryParameter('request', ...) once per field. They have not been re-run against this version.
curl ... "https://<gateway-host>/1.0.0/nano-jsonata/search?q=Ada%20Lovelace&limit=500&exact=true"
HTTP/2 200
{"q":"ada%20lovelace","qLength":14,"limit":50,"exact":true,"hasPage":false,"queryParameters":[{"q":"Ada%20Lovelace"},{"limit":"500"},{"exact":"true"}]}
Four things to read from that:
limit=500became50.$numbercoerced it and$min/$maxclamped it.pagewas not sent, sopageandpageSuppliedAsare missing from the output. Object construction drops anything that is nothing.hasPageshows it.$queryParameterdoes not URL-decode.Ada%20Lovelacestaysada%20lovelaceand the length is 14, not 12. A+stays a+.$queryParametersreturns an array of single-key objects. With one parameter it returned a plain object instead:"queryParameters":{"q":"a"}. Code that reads it needs to cope with both shapes.
$boolean applies JSONata truthiness to the string, so exact=false is also true:
curl ... "https://<gateway-host>/1.0.0/nano-jsonata/search?q=Ada+Lovelace&limit=500&exact=false"
{"q":"ada+lovelace","qLength":12,"limit":50,"exact":true,"hasPage":false,"queryParameters":[{"q":"Ada+Lovelace"},{"limit":"500"},{"exact":"false"}]}
Leave parameters out and the behaviour is uneven. With only q=a, limit came back as 50, because the clamp turned a missing number into the maximum, and exact was dropped. With no q, the call returned:
HTTP/2 500
Internal Server Error
A missing q fails the whole operation, even though the other fields would have been fine.
Example 7: path parameters
$pathParameters() returns all the template variables. As in Example 6, use it as the context and read each one by name:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
$pathParameters() . [
{
"tenant": tenant,
"normalized": $lowercase(tenant),
"region": $substringAfter(tenant, '-'),
"isEu": $lowercase($substringAfter(tenant, '-')) = 'eu',
"routeKey": 'tenant-' & $lowercase(tenant),
"method": $httpMethod('request'),
"pathParameters": $
}
]
The outputs below came from my first version, which called $pathParameter('tenant') for every field. They have not been re-run against this version.
curl ... "https://<gateway-host>/1.0.0/nano-jsonata/tenant/acme-eu/config"
HTTP/2 200
{"tenant":"acme-eu","normalized":"acme-eu","region":"eu","isEu":true,"routeKey":"tenant-acme-eu","method":"GET","pathParameters":{"tenant":"acme-eu"}}
Like query parameters, path parameters are not URL-decoded. A call to /tenant/ACME%2Deu/config returned:
{"tenant":"ACME%2Deu","normalized":"acme%2deu","region":"ACME%2Deu","isEu":false,"routeKey":"tenant-acme%2deu","method":"GET","pathParameters":{"tenant":"ACME%2Deu"}}
$substringAfter found no -, so region is the whole string and isEu is wrong.
Example 8: base64
The message body is expensive to copy, so read it once and use it as the context:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
$body('request') . [
{
"decoded": $base64decode(envelope),
"decodedLength": $length($base64decode(envelope)),
"reencoded": $base64encode($base64decode(envelope)),
"roundTrips": $base64encode($base64decode(envelope)) = envelope,
"contentType": $bodyType('request'),
"prefix": $substring($base64decode(envelope), 0, 7)
}
]
The output below came from my first version, which called $body('request') for every field. It has not been re-run against this version.
Request body:
{ "envelope": "eyJvcmRlcklkIjoiT1JELTEwMDEifQ==", "encoding": "base64" }
HTTP/2 200
{"decoded":"{\"orderId\":\"ORD-1001\"}","decodedLength":22,"reencoded":"eyJvcmRlcklkIjoiT1JELTEwMDEifQ==","roundTrips":true,"contentType":"Parsed_JSON","prefix":"{\"order"}
decoded is a string. roundTrips is true because encoding the decoded value gave the original back.
Example 9: pass a value between policies
A set policy stores a variable once. Every later policy reads it with $variable.
kind: Set
spec:
valueType: jsonata
variable:
name: tenant
value: $lowercase($body('request').tenant)
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"tenant": $variable('tenant'),
"greeting": 'hello ' & $uppercase($variable('tenant')),
"requestedBy": $body('request').user,
"isEu": $substringAfter($variable('tenant'), '-') = 'eu'
}
Request body:
{ "tenant": "ACME-EU", "user": "ada" }
HTTP/2 200
{"tenant":"acme-eu","greeting":"hello ACME-EU","requestedBy":"ada","isEu":true}
The first policy lowercased ACME-EU, the second read it back.
Example 10: raise an error from a guard
$error raises a policy error, and the backend is never called. The guard is a switch case with a JSONata condition. The case runs a set whose whole expression is $error(...):
kind: Switch
spec:
cases:
- condition: $exists($body('request').amount) and $number($body('request').amount) < 0
execute:
- $ref: nanogw-policy-samples:nano-jsonata-error-amount:1.0.0
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: $error('amount must be greater than zero')
When the case does not match, the normal set runs:
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
{
"amount": $number($body('request').amount),
"accepted": true,
"message": 'amount accepted'
}
curl ... -X POST -H 'Content-Type: application/json' -d '{"amount":-5}' "https://<gateway-host>/1.0.0/nano-jsonata/errors/policy"
HTTP/2 500
Internal Server Error
curl ... -X POST -H 'Content-Type: application/json' -d '{"amount":10}' "https://<gateway-host>/1.0.0/nano-jsonata/errors/policy"
HTTP/2 200
content-type: application/json
{"amount":10,"accepted":true,"message":"amount accepted"}
The caller sees a plain 500 and the canonical text. The message you passed to $error is not in the response.
Example 11: a path that matches nothing
kind: Set
spec:
valueType: jsonata
messageBody:
messageName: response
value: |
$body('request').customer.id
The request body is {"present": 1}. There is no customer, so the expression has no result:
HTTP/2 500
Internal Server Error
A bare path that selects nothing fails the whole operation.
Summary
valueType: jsonatagoes on thesetpolicy, not on the variable or the message.- Request data came through
$body('request')and friends. A bare field name read the message the expression writes to. - Query and path parameters arrived as sent, with no URL decoding.
- Read
$body,$queryParametersand$pathParametersonce and use the result as the context, instead of calling the function for every field. - A path that selects nothing returned a
500. $errorreturned a plain500with no message.
Limitations and Notes
- Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
- The function lists above are for Nano Gateway 1.2. Check them against the version you run.
- Examples 3, 6, 7 and 8 were rewritten after review. The responses shown are from the earlier versions, so re-run the new expressions before publication. Examples 3, 7 and 8 should return the same values, because only the plumbing changed. Example 6 is the one whose response shape may change: its earlier output shows
$queryParametersreturning an array of single-key objects when several parameters are present, and the rewrite reads the fields from that value as a single context. Confirm the shape when you re-run.
