Composing one API from several backends¶
How-to guideThe steps for one task.
A caller asks for an order and wants the customer and the shipping status with it, but those
live in three different services. The service-callout policy calls the other backends during
the request and leaves each answer in a named slot; the transform policy you already know
then writes the final body from the backend's answer and the slots. No backend-for-frontend
service to write, run and keep up.
The orders example¶
The API's main backend is the orders service. After it answers, the gateway calls the customers service (with the customer id from the order), the shipping service (with the order id from the path) and, once the customer is known, the loyalty service (with the customer's tier).
apiVersion: apinx/v1
kind: API
name: orders
base_path: /orders
upstream: orders-service
strip_prefix: true
policies:
- type: service-callout
config:
deadline: 3s # wall clock for all callouts of one request
secrets:
customers_key: env:CUSTOMERS_KEY # sealed at rest; ${secret.customers_key} below
callouts:
- name: customer
url: https://customers.internal/v1/customers/${response.body.customer_id}
headers:
X-API-Key: ${secret.customers_key}
timeout: 800ms
retries: 1
- name: shipping
url: https://shipping.internal/v1/shipments?order=${path.id}
optional: true # the order is still served without it
- name: loyalty
url: https://loyalty.internal/v1/tiers/${callout.customer.body.tier}
after: [customer] # runs once customer answered; shipping runs alongside
- type: transform
config:
response:
body:
program: |
{
order: .body,
customer: (.callouts.customer.body | {id, name, email}),
shipping: (.callouts.shipping.body // {status: "unknown"}),
tier: .callouts.loyalty.body.tier
}
operations:
- name: one
path: /{id}
methods: [GET]
customer and shipping run in parallel; loyalty starts when customer has answered. The
caller waits for the slowest branch, not for the sum.
What the caller gets¶
{
"order": {"id": "o-7", "customer_id": "c-42", "total": 99.5},
"customer": {"id": "c-42", "name": "Ada", "email": "ada@example.com"},
"shipping": {"status": "in transit"},
"tier": "gold"
}
What a slot holds¶
In jq programs, .callouts.<name> is:
{"ok": true, "status": 200, "headers": {"Content-Type": "application/json"},
"body": {"id": "c-42", "name": "Ada", "tier": "gold"}, "duration_ms": 37.4, "cached": false}
body is the parsed JSON, a string when the answer is not JSON, null when it is empty. A failed
callout has ok: false and an error such as APX-PL-0028: status 503; one that never ran (a
dependency failed, the deadline passed) has error: "skipped". In header, path and query values
the same facts are references: ${callout.customer.body.tier}, ${callout.customer.status},
${callout.customer.header.Content-Type}.
The callouts also see the backend's answer: ${response.status}, ${response.header.<Name>}
and ${response.body.<field>} (dotted for nested fields), and in a body_program the document
transform's response program sees, plus callouts.
Before the backend: look something up¶
A callout can run before the main backend is called, to shape the request or refuse it. The
policy's own set_headers and reject make that useful without a transform:
policies:
- type: service-callout
config:
callouts:
- name: tenant
url: https://tenants.internal/v1/tenants/${header.X-Tenant}
when: before
cache_ttl: 1m # the same tenant is not looked up on every call
set_headers:
X-Tenant-Plan: ${callout.tenant.body.plan}
reject:
- if: .callouts.tenant.body.suspended
status: 403
message: This tenant is suspended
The backend receives X-Tenant-Plan; a suspended tenant is refused with 403 APX-PL-0031 and
the backend is never called. Transform's request rules see before-phase slots too.
Answer from the callouts alone¶
Sometimes there is no main backend: the answer is the composition. A dashboard that gathers a
customer, their last orders and their open shipments has nothing of its own to call. With
respond, the policy composes the answer from the callouts, and the operation needs no
upstream.
apiVersion: apinx/v1
kind: API
name: dashboard
base_path: /dashboard
strip_prefix: true
policies:
- type: api-key
operations:
- name: summary
path: /{customer}
methods: [GET]
policies:
- type: service-callout
config:
deadline: 3s
callouts:
- name: customer
url: https://customers.internal/v1/customers/${path.customer}
when: before
fields: [id, name, tier] # the rest of the answer never enters the slot
- name: orders
url: https://orders.internal/v1/customers/${path.customer}/orders?limit=5
when: before
- name: shipping
url: https://shipping.internal/v1/customers/${path.customer}/open
when: before
optional: true
respond:
status: 200
program: |
{
customer: .callouts.customer.body,
recent_orders: .callouts.orders.body,
open_shipments: (.callouts.shipping.body // [])
}
- Every callout runs before. There is no backend to run after, so
when: afteris refused at save with the callout named.afterstill orders the callouts among themselves, andrejectrules still run before the answer is composed. - The default body is one member per callout. Without a
programthe answer is a JSON object with a member per callout, named after it, holding the answer's body:{"customer": {…}, "orders": […], "shipping": null}. A failed optional callout givesnull. programis a jq program whose single output, as JSON, is the body. Its input is the request document the transform policy's request program sees (.method,.path,.params,.query,.body,.principal) plus.callouts. A program that fails or produces nothing answers502 APX-PL-0032, never a partial body.fieldskeeps only the listed top-level members of a JSON object answer; the rest is dropped before the slot is filled, so a program and the trace never see it. It works on any callout, with or withoutrespond.X-Apinx-Completedon the answer says whether every callout succeeded:falsewhen an optional callout failed, so a client can tell a partial answer from a full one.status(200),content_type(application/json) andheaders(references allowed) shape the rest of the answer.- Required and optional failures keep their meaning: a required callout that fails answers
the caller with the gateway's coded
502 APX-PL-0028,504 APX-PL-0029or502 APX-PL-0030; an optional one leavesok: falsein its slot and the program decides, asshippingdoes above. - No upstream. The deploy check accepts an operation without a backend once a
service-calloutwithrespond(or amock-response) is bound; the operation editor's Backend shows None (answered by a policy). An operation with neither is refused.
Chaining¶
after names the callouts of the same phase that must finish first. Any order without cycles is
accepted; the gateway runs each level in parallel and the next level when the previous one
finished. One level of composition only: a callout cannot itself run callouts, and a callout to
an Apinx API that makes callouts is refused as a loop (508 APX-RT-0009; callouts carry the
X-Apinx-Callout header). A value expanded into a callout's path stays in its own segment:
/ and .. are escaped, so a caller cannot steer a callout to another path on the backend.
When a backend fails¶
- A required callout that fails answers the caller with the gateway's own coded error and
never a body with a hole in it:
502 APX-PL-0028(connection error, unexpected status),504 APX-PL-0029(its timeout or the policy's deadline),502 APX-PL-0030(an answer larger thanmax_bytesor undecodable). - An optional callout leaves
ok: falsein its slot and the request goes on; the program decides, asshippingdoes above with// {status: "unknown"}. expectsays which statuses count as success (2xxby default;[2xx, 404]when a 404 is an answer, not a failure).retriesrepeats GET, HEAD and OPTIONS on a connection error, a timeout or a 5xx, up to 3 times. Other methods are never retried.- By default the after phase runs only when the backend answered below 400;
run_after_on: alwaysruns it on every answer. It never runs on the gateway's own errors.
What the trace shows¶
Every callout is a row in the request's trace: its name, phase, method, URL (without the query),
status, duration, attempts and whether it came from the cache. The access log carries callouts
(how many) and callout_ms (the time the request waited in callout phases), so
duration_ms − upstream_ms − callout_ms is the gateway's own time. Prometheus has
apinx_callout_total and apinx_callout_duration_seconds by API, callout and outcome. No
callout body or header is ever stored.
Previewing before you deploy¶
The transform editor's Preview against a sample shows one pretend answer per callout bound beside it. Set the status and body each would have returned and run the preview: the stitched body and the inspector steps appear without a single call leaving the gateway.
Apinx Cloud¶
The plan caps callouts per request and the policy's deadline: two callouts and two seconds on
Free, ten and ten seconds on Enterprise. A policy with more callouts, or an explicit deadline over
the cap, is refused at deploy; an unset deadline is simply held to the cap. Callout URLs pass the
same egress guard as upstreams, so the platform's own network, and Apinx Cloud's own addresses,
cannot be called. On premises proxy.callouts.max_per_request and proxy.callouts.max_deadline
in the configuration file set the same caps, unlimited by default.
Cost¶
A route without the policy pays nothing: the policy is simply not in its chain. With it, the
request waits for the callouts' wall clock, which the trace and callout_ms show. The gateway's
own work per callout, building the request, expanding references, parsing the answer, is
measured in ADR-0032:
about 10 µs and 146 allocations per callout on a loopback bench with a 300-byte JSON answer;
JSON parsing dominates as answers grow (about 30 µs at 1 KB, 2.7 ms at 100 KB). Answers are buffered up to max_bytes (1 MB) each, parsed once and shared with the
transform policy.