Parse turns bytes into a document. Set rewrites the message. Handlebars turns a document back into text. This post runs all three against a real gateway, with the YAML from API Studio code view and the response that came back.

The JSONata post already uses set with valueType: jsonata in every example. This one covers the parts that post does not: the Parse options, the method and URI targets, the literal default and Handlebars.

The test project

One API Studio project, one API called nano-message, one operation per example. There is no backend. A set or Handlebars policy builds each response.

ExtractIdentity, Authenticate and Authorize check client credentials, then an OperationSwitch sends each operation to its own policies.

Every call goes to the published product URL with the client credentials of a subscribed application:

curl -s -X POST -H 'Content-Type: application/json' \
  -H "X-IBM-Client-Id: <client-id>" \
  -H "X-IBM-Client-Secret: <client-secret>" \
  -d '{"order":{"id":"ORD-1001","customer":"ada lovelace","total":37.5}}' \
  "https://<product>-<catalog>-<org>.nanogw.<ingress-domain>/1.0.0/nano-message/parse/json"

Example 1: parse JSON

Without a parse, every JSONata expression sees the body as an opaque value. This is the first policy in almost every POST assembly:

kind: Parse
spec:
  input: request
  documentType:
    json: {}

input names the message to parse. With no output, the parsed document replaces the body of that message, so $body('request') is the document from then on. Set output: parsed to keep the original body and read the document as $body('parsed'). I used the first form.

A set then uses real types: a string function on a string and arithmetic on a number.

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "orderId": $body('request').order.id,
        "customer": $uppercase($body('request').order.customer),
        "doubled": $body('request').order.total * 2
      }

Request body:

{ "order": { "id": "ORD-1001", "customer": "ada lovelace", "total": 37.5, "lines": [1, 2, 3] } }
HTTP/2 200

{"orderId":"ORD-1001","customer":"ADA LOVELACE","doubled":75}

documentType.json also takes maxDepth, maxDocumentSize, maxNameLength, maxValueLength, maxWidth and maxNumberLength. I did not test them. They are the limits to set on an API that accepts documents from the internet.

A body that is not JSON fails at the parse:

HTTP/2 400

Bad Request

Example 2: choose the parser from the Content-Type

detectByContentType picks the parser from the message’s Content-Type header:

kind: Parse
spec:
  input: request
  documentType:
    detectByContentType: {}
curl ... -X POST -H 'Content-Type: application/json' -d '{"probe":"value","n":7}' \
  "https://<gateway-host>/1.0.0/nano-message/parse/detect"
HTTP/2 200

{"contentType":"application/json","probe":"value","parsedAs":"json"}

detectByPayload sniffs the first bytes of the body instead and ignores the header. I did not test it.

parsedAs is a fixed string in my set policy, so it proves nothing. The useful part is that probe was read from the body. Now the same operation with Content-Type: text/plain and the body hello:

HTTP/2 200

{"contentType":"text/plain; charset=UTF-8","parsedAs":"json"}

There was no error. probe is simply missing, because the body was not parsed into an object. A policy that needs an object fails or drops fields when the content type is not one you expected. It does not return a 415.

The accepted documentType values are json, binary, detectByContentType and detectByPayload. There is no XML parser. From my project notes, documentType: xml is rejected by apic lint. I did not re-run that.

Example 3: binary bodies

documentType: binary tells the runtime not to interpret the body:

kind: Parse
spec:
  input: request
  documentType:
    binary:
      maxDocumentSize: 1048576

maxDocumentSize is the only limit this variant takes.

JSONata cannot read the result. From my project notes, $body('request') returns nothing and any expression that touches it fails with [T0410] Must be a string. I did not re-run that. A Lua script can read it, because body:read() returns a Buffer:

kind: LuaScript
spec:
  source: |
    local req = context:get_message('request')
    local resp = context:create_message('response')

    local buf = req.body:read()

    resp.body:write({
      bodyType = 'binary',
      bytes = #buf,
      text = buf:tostring(),
    })
curl ... -X POST -H 'Content-Type: application/octet-stream' \
  -d '{"note":"binary documents arrive as a base64 string"}' \
  "https://<gateway-host>/1.0.0/nano-message/parse/binary"
HTTP/2 200

{"bodyType":"binary","bytes":53,"text":"{\"note\":\"binary documents arrive as a base64 string\"}"}

#buf is the byte count. buf:tostring() copies the payload into a Lua string, which is only safe when the payload is text. For a real binary format keep the Buffer and use its integer readers, such as readu8(offset). The Lua post covers the rest of the Lua surface.

Example 4: rewrite the method and URI

set is not only for bodies. messageMethod and messageUri change the request that the rest of the assembly sees. Later policies, invoke and the backend see the change. The route was already matched, so the caller’s URL does not change.

kind: Set
spec:
  messageMethod:
    messageName: request
    method: PUT

A set carries one target only: messageBody, messageHeader, messageMethod, messageUri or variable. Rewriting both the method and the URI takes two policies:

kind: Set
spec:
  messageUri:
    messageName: request
    nameType: plain
    path: /set/method
    queryParams:
      - name: rewritten
        value: 'yes'

path plus a list of queryParams replaces the query parameters as a set. A third set reads the result back:

kind: Set
spec:
  valueType: jsonata
  messageBody:
    messageName: response
    value: |
      {
        "method": $httpMethod('request'),
        "rewrittenParam": $queryParameter('request', 'rewritten')
      }
curl ... -X POST -H 'Content-Type: application/json' -d '{"orderId":"ORD-1001"}' \
  "https://<gateway-host>/1.0.0/nano-message/set/method"
HTTP/2 200

{"method":"PUT","rewrittenParam":"yes"}

The caller sent a POST and the assembly saw a PUT. There was no rewritten parameter on the incoming call.

Both fields accept valueType: jsonata. With that, method: $body('request').wantedVerb would forward a verb chosen by the caller. I used the plain form on purpose.

From my project notes, on 12.1.1 $relativeUrl('request') comes back empty after a messageUri rewrite, while $httpMethod and $queryParameter see the change. I did not re-run that. Log $relativeUrl before the rewrite.

Example 5: a literal body

The default valueType of set is a literal. A body written without valueType: jsonata is sent as text:

kind: Set
spec:
  messageBody:
    messageName: response
    value: '{"note": "this text was NOT evaluated: $uppercase(''x'')", "literal": true}'
curl ... -X POST -H 'Content-Type: application/json' -d '{"anything":true}' \
  "https://<gateway-host>/1.0.0/nano-message/set/literal"
HTTP/2 200

{"note": "this text was NOT evaluated: $uppercase('x')", "literal": true}

The $uppercase('x') came back as written. Add valueType: jsonata directly under spec and the same value is evaluated as an expression. This is the most common silent failure with set. The status is 200 and the body is just wrong.

Example 6: Handlebars

HandlebarsTemplate renders a template into a message body or a variable. Use it to answer with text, HTML or CSV.

kind: HandlebarsTemplate
spec:
  input:
    - message: request
  template: 'Order {{message.body.order.id}} for {{message.body.order.customer}} totals {{message.body.order.total}} ({{message.method}} {{message.uri}})'
  destination:
    messageBody:
      message: response

input is a list of objects. message: request exposes {{message.body}}, {{message.headers}}, {{message.method}} and {{message.uri}}. variables: [name] exposes assembly variables as {{variables.name}}.

{{message.body.order.id}} only works because a parse ran first. A set adds a Content-Type, because the template does not set one:

kind: Set
spec:
  messageHeader:
    action: set
    headerName: Content-Type
    messageName: response
    value: 'text/plain'
curl ... -X POST -H 'Content-Type: application/json' \
  -d '{"order":{"id":"ORD-1001","customer":"ada lovelace","total":37.5}}' \
  "https://<gateway-host>/1.0.0/nano-message/handlebars/render"
HTTP/2 200
content-type: text/plain

Order ORD-1001 for ada lovelace totals 37.5 (POST /1.0.0/nano-message/handlebars/render)

message.uri is the full path as the gateway sees it, including the version and API base path.

A missing field is not an error. Send {"x":1} and the template renders blanks:

HTTP/2 200
content-type: text/plain

Order  for  totals  (POST /1.0.0/nano-message/handlebars/render)

From my project notes, a template with no input also renders blanks, and declaring a text/plain response schema in the OpenAPI document stops the runtime from loading the API. I did not re-run either. Describe the text response in prose.

Summary

  • Put a parse in front of anything that reads the body. A body that fails to parse is a 400.
  • set is a literal until valueType: jsonata is set under spec. Check the body, not the status.
  • One set carries one target, so a method rewrite and a URI rewrite are two policies.
  • Handlebars renders blanks for anything it cannot find. Test the missing-field case.

Limitations and Notes

  • Tested on a DataPower Nano Gateway with the API Connect 12.1 documentation set. Check the version you run.
  • Not tested: output on parse, detectByPayload, the size and depth limits, variables as Handlebars input, and jsonata in messageMethod or messageUri.
  • The binary example sends text with an application/octet-stream header. I did not send real binary data.
  • The Nano Gateway only validates JSON schemas, so keep OpenAPI response schemas to JSON media types.