Skip to main content

API Gateway

How every published API Builder API is called through Hrida.ai's built-in gateway: pipeline, authentication, consumer keys and their restrictions, caller identity, errors, response handling and reliability.

Every published API runs behind Hrida.ai's built-in API gateway. When a published API exposes operations to agents, its Tool Server entry points at the gateway, never at the raw upstream_base_url, whether or not the API has mappers. Agents call the gateway; the gateway applies your policy, adds the upstream credential and forwards the call.

GET/POST/PUT/PATCH/DELETE  /gw/{catalog-slug}/{api-slug}/{path}           prod
GET/POST/PUT/PATCH/DELETE /gw/{catalog-slug}/{api-slug}/{stage}/{path} a stage

For example https://hrida.ai/gw/lob/qa-posts-api/posts/1. {catalog-slug} is the API's home catalog (_ for platform-wide APIs) and {api-slug} the API's Slug: filled in from the spec's info.title when the API is created, unique within the catalog, editable until the API is first published and locked after that, because callers hard-code the URL. The API page's Endpoints card lists every operation's complete URL per environment.

The permanent ID URL /api/v1/api-definitions/{id}/proxy/{path} (stages: /api/v1/api-definitions/{id}/env/{stage}/proxy/{path}) keeps working and runs the exact same pipeline; Studio's own tool registration uses it.

Routing everything through one place means rate limits, size caps, caller identity, auditing, masking and the network checks apply to every API. The real upstream credential also never appears in the Tool Server configuration — only the gateway holds it.


Request Pipeline​

Each call passes these stages in order. A call refused at any stage never reaches the upstream.

#StageRefused with
1Admission: at most API_GATEWAY_MAX_IN_FLIGHT calls in progress per gateway worker503 overloaded
2Path check: . and .. segments are rejected400 invalid_path
3Published check: only a currently published API, in an environment and gateway that aren't suspended404 not_found, 503 suspended
4Credential: the gateway secret, a consumer key for this environment (with its allowed addresses and client certificate), or a partner access token401 unauthorized, 403 ip_not_allowed / client_certificate_required / insufficient_scope, 503 jwks_unavailable; 429 auth_throttled after too many failures from one address
5Caller identity: the signed X-Hrida-Caller token, verified when present and required when the API's policy says so401 caller_identity_required / caller_token_invalid / caller_token_expired
6Access re-check: the caller must still have access to the API's Tool Server403 caller_forbidden
7Rate limits and quotas: per API and per caller, and a consumer key's daily and monthly quota429 rate_limited / quota_exceeded + Retry-After
8Idempotency-Key (opt-in): a repeated POST/PATCH gets the first response400 idempotency_key_invalid, 409 idempotency_in_progress, 422 idempotency_key_reused
9Request size cap, and the JSON nesting depth (opt-in)413 request_too_large, 400 request_too_deep
10Schema validation (opt-in): parameters and JSON body against the OpenAPI spec400 request_invalid
11Request mappers: message reshape (body and optional query mapping), then protocol encode. A non-JSON body on an operation with a request mapper is refused400 request_not_json, 502 request_mapping_failed / request_encoding_failed
12Before the upstream: host allow-list; the upstream credential can be decrypted; GET cache; circuit breaker; a slot among the API's calls at once502 upstream_blocked / upstream_credentials_unreadable, 503 upstream_circuit_open / upstream_busy
13Upstream call: with upstream auth and TLS applied, a streamed and capped response read, and retries. Every new connection checks the addresses the host resolves to502 upstream_unreachable / upstream_blocked / upstream_response_too_large, 504 upstream_timeout
14Response mappers: protocol decode, then message reshape (2xx only)502 response_decoding_failed / response_mapping_failed
15Response validation (opt-in): the mapped response against the spec502 response_invalid (enforce)
16Masking (opt-in): sensitive values in the response are masked—

With mock responses on, the call is answered from the spec right after stage 10: stages 11–15 never run and the upstream is never called (masking still applies).

An operation served from a data source runs its query instead of stages 11–13, after the mock check. The GET cache and the calls-at-once limit apply, but the circuit breaker and retries don't. Its answer then goes through stages 14–16 like an upstream's. An operation with neither a query nor a base URL gets 502 no_backend.

An environment runs the mappers saved with the version it serves (see Message Mappers).

Every call, allowed or refused, writes one row to the Gateway Call Log, except failed logins past the per-address limit. The limits and opt-in checks in stages 4–10, 12, 15 and 16 are set per API under Gateway Policy & Security.

The gateway matches the request against the API's OpenAPI spec to find the operationId, resolving path templates such as /pets/{petId}. When a literal path and a templated path both match, the more specific literal path wins. Only operations in the spec are reachable; anything else returns 404 no_matching_operation.


Error Responses​

Refusals and failures return a short JSON body with no internal details:

json
{
  "error": "rate_limited",
  "message": "Rate limit exceeded for this API (600 calls per minute). Retry shortly.",
  "reference": "8c4c7952936e"
}

The error code identifies the stage (see the table above). The reference matches a server log line that holds the full detail — upstream host names, exception text, mapper errors — so support can find exactly what happened without that detail ever reaching the calling agent or the model's context. Refusals that come in floods under load or abuse (rate_limited, quota_exceeded, auth_throttled, overloaded, upstream_busy) are logged only at debug level; the call log and the gateway's metrics count them.

Upstream responses themselves (including upstream 4xx/5xx) are passed through with the upstream's status code. The exception is a SOAP Fault on an operation with a SOAP response mapper: it comes back as {"error": {"type": "soap_fault", ...}}, with 400 when the caller caused it (see SOAP Faults).


Authentication into the Gateway​

The gateway holds your real, decrypted upstream credential, so it needs its own lock:

  • Each API has a random gateway secret, created on first publish. The Tool Server entry carries it as a bearer key; every call must present Authorization: Bearer <gateway secret>.
  • The check fails closed: no secret, no access.
  • Lifecycle managers, space admins and admins can view the secret and the gateway URL with Security → Show gateway secret, to call the API from scripts or other services, and rotate it at any time. See Secret rotation.

Outside callers don't need the gateway secret: give each its own consumer key, or accept access tokens from its own identity provider.


Debugging a Call​

Every gateway response carries headers that say what happened, without exposing anything secret:

HeaderMeaning
X-Hrida-Environmentprod or the stage that served the call
X-Hrida-VersionThe API version served
X-Hrida-OperationThe matched operationId
X-Hrida-CacheHIT or MISS when the GET cache is on
X-Hrida-Breakeropened / recovered / open when the circuit breaker acted
X-Hrida-WarningA non-fatal finding, e.g. response_invalid, or mock for a mocked answer
X-Hrida-Mocktrue when mock responses answered instead of the upstream
X-Hrida-Trace-IdThe W3C trace id sent to the upstream (see Tracing), to find the call in the upstream's logs
Idempotent-Replayedtrue when a repeated request got the first response again (see Idempotency-Key)
Deprecation, Sunset, LinkThe API is deprecated, and when it goes away

Errors also return {"error", "message", "reference"}; the same reference is in the server log with the full detail. The test console shows these headers under each result, and Environments shows each environment's version and breaker state.

Testing an API​

The Test card on the API's page sends one request through this same gateway pipeline, as the signed-in user: operation matching, request validation, mappers, upstream auth and TLS, limits and masking. What you see is what an agent would get.

  1. Pick an operation. Fields appear for its path and query parameters, and for POST/PUT/PATCH a JSON body prefilled from the spec's example.
  2. Click Send request. The result shows the status code, duration, the matched operation, the upstream status (or, if the gateway refused or failed the call, its error code and the reason) and the response body. The reason only shows here: callers of the API get the error code and message.

Good to know:

  • Available to api_developer, lifecycle_manager, space_admin and admin, and works on drafts as well as published APIs, so you can check an API before submitting it for review.
  • By default it uses the saved working copy. Save first to test changes. Choose an environment under Test against to test exactly what that environment serves.
  • It calls the real upstream: a test POST, PUT or DELETE really changes data.
  • Test calls count toward the API's rate limits and appear in the call log under your user.
  • The body shown is at most 256 KB; a longer one, including a streamed response, is cut there and returned with "truncated": true.
POST /api/v1/api-definitions/{id}/test
{"method": "GET", "path": "/posts/1", "query": {"expand": "author"}, "body": null}
→ {"status_code": 200, "ok": true, "duration_ms": 142, "operation_id": "getPost",
"upstream_status": 200, "error_code": null, "error_detail": null, "content_type": "application/json",
"body": "{...}", "truncated": false}

Consumer keys for outside callers​

To let a script or partner service call a published API, give it a consumer key rather than the gateway secret. Lifecycle managers, space admins and admins manage them in the API's Consumer keys card:

  • New key asks for a name, and optionally an expiry (days) and a calls-per-minute limit. Without a limit, the key gets the API's per-user limit; every key also counts toward the API-wide limit.
  • Restrictions (optional, below the form):
    • Calls / day and Calls / month: a quota per UTC day and month. Past it: 429 quota_exceeded, with Retry-After until the quota resets. With Redis the quota holds across replicas.
    • Allowed addresses: IPs or CIDR ranges (203.0.113.10, 10.0.0.0/8) the key works from. From anywhere else: 403 ip_not_allowed.
    • Client certificate SHA-256: the key then works only with that TLS client certificate, which your load balancer checks and passes on (mutual TLS); otherwise 403 client_certificate_required. Set API_GATEWAY_CLIENT_CERT_HEADER to the header it passes the certificate in: a URL-encoded PEM (nginx $ssl_client_escaped_cert, AWS ALB), Envoy's X-Forwarded-Client-Cert, or a hex fingerprint.
  • The key (hak_<prefix>_<secret>) is shown once. Only a hash is stored, so a lost key can't be recovered: revoke it and create another. A new key works from its first call, on every server.
  • Revoke stops one key immediately, without affecting other keys or agents.
  • The table shows each key's status (active, expired, revoked), limit and restrictions, expiry and when it was last used, and calls appear in the call log under the key's name.

Callers send it like any bearer token:

curl -H "Authorization: Bearer hak_ab12cd34_…" https://hrida.example.com/gw/lob/qa-posts-api/posts/1

A key only works for the API it was created for, only while the API is published and its space is active, and never when the API requires a signed caller identity. Creating and revoking keys is recorded in the audit log (CREATE_CONSUMER_KEY, REVOKE_CONSUMER_KEY).

GET  /api/v1/api-definitions/{id}/consumer-keys
POST /api/v1/api-definitions/{id}/consumer-keys {"name": "...", "expires_in_days": 90, "rate_limit_per_minute": 60,
"quota_per_day": 10000, "quota_per_month": 250000,
"allowed_ips": ["203.0.113.0/24"], "client_cert_sha256": "ab12…"}
POST /api/v1/api-definitions/{id}/consumer-keys/{key_id}/revoke
Client addresses behind a load balancer

Allowed addresses, the failed-login limit and the call log use the client's address as the gateway sees it, from X-Forwarded-For. The gateway trusts that header only from the addresses in FORWARDED_ALLOW_IPS. By default that's loopback and the private networks (127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7), where a reverse proxy, ingress, tunnel or Docker network sits. It then takes the right-most address that isn't one of those, which is the one your proxy added, so a caller can't claim another address by sending the header itself.

  • A reverse proxy, Cloudflare Tunnel, Docker Swarm's ingress network or a Kubernetes ingress on a private address needs nothing.
  • A load balancer that reaches the containers from a public address: add its addresses to FORWARDED_ALLOW_IPS.
  • Don't set *: the gateway would then take the left-most address, which the caller writes.

The spec at the gateway URL​

Each published API serves its OpenAPI spec at its gateway URL plus /openapi.json (for a stage, …/staging/openapi.json), so consumers, client generators and Postman can load it from there:

curl -H "Authorization: Bearer hak_ab12cd34_…" https://hrida.example.com/gw/lob/qa-posts-api/openapi.json
  • It needs the same credential as a call: a consumer key for that environment, a partner access token when the API accepts them, or the gateway secret. Without one it answers 401.
  • servers is the gateway URL, and the only security scheme is the gateway's bearer key: the upstream's own auth stays with the gateway.
  • It's the spec of the version that environment serves.
  • An API that defines its own /openapi.json operation keeps it: that path is then forwarded to the upstream like any other.

Using a published API in chat​

A published API that exposes operations to agents is already a Global Tool Server: it only has to be switched on in chat, and it offers only those operations (see Tool Server Publishing). To add it yourself instead, for example from another Hrida.ai instance, use Settings › Integrations › Manage Tool Servers › +:

  • URL: the API's gateway URL, e.g. https://hrida.example.com/gw/lob/number-conversion-api. Not an operation's URL (such as …/NumberConversion.wso): the dialog adds /openapi.json to the URL, and the gateway serves the spec only there. If you paste an operation's URL or a documentation page, the dialog offers the right URL.
  • Auth: Bearer, with one of the API's consumer keys.

Caller identity​

The gateway secret proves a call came from Hrida.ai; the caller token says who it's for. When an agent calls a published API, Hrida.ai attaches a short-lived signed token in the X-Hrida-Caller header with the user, chat and message.

  • The token is signed with the instance secret, carries the audience hrida-api-gateway and the API's id, and expires after 15 minutes (API_GATEWAY_CALLER_TOKEN_TTL_SECONDS). A normal session token, or a token minted for a different API, is rejected.
  • When present, the gateway re-checks that user against the API's current access grants on every call — a user removed from the API Space loses access mid-conversation, not just at the next tool listing.
  • It drives the per-user rate limit and the user column of the call log.
  • Turn on Require a signed caller identity in the API's gateway policy to refuse any call that doesn't carry one.

Response Handling​

  • JSON responses are mapped and masked as configured, then returned as JSON.
  • XML and form responses with a response protocol mapper are decoded to JSON and typed according to the operation's response schema.
  • XML and other text responses without a response mapper are returned unchanged with the upstream's Content-Type (masked if masking is on).
  • Binary responses (PDFs, images, archives) are passed through byte for byte with the upstream's Content-Type.
  • Non-JSON request bodies (form posts, file uploads) without a request mapper are forwarded as-is with the caller's Content-Type.
  • Bodies nothing changes are passed on byte for byte. When no mapper, masking or validation applies, the upstream's bytes and Content-Type are returned as they came, and the caller's body is sent upstream as it came: numbers such as 12345678901234567.89 keep every digit. When the gateway does process JSON, it keeps numbers exact too.
  • Large responses are streamed. A response nothing changes that is over 1 MB (API_GATEWAY_STREAM_THRESHOLD_BYTES), or doesn't declare its length, is passed to the caller as it arrives, without the gateway holding it in memory. The response size cap still applies: a stream that passes it is cut off.
  • Headers: see Headers for the ones passed each way.

Reliability​

  • Timeout — each attempt may take up to the API's upstream timeout (60 seconds by default); then the call fails with 504 upstream_timeout.
  • Retry — a failure to connect (refused, DNS, connect timeout) always retries, since the request never reached the upstream. A timeout or dropped connection after connecting retries only for GET/HEAD: a POST the upstream may already be working on (a payment, or any SOAP call) is never sent twice. Received responses retry only for 503 (any method) or 500/502/504 on GET/HEAD. Backoff doubles each attempt, with random jitter, up to 3 attempts, and retries come out of a retry budget so they can't multiply the load on a failing upstream.
  • Overload: per-API limits on calls at once and a per-worker cap answer 503 quickly instead of queueing; see Concurrency and overload.
  • Bounded memory — the upstream response is read in chunks and abandoned as soon as it passes the API's response-size cap.
  • Reused connections — each gateway process keeps a pool of open connections to upstreams, so calls skip the TCP and TLS handshake. Idle connections close after 4 seconds; cookies an upstream sets are never sent on another call.
  • Address check — every new connection checks the addresses the upstream's host name resolves to, and refuses loopback, link-local and cloud metadata addresses with 502 upstream_blocked, without a retry. A host name that doesn't resolve is 502 upstream_unreachable after the retries.
  • Cached lookups — the API's definition, the version each environment serves, its mappers, consumer keys and the gateway settings are cached for API_GATEWAY_CACHE_SECONDS (15 by default), so a call usually doesn't touch the database. Any change made in Studio clears them at once: publishing, editing, revoking a key, suspending a space. With several replicas or the dedicated gateway service, that happens through Redis. Studio confirms a change only after announcing it, and each call checks for announcements before it uses the cache, so a call made right after the change sees it on every process. A key that isn't in a process's cached list yet (created moments ago) is checked against the database before it's turned away, so made-up keys still cost at most one query a second.

For heavy traffic, the gateway can run as its own service, with its own replicas, and on Kubernetes with autoscaling: see Dedicated Gateway Service.

Tracing​

Every upstream call carries a W3C traceparent header (and the caller's tracestate), so the upstream's logs and traces join the caller's:

  • With OpenTelemetry on, it's the gateway's own span, a child of the caller's trace.
  • Otherwise the caller's traceparent is passed on when it's valid, or a new trace starts.

The trace id comes back in X-Hrida-Trace-Id, including in the test console.


Hrida.ai is proprietary software of Zlabs Innovation. See the license for terms. © 2026 Zlabs Innovation.