Skip to content

Transforming requests and responses

How-to guideThe steps for one task.

The transform policy rewrites headers, path, query, status and JSON bodies. set-header is its small sibling for fixed headers. Both run in the transformation phase, after authentication and limits.

Headers

policies:
  - type: transform
    config:
      request:
        headers:
          set:
            X-Tenant: ${claim.tenant}          # from the caller's token
            X-Request-Source: apinx
          add:
            Via: apinx                        # keeps existing values
          remove: [Cookie]
          rename: { X-Legacy-Id: X-Id }
      response:
        headers:
          remove: [X-Powered-By, Server]
          set: { X-Served-By: apinx }

Values may use references: ${path.<param>}, ${header.<Name>}, ${query.<name>}, ${principal.id}, ${principal.name}, ${claim.<name>}, ${client_ip}, ${host}. A header whose reference is empty on a request is left out.

Path and query

config:
  request:
    path:
      strip_prefix: /public
      add_prefix: /v2
      replace:
        pattern: ^/users/([0-9]+)$
        with: /accounts/$1
    query:
      set: { api-version: "2" }
      remove: [debug]

Path rewriting applies after the API's own strip_prefix, in the order strip, add, replace.

Changing the method

A mobile client may prefer to POST a JSON body where the backend serves the same thing on GET with query parameters. request.method forwards the request with another method, and ${body.<field>} lifts fields out of a JSON request body (dotted for nested fields):

config:
  request:
    method: GET
    query:
      set:
        pageNumber: ${body.pageNumber}
        pageSize: ${body.pageSize}
        dept: ${body.filter.dept}

GET and HEAD carry no body, so the client's body is dropped once its fields have been moved. Referencing ${body.…} buffers the body like a program does, within the same max_bytes. Other methods keep the body (a body program, if bound, has already reshaped it).

Bodies with jq

Body programs are jq expressions over a document:

{ body, headers, header_values, method, path, query, params, principal, status }
config:
  response:
    body:
      program: |
        {
          id: .body.id,
          title: .body.title,
          author: .body.userId,
          links: { self: ("/posts/" + (.body.id|tostring)) }
        }

Rules that keep this safe:

  • Bodies are buffered only on operations that bind a body program or a status condition, up to max_bytes (1 MB) and within time_budget (50 ms). A body over the limit or a failing program never forwards a partial result: 413 or 400 on the request side, 502 APX-PL-0014 on the response side.
  • A program is held to what a body transformation needs. It sees its own request and nothing else: no environment, no files, no network, no other request. It is at most 256 KB of text and 5,000 levels of nesting (brackets, or operators in one chain). It cannot build a value over four times max_bytes, recurse without end (its own call stack stops at the same size, 4 MB at least), or return a value nested deeper than 10,000 levels, the deepest JSON itself goes. A program that does fails like any other failing program, and the trace says which limit it met.
  • time_budget holds for single calls too. A call whose worst case cannot finish in the time the program has left is refused before it starts, as over the budget: a sort or a comparison of values that repeat one large array, indices, contains or array subtraction on large arrays, test, match or gsub with a wide counted repeat such as {1,1000} on a long string. A regular expression in a program is at most 32 KB and 5,000 characters' worth once its counted repeats are written out. Ordinary calls on a body of the default size are far inside the budget; a program that meets this on real data can raise time_budget.
  • A program is held to what it returns and to what it holds. Its output, written out as JSON, takes at most four times max_bytes, or twice its input when that is more: an output that repeats one array thousands of times is refused before it is written. What a program holds in memory at once, its input and everything it has built and still uses, is at most 128 times max_bytes (128 MB by default; 16 MB at least and 512 MB at most). A program that keeps large strings or copies of an array in a list meets this; one that grows a text or an object step by step does not, since each step lets the one before go. A global match, scan or gsub that would build more matches and captures than fit is refused before it builds any. In Apinx Cloud the programs of one organization may together hold four times what one may; when they do, a request is answered 503 APX-PL-0040 with Retry-After, and fits a moment later.
  • A body that is not JSON passes through untouched (if_not_json: pass) or is refused.
  • The Develop tab's editor has Preview against a sample: paste a request and a backend answer and see the reshaped bodies, the status and the steps, before deploying.

Reading callout slots

When a service-callout policy is bound beside the transform, the document also carries callouts: one entry per callout, {ok, status, headers, body, duration_ms, cached, error}, on both legs for callouts that ran before the backend and on the response leg for the rest. The response program stitches them in:

config:
  response:
    body:
      program: |
        {
          order: .body,
          customer: .callouts.customer.body,
          shipping: (.callouts.shipping.body // {status: "unknown"})
        }

Header, path and query values read the same facts with ${callout.<name>.body.<field>}, ${callout.<name>.status} and ${callout.<name>.header.<Name>}. The preview offers one pretend answer per callout. See Composing one API from several backends.

Status rules

config:
  response:
    status:
      map: { "502": "503" }                     # remap
      when:                                     # ordered conditions on the response document
        - if: .body.error == "not_found"
          status: 404
      # set: 200                                # force, applied last

normalize-errors then shapes the body for the resulting status.

Compressing responses

The compress policy sends a response out gzip- or brotli-encoded when the caller's Accept-Encoding allows it. It is not on by default: add it to an API whose answers are large JSON, XML or text, and the client's download shrinks to a fifth or less.

policies:
  - type: compress
    config:
      encodings: [gzip, br]        # offered in this order; the caller gets the first it accepts
      min_bytes: 1KB               # shorter bodies go out as they are
      content_types: [application/json, text/]   # matched by prefix; the default list covers JSON, XML, text and SVG
      level: default               # fast, default or best

What is left alone. A response the backend already encoded, a 204, 304 or partial (Content-Range) answer, a HEAD, a body under min_bytes, a media type outside the list, a response with Cache-Control: no-transform, and any caller that did not send Accept-Encoding or sent the encoding with q=0. The trace's compress step says which: gzip, br, or not compressed: … with the reason.

Streaming stays streaming. The body is compressed as it passes, on the request's own goroutine, and flushed whenever the backend pauses, so a newline-delimited JSON feed still arrives line by line. A body of unknown length is read up to min_bytes first to decide; one that ends before that goes out uncompressed with its length. Server-sent events are not in the default media types and should stay out.

With the cache. compress runs last on the response, after the cache stored the body, so the cache holds the uncompressed answer and serves every caller; a cache hit (and a mock) is compressed in memory for the callers that accept it. The response gets Vary: Accept-Encoding, loses its Content-Length, and a strong ETag becomes weak, since the bytes are no longer the backend's.

Cost. On a 12 KB JSON body, gzip at default takes about 5 µs and brotli about 13 µs per response on one core, with the compressors pooled; best costs several times that for a few percent more. The request inspector still shows the body: compressed previews are decoded for display.

Where to bind

  • API level for what every operation needs (identity headers, backend header hygiene).
  • Operation level for shape changes of one endpoint.
  • Use strategy: append on an operation to add a second transform without replacing the API's.

Cost

Header and path rules cost microseconds. Body programs cost the buffering and the jq run, bounded by the settings above; the trace shows the time of every transform step.