JSONata on the Nano Gateway is a small subset of the language on docs.jsonata.org. This post runs eleven patterns that work inside it, with the YAML from API Studio code view and the response the gateway returned.

The companion posts cover the invoke policy, the switch policy and the Lua Script policy. Where an example hits a JSONata limit, the Lua post has the other half.

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 it out and you get the expression as literal text. The message post shows that happening.

One more rule changes how every expression is written. 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').

What the runtime supports

The reference page lists the supported functions. I used these as well, and they are not on that page: $substring, $substringBefore, $substringAfter, $min and $max. All five worked on my gateway. Treat them as undocumented until the page catches up.

Family Functions used here
String $string $length $uppercase $lowercase $contains $substring $substringBefore $substringAfter
Encoding $base64encode $base64decode
Numeric $number $floor $min $max
Boolean $boolean $exists
Error $error
Context $body $bodyType $header $httpMethod $path $pathParameter $pathParameters $queryParameters $queryParameter $relativeUrl $requestProperty $telemetry $variable $gtid $tid

Example 1: correlation IDs

Reuse the caller’s X-Correlation-Id, or make one. This is where the subset bites first. There is no ternary, so $header(...) ? $header(...) : $gtid() is not available. A conditional value is a policy decision, and the policy for the job is switch:

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.

clientAddr is the router’s address, not the caller’s, because the request came through the OpenShift route. The documentation says $telemetry cannot return catalog_name when you configure fields through OpenTelemetry. I got sandbox back here, so that restriction did not apply to my setup.

Example 3: inspect a bearer token

The gateway has no $split, so JWT segments are pulled out with $substringAfter and $substringBefore:

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "scheme": $substringBefore($header('request', 'Authorization'), ' '),
        "isBearer": $contains($header('request', 'Authorization'), 'Bearer '),
        "tokenLength": $length($substringAfter($header('request', 'Authorization'), 'Bearer ')),
        "jwtHeaderSegment": $substringBefore(
          $substringAfter($header('request', 'Authorization'), 'Bearer '), '.'),
        "jwtPayloadSegment": $substringBefore(
          $substringAfter($substringAfter($header('request', 'Authorization'), 'Bearer '), '.'),
          '.')
      }
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 is inspection, not validation. JSONata cannot check an RSA or EC signature. Use the validate policy or an invoke to an auth service for that. Never make an authorisation decision from a token you only decoded.

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() is the coercion and $string() is the reverse. & joins strings, not +. status = 'paid' gives a real JSON boolean. Note unit_price went in as "12.50" and came out as 12.5. A missing field drops the property from the output. It 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}

Two limits show up here. There is no $round, so rounding to cents is $floor(x * 100 + 0.5) / 100. There are no variables inside an expression, so the clamp is written out four times. If an expression needs the same value more than twice, move it to a set policy variable (Example 9) or to Lua.

A segment-dependent discount cannot be written at all, because there is no conditional. Put switch cases on the segment, store the rate in a variable and read it here.

Example 6: normalise query parameters

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "q": $lowercase($queryParameter('request', 'q')),
        "qLength": $length($queryParameter('request', 'q')),
        "limit": $max([$min([$number($queryParameter('request', 'limit')), 50]), 1]),
        "exact": $boolean($queryParameter('request', 'exact')),
        "page": $number($queryParameter('request', 'page')),
        "hasPage": $exists($queryParameter('request', 'page')),
        "pageSuppliedAs": $queryParameter('request', 'page'),
        "queryParameters": $queryParameters('request')
      }
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=500 became 50. $number coerced it and $min/$max clamped it.
  • page was not sent, so page and pageSuppliedAs are missing from the output. Object construction drops anything that is nothing. hasPage is how you detect it. A default for a missing parameter belongs in a switch or set policy.
  • $queryParameter does not URL-decode. Ada%20Lovelace stays ada%20lovelace and the length is 14, not 12. A + stays a +.
  • $queryParameters returns 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"}]}

Compare the string to 'true' instead: $queryParameter('request', 'exact') = 'true'.

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. I did not isolate which function raised it. Guard required parameters with a switch before the expression runs.

Example 7: path parameters

$pathParameter reads a template variable.

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "tenant": $pathParameter('tenant'),
        "normalized": $lowercase($pathParameter('tenant')),
        "region": $substringAfter($pathParameter('tenant'), '-'),
        "isEu": $lowercase($substringAfter($pathParameter('tenant'), '-')) = 'eu',
        "routeKey": 'tenant-' & $lowercase($pathParameter('tenant')),
        "method": $httpMethod('request'),
        "pathParameters": $pathParameters()
      }
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"}}

routeKey is what a set policy would write to a header for the backend, or what an operation-switch would branch on.

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. Keep tenant IDs to [a-z0-9-] in the contract.

Example 8: base64

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "decoded": $base64decode($body('request').envelope),
        "decodedLength": $length($base64decode($body('request').envelope)),
        "reencoded": $base64encode($base64decode($body('request').envelope)),
        "roundTrips": $base64encode($base64decode($body('request').envelope)) = $body('request').envelope,
        "contentType": $bodyType('request'),
        "prefix": $substring($base64decode($body('request').envelope), 0, 7)
      }

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. It looks like JSON but JSONata on this runtime cannot turn a string into a document, so $base64decode(...).orderId does not work. If you need the fields, decode in Lua with json.decode. roundTrips is a cheap check for non-canonical base64, such as missing padding.

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. Variables last for one request. For anything longer use the cache policy.

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. A 500 also looks like a gateway fault in client telemetry, so keep $error for contract violations. For an expected rejection with a real 4xx, use a switch that runs a return, or a throw policy.

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. Wrap it in an object and the property is dropped instead:

value: |
  { "customerId": $body('request').customer.id }

That returns {}. I did not run the wrapped version. It is the behaviour the object construction in Examples 4 and 6 already showed: a missing value drops the property.

Summary

  • Build the response with a set policy and valueType: jsonata on the policy, not on the variable or message.
  • Read request data through $body('request') and friends. A bare field name reads the message the expression writes to.
  • Conditional values are a policy decision. Use switch and store the result in a variable.
  • Query and path parameters arrive as sent. Decode them yourself.
  • Anything that needs a loop, a split, a clock or a mutable document belongs in the Lua Script policy.

Limitations and Notes

  • Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
  • $substring, $substringBefore, $substringAfter, $min and $max worked but are not on the supported functions page.
  • Not run for this post: a ternary, a lambda, a $name := value block and a function that the runtime does not implement. In my earlier testing on this project, each of these passed apic lint and publish, then stopped the whole API from starting (503, CrashLoopBackOff, with Invalid Token or Unrecognized Function in the pod log). Call every operation after you publish. A bad expression takes the whole API down, not one operation.
  • The reference page also lists $random and $telemetry span options. I did not test either.
  • I did not test the wrapped-object version in Example 11 or a missing Authorization header in Example 3.