YAML samples¶
ReferenceFacts to look up.
Every kind: API sample is a document you can paste into Develop → APIs → API → Code. The
kind: Gateway samples are parts of a whole configuration: import them with apinxctl import
and deploy with apinxctl publish, or paste one object at a time into the console's Code view
with apiVersion and kind on top (see
One object at a time). Fields are explained in
the gateway configuration reference and every policy setting
in the policy reference.
A public API¶
apiVersion: apinx/v1
kind: API
name: catalog
base_path: /catalog
upstream: catalog-service
strip_prefix: true
operations:
- name: all
path: /{rest...}
API key and a rate limit¶
apiVersion: apinx/v1
kind: API
name: orders
base_path: /orders
upstream: orders-service
strip_prefix: true
policies:
- type: api-key # X-API-Key header by default; the key is stripped
- type: rate-limit
config:
limit: 600
window: 1m # per consumer by default
operations:
- name: all
path: /{rest...}
- name: health
path: /health
policies:
- type: api-key
enabled: false # this operation is public
JWT from your identity provider¶
policies:
- type: jwt
config:
issuer: https://login.example.com/
jwks_url: https://login.example.com/.well-known/jwks.json
audiences: [orders-api]
required_scopes: [orders:read]
required_claims:
tenant: [acme, globex] # one of these values
employee_id: [] # present, any value
Keys are fetched and cached; the token is stripped before the backend and the subject is sent
as X-Apinx-Subject.
CORS for a browser app¶
policies:
- type: cors
config:
origins: [https://app.example.com]
methods: [GET, POST, PUT, DELETE]
headers: [Authorization, Content-Type]
credentials: true
max_age: 10m
Reshape the backend's answer with jq¶
operations:
- name: post-summary
path: /posts/{id}
methods: [GET]
policies:
- type: transform
config:
request:
headers:
set:
X-User-Id: ${claim.sub}
X-Request-Source: apinx
response:
headers:
remove: [X-Powered-By, Server]
body:
program: '{id: .body.id, title: .body.title, via: "apinx"}'
The Develop tab's transform editor has Preview against a sample that runs the program on the server before anything is deployed.
Stitch one answer from several backends¶
The orders service is the backend; the customers, shipping and loyalty services are called after it and their answers are written into one body (Composing one API from several backends).
apiVersion: apinx/v1
kind: API
name: orders
base_path: /orders
upstream: orders-service
strip_prefix: true
policies:
- type: service-callout
config:
deadline: 3s
secrets:
customers_key: env:CUSTOMERS_KEY
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
- name: loyalty
url: https://loyalty.internal/v1/tiers/${callout.customer.body.tier}
after: [customer]
- type: transform
config:
response:
body:
program: |
{
order: .body,
customer: (.callouts.customer.body | {id, name}),
shipping: (.callouts.shipping.body // {status: "unknown"}),
tier: .callouts.loyalty.body.tier
}
operations:
- name: one
path: /{id}
methods: [GET]
A lookup before the backend, with a refusal rule and a header for the backend:
policies:
- type: service-callout
config:
callouts:
- name: tenant
url: https://tenants.internal/v1/tenants/${header.X-Tenant}
when: before
cache_ttl: 1m
set_headers: { X-Tenant-Plan: "${callout.tenant.body.plan}" }
reject:
- if: .callouts.tenant.body.suspended
status: 403
message: This tenant is suspended
Cache responses for a minute¶
policies:
- type: cache
config:
ttl: 60s
vary_by_consumer: true # separate entries per caller
key_headers: [Accept-Language]
Responses carry X-Cache: HIT or MISS; purge an API or an operation with Purge cache on the API page.
With vary_by_consumer: true (the default) each caller has entries of its own: by the identity
the gateway authenticated, and by every credential the request carries on to your backend
(Authorization, Cookie, key and token headers), so a browser's cookies make its entries its
own. For answers that are the same for everyone, set vary_by_consumer: false: one entry then
serves every caller. The request headers your backend names in Vary are part of the key.
When many callers ask at the same moment for an entry that is not stored (a popular answer that
has just expired), one of them calls the backend and the others wait for that answer, at most
coalesce (2 s by default; coalesce: 0s turns it off). An answer that may not be stored
(Cache-Control: private, a cookie, an error) frees the waiting callers at once, and that
entry's callers do not wait for one another again for a while.
Threat protection¶
policies:
- type: threat-protection
config:
max_body_bytes: 1MB
json:
max_depth: 8
patterns:
in: [path, query, headers, body] # SQL, script, traversal and command injection
Take an operation offline¶
operations:
- name: legacy-export
path: /export
policies:
- type: deny
config:
status: 503
message: Retired; use /v2/export
Allow only your office and a partner¶
Per-consumer restrictions live on the application instead: Consumers → Allowed sources.
Two versions on one base path¶
# The gateway creates this for you from the Versions tab; shown here as it compiles.
apiVersion: apinx/v1
kind: API
name: orders-v2
family: orders
version: v2
base_path: /orders
upstream: orders-service-v2
selector:
header: Api-Version
value: v2
Calls with Api-Version: v2 reach orders-v2; every other call reaches orders.
A product with plans¶
apiVersion: apinx/v1
kind: Gateway
products:
- name: content
display_name: Content API
apis: [posts, comments]
plans:
- name: trial
display_name: Trial
quota: { limit: 200, period: day }
- name: partner
display_name: Partner
approval_required: true
rate_limit: { limit: 500, per: second }
quota: { limit: 1000000, period: month }
The gateway signs in to the backend for the app¶
The phone never holds the backend's credentials. It calls the gateway with its API key; the gateway signs in to the backend's own login endpoint with a service account configured here, keeps the JWT it gets back until shortly before it expires, and sends it to the backend on every request. The caller's identity still travels, in a header.
apiVersion: apinx/v1
kind: API
name: hr-mobile
base_path: /hr
upstream: hr-backend
strip_prefix: true
policies:
# 1. Who is calling: the app's key (Consumers → Applications). Stripped before the backend.
- type: api-key
- type: rate-limit
config: { limit: 100, window: 1m } # per application
# 2. The gateway's own session with the backend.
- type: upstream-auth
config:
token_url: https://hr.example.com/api/auth/login
request: json # the backend's login takes a JSON body
grant: password
username: svc-gateway # a service account, not a person
password: ${secret} # stored encrypted
token_field: accessToken # where the backend puts the token
expires_field: expiresIn # its lifetime in seconds; else the token's exp
refresh_before_percent: 20 # renew at 80% of the lifetime
refresh_token_field: refreshToken # renew with it when the backend gives one
refresh_url: https://hr.example.com/api/auth/refresh
headers:
X-App: ${principal.id} # which application is calling
operations:
- name: directory
path: /api/employees/{rest...}
methods: [GET]
What one call looks like:
GET /hr/api/employees/42withX-API-Key: …from the phone.api-keyfinds the application and removes the header;rate-limitcounts it.upstream-authhas no token yet: it posts{"username":"svc-gateway","password":"…"}to the backend's login, readsaccessToken,expiresInandrefreshTokenfrom the answer, and caches the token for 80% of its lifetime. Ten operations to the same backend share it; a burst of first requests makes one login, not ten. When the 80% are up, the next request posts{"refreshToken":"…"}to/api/auth/refreshand carries on with the new token; if the backend refuses the refresh, the gateway signs in with the credentials again.- The request reaches the backend as
GET /api/employees/42withAuthorization: Bearer <backend JWT>andX-App: mobile. - A
401from the backend discards the cached token; the next request signs in again. If the login endpoint is down and no token is cached, the caller gets502 APX-PL-0026, never a request without a token.
Trace it in Traffic: the step reads "token fetched from the backend's token endpoint" the first time and "cached token" after that.
With an OAuth 2 token endpoint¶
The same policy against a standard token endpoint, client credentials in HTTP Basic, the caller identified by a claim of its own JWT:
policies:
- type: jwt
config:
issuer: https://xxauth.example.com/
jwks_url: https://xxauth.example.com/.well-known/jwks.json
required_claims:
employee_id: []
- type: upstream-auth
config:
token_url: https://yyauth.example.com/oauth/token
client_id: gateway-xx
client_secret: ${secret} # stored encrypted
scopes: [employees:read]
headers:
X-User-Id: ${claim.employee_id}
grant: password with username and password is the resource-owner password grant against
the same kind of endpoint. See Authenticating to a backend.
A backend with health checks, a circuit breaker and retries¶
apiVersion: apinx/v1
kind: Upstream
name: orders-service
balancer: least_connections # round_robin (default), weighted, least_connections, consistent_hash
targets:
- url: http://10.0.1.10:8080
- url: http://10.0.1.11:8080
- url: http://10.0.1.12:8080
weight: 2 # weighted only
health:
active:
enabled: true
path: /healthz
interval: 10s
timeout: 2s
unhealthy_threshold: 3
healthy_threshold: 2
passive:
enabled: true
failures: 5 # consecutive 502/503/504 or connection errors
eject_for: 30s
circuit_breaker:
enabled: true
failure_threshold: 5
open_duration: 30s
half_open_requests: 1
retry:
attempts: 2
conditions: [connect_error, reset, "503"] # never on other 4xx/5xx; GET and HEAD only
methods: [GET, HEAD]
backoff: 50ms
max_backoff: 500ms
budget_ratio: 0.2 # at most 20% extra requests from retries
timeouts:
connect: 2s
response_header: 10s
total: 30s
A target the checks mark down, a target ejected by passive health and a target whose breaker is open all leave the rotation; the Overview and the Gateway map show each state.
Sticky sessions¶
apiVersion: apinx/v1
kind: Upstream
name: legacy-sessions
balancer: consistent_hash
hash:
source: cookie # header, cookie or ip
key: JSESSIONID
targets:
- url: http://10.0.2.10:8080
- url: http://10.0.2.11:8080
Requests with the same cookie reach the same target; a request without the cookie is spread round-robin. Removing a target moves only its own share.
Rewrite the path and map headers for a backend¶
operations:
- name: legacy-customers
path: /customers/{rest...}
policies:
- type: transform
config:
request:
path:
strip_prefix: /customers # whole segments only
add_prefix: /v3/crm/accounts
headers:
set:
X-Tenant: ${header.X-Org} # rename a header
Accept: application/json
remove: [X-Org, X-Debug]
query:
set: { source: gateway }
remove: [debug]
response:
headers:
remove: [Server, X-Powered-By]
set: { Cache-Control: no-store }
The backend sees /v3/crm/accounts/…; the client never learns the backend's layout.
Uploads: a size limit per content type¶
operations:
- name: photo-upload
path: /api/employees/{id}/photo
methods: [PUT]
policies:
- type: request-size-limit
config: { max_bytes: 100KB } # 413 before the backend reads a byte
- type: threat-protection
config:
max_body_bytes: 100KB # any other type
content_types:
image/jpeg: 100KB
image/png: 100KB
application/json: 4KB # a JSON body here is a mistake; keep it tiny
A body over the limit for its type is refused with 413 before the backend reads a byte.
A language header the app must send¶
policies:
- type: require-headers
config:
required:
Accept-Language: [ar, en] # present, and one of these; else 400 APX-PL-0027
operations:
- name: employee
path: /api/employees/{id}
policies:
- type: transform
config:
response:
body:
program: |
(.request_headers["Accept-Language"] // "" | ascii_downcase | startswith("ar")) as $ar
| .body
| .fullName = (if $ar then .fullNameAr else .fullName end)
| del(.fullNameAr)
- type: cache
config:
ttl: 5m
key_headers: [Accept-Language] # Arabic and English answers are different entries
A shared flow, adjusted by one API¶
apiVersion: apinx/v1
kind: Gateway
shared_flows:
- name: standard-security
policies:
- type: api-key
- type: rate-limit
config: { limit: 100, window: 1m }
- type: normalize-errors
apis:
- name: orders
base_path: /orders
upstream: orders-service
shared_flows: [standard-security]
policies:
- type: rate-limit
strategy: merge
config: { limit: 600 } # keeps the flow's window, raises the limit
- type: normalize-errors
enabled: false # off for this API only; the flow is unchanged
A flow hooked at the environment (previous sample) cannot be adjusted this way: it is enforced.
Login throttled per device, everything else per user¶
policies:
- type: jwt
config:
issuer: https://hr.example.com/
jwks_url: https://hr.example.com/.well-known/jwks.json
- type: rate-limit
config: { limit: 100, window: 1m } # key consumer: the token's subject
operations:
- name: login
path: /api/auth/login
methods: [POST]
policies:
- type: jwt
enabled: false # no token yet
- type: rate-limit
config:
limit: 10
window: 1m
key: ip
trust_x_forwarded_for: true # behind nginx or a CDN
Listeners and an upstream, as one configuration¶
apiVersion: apinx/v1
kind: Gateway
listeners:
- name: public
address: ":8080"
protocol: http
h2c: true
limits:
max_header_bytes: 64KB
read_header_timeout: 10s
idle_timeout: 60s
upstreams:
- name: orders-service
targets:
- url: https://orders.internal:8443
tls:
ca_file: /etc/apinx/ca.pem # a private CA
server_name: orders.internal
pass_host_header: false
Environment defaults and flow hooks¶
apiVersion: apinx/v1
kind: Gateway
policies: # global defaults, overridable per API
- type: normalize-errors
environment:
policies:
- type: request-size-limit
config: { max_bytes: 2MB }
flow_hooks: # administrators only; locked on every API
client: [standard-security]
backend: [audit-headers]
shared_flows:
- name: standard-security
policies:
- type: threat-protection
- type: cors
config: { origins: [https://app.example.com] }
- name: audit-headers
policies:
- type: set-header
config: { response: { X-Served-By: apinx } }
A WebSocket backend¶
routes:
- name: chat
path: /chat/{rest...}
upstream: chat-service
strip_prefix: true
websocket:
enabled: true
idle_timeout: 60s
max_duration: 1h # Apinx Cloud: at most the plan's (Free 1 h, Enterprise 24 h); 0s takes it
A gRPC backend¶
The backend is reached over HTTP/2 without TLS (grpc://), the base path is the service and
the prefix stays, since a gRPC client sends /package.Service/Method and cannot add anything
(gRPC services).
upstreams:
- name: greeter-grpc
targets:
- url: grpc://10.0.0.5:50051
timeouts: { total: 0s }
apis:
- name: greeter
base_path: /helloworld.Greeter
upstream: greeter-grpc
strip_prefix: false
routes:
- name: greeter-methods
api: greeter
path: /helloworld.Greeter/{method}
methods: [POST]
upstream: greeter-grpc
strip_prefix: false
A SOAP backend as a JSON operation¶
The caller sends {"orderId": "A-1001"}; the gateway builds the GetOrder envelope, posts it
to the service's one path and answers the decoded JSON, a fault as a coded error
(SOAP backends as JSON APIs).
routes:
- name: orders-get
api: orders
path: /orders/get
methods: [POST]
upstream: orders-soap
policies:
- type: soap
config:
version: "1.1"
action: urn:example:orders/GetOrder
endpoint_path: /soap/orders # the WSDL's address path, for every operation
namespaces: { ord: urn:example:orders }
request: |
<ord:GetOrder>
<ord:OrderId>${body.orderId}</ord:OrderId>
</ord:GetOrder>
response:
unwrap: GetOrderResponse/Order
arrays: [Line]
security: username_token
username: svc-gateway
password: env:ORDERS_SOAP_PASSWORD # sealed at rest; env:, file: or vault:
An operation with an array in the request, and the answer reshaped with jq:
- type: soap
config:
action: urn:example:orders/CreateOrder
endpoint_path: /soap/orders
namespaces: { ord: urn:example:orders }
request: |
<ord:CreateOrder>
<ord:Customer>
<ord:Name>${body.customer.name}</ord:Name>
<ord:Email>${body.customer.email}</ord:Email>
</ord:Customer>
<ord:Lines>
${each body.lines as line}
<ord:Line>
<ord:Sku>${line.sku}</ord:Sku>
<ord:Qty>${line.qty}</ord:Qty>
${if line.note}<ord:Note>${line.note}</ord:Note>${end}
</ord:Line>
${end}
</ord:Lines>
</ord:CreateOrder>
response:
arrays: [Line]
types: infer
jq: '{id: .OrderId, status: .Status, lines: [.Lines.Line[] | {sku: .Sku, qty: .Qty}]}'