Skip to main content
Version: 3.9.x

Built-In Variables

Built-in variables in API7 Gateway are pre-defined variables that can be directly referenced in configurations. They are often used in plugin configurations, route matching, and log customization.

API7 Gateway supports three types of built-in variables:

  • NGINX Variables
  • APISIX Variables
  • Custom Variables

These variables are evaluated in a given order.

NGINX Variables​

NGINX provides variables that expose request and response information.

Commonly used variables include:

VariableDescription
upstream_addrIP address and port, or UNIX-domain socket path, of the upstream server.
remote_addrClient address.
request_methodRequest method, such as GET or POST.
request_uriFull original request URI, including arguments.
server_nameName of the server that accepted the request.
statusResponse status. It can be 000 until NGINX establishes the response status. Use it in response-phase contexts, such as Debug Session sampling rules or logging plugins; do not use it for route matching.
uriCurrent normalized request URI, which can change during request processing.
http_user_agentValue of the User-Agent request header.

See the complete list of NGINX variables for more information.

In plugin code, ctx.var.request_uri is the normalized path plus the query string before API7 Gateway applies Service path-prefix stripping. The original target is ctx.var.real_request_uri. When Service strip_path_prefix is enabled, Route plugins read the stripped path from ctx.var.uri, while request_uri keeps the pre-strip path. See the base assignments in APISIX Plugin Request URI Values.

APISIX Variables​

In addition to NGINX variables, APISIX offers a variety of built-in variables:

Variable NameDescription
post_arg_*HTTP POST form data when the content type is application/x-www-form-urlencoded. The asterisk is to be replaced with the actual name of the POST form data.
post_arg.*HTTP POST body parameter when the content type is application/json, application/x-www-form-urlencoded, or multipart/form-data. The asterisk is to be replaced with the actual name of the POST parameter. Supports JSON path-like selection, such as post_arg.model.version and post_arg.messages[*].content[*].type.
arg_*URL query string. The asterisk is to be replaced with the actual query parameter name.
http_*HTTP request header. The asterisk is to be replaced with the actual name of the header.
cookie_*Request cookie. The asterisk is to be replaced with the actual name of the cookie.
methodHTTP request method, such as GET or POST. The equivalent NGINX variable is request_method.
balancer_ipUpstream server IP.
balancer_portUpstream server port.
consumer_nameConsumer username.
consumer_group_idInherited runtime variable for a consumer group ID. API7 Gateway does not assign consumer group IDs, so this variable is unset.
graphql_nameGraphQL operation name.
graphql_operationGraphQL operation type.
graphql_root_fieldsGraphQL root fields.
route_idRoute ID.
route_nameRoute name.
service_idService ID.
service_nameService name.
resp_bodyHTTP response body.
mqtt_client_idClient ID in MQTT protocol.
redis_cmd_lineRedis command.
rpc_timeRPC request round-trip time.
external_user.*External user information. This variable can be populated by authentication plugins such as openid-connect, making it available to other plugins. For example, limit-count-advanced can enforce rate limiting by username when key is set to ${external_user.preferred_username}.
upstream_unresolved_hostThe configured upstream host or domain name before DNS resolution (the upstream node's domain or host). Available in API7 Enterprise from version 3.9.15.
rate_limiting_infoJSON object that describes how a rate limiting plugin evaluated the request. See Rate Limiting Information below. Available in API7 Enterprise from version 3.9.6.
caution

http_* reads an HTTP request header. It is not a prefix for other built-in variables. For example, http_uri, http_method, and http_status read request headers named Uri, Method, and Status. Use uri, method, and status for the request path, request method, and response status.

API7 Gateway does not verify that such a header exists when compiling an expression. If a client does not send the header, a condition that expects it to have a value can fail to match without an error.

AI Request Variables​

The AI Proxy and AI Proxy Multi plugins populate AI variables as a request progresses. A variable that depends on the upstream response is not available for routing or access-phase checks.

VariableMeaning and availability
request_typeRequest classification, such as ai_chat or ai_stream. Set when the AI proxy parses the request in access.
request_llm_modelModel supplied by the client. Available after the AI proxy parses the request in access, when the request includes a model.
llm_modelModel selected for the upstream request, which can differ from the client's model. Set in before_proxy; do not use it for an access-phase limit.
llm_streamWhether the upstream request streams, as true or false. Set while preparing the upstream request.
llm_tool_countNumber of tools in the final upstream request. Set while preparing that request.
llm_end_user_idEnd-user identifier extracted from the final upstream request, when the protocol exposes one.
llm_prompt_tokens, llm_completion_tokens, llm_total_tokensToken usage extracted from the upstream response. Use in response processing or logs, not in access.
llm_cache_read_input_tokens, llm_cache_creation_input_tokens, llm_reasoning_tokensProvider-reported cache and reasoning usage extracted from the response. Availability depends on the provider and protocol.
llm_time_to_first_tokenTime in milliseconds from sending the upstream request to receiving the first token, or the response for a non-streaming request.
llm_has_tool_callsIndicates that tool calls were observed in the response.
llm_content_risk_levelLatest risk level returned by an AI content moderation plugin. Request moderation can set it in access; response moderation can replace it later.

For a concurrency limit keyed by consumer and the client's model, configure limit-conn with key_type set to var_combination and key set to $consumer_name:$request_llm_model. The default plugin priorities run AI Proxy or AI Proxy Multi before limit-conn in access. If you override priorities, preserve that order. Ensure authentication has resolved the consumer and the request supplies a model; an absent variable does not identify the intended consumer/model pair.

These AI variables are populated after route matching. To match a route on a JSON request's model field, use post_arg.model instead. For usage logging, see Include LLM Information in Access Log. A missing value or a zero token count is not evidence that the provider charged nothing, especially when a stream ends before usage is reported.

Rate Limiting Information​

The rate_limiting_info variable holds a JSON object that describes how a rate limiting plugin evaluated the request. Available in API7 Enterprise from version 3.9.6.

The following plugins set the variable: limit-count, limit-count-advanced, graphql-limit-count, and ai-rate-limiting. Before one of them runs, or on a route without any of them, the variable is an empty string.

Add the Variable to the Access Log​

Add the variable to the access log in the data plane's config.yaml. With access_log_format_escape set to json, the variable is written as an escaped JSON string inside the log line:

conf/config.yaml
nginx_config:
http:
access_log_format: '{"time_local":"$time_local","remote_addr":"$remote_addr","request":"$request","status":"$status","rate_limiting_info":"$rate_limiting_info"}'
access_log_format_escape: json

Parse the log line as JSON first, then parse the value of rate_limiting_info as JSON again. Read fields by name instead of relying on their order. You can also reference the variable in the log format of a logger plugin.

The variable has a value like the following:

{"rate_limiting_key":"/apisix/routes/1:1:127.0.0.1","rate_limiting_limit":10,"rate_limiting_remaining":3,"rate_limiting_reset":42}

Fields​

FieldDescription
rate_limiting_keyCounter key that the request was counted under.
rate_limiting_limitQuota of the window.
rate_limiting_remainingRemaining quota after the request. It is 0 when the request is rejected or the counter could not be updated.
rate_limiting_resetSeconds until the quota resets, rounded down to a whole number.

AI Token Accounting with Redis​

ai-rate-limiting checks available quota in access before the LLM reports usage, then charges the reported usage in log. With redis, redis-cluster, or redis-sentinel, the log-phase update runs asynchronously and does not rewrite the original request's rate_limiting_info. The logged value therefore describes the earlier quota check, unless another rate-limiting evaluation replaced it; it is not the final token charge or the Redis balance after that charge.

With local, token accounting updates the request variable synchronously in log. A logger that runs before that update still sees the earlier value. Use the AI token variables or llm_summary to record reported usage, and inspect Redis or the configured accounting backend when you need to verify the shared balance.

Multiple Rules and Plugins​

The variable holds one evaluation. Each evaluation replaces the previous value, so the variable describes the last rule that was evaluated:

  • When a plugin is configured with multiple rules, the rules are evaluated in order and evaluation stops at the first rule that rejects the request. The variable describes that rule, or the last rule if no rule rejected the request.
  • When more than one of the plugins above runs on a request, the variable describes the rule that the last plugin evaluated.

Evaluation Order​

API7 Gateway evaluates variables in the given order:

  1. Custom Variables
  2. APISIX Variables
  3. NGINX Variables

If a variable is successfully sourced in custom variables, API7 Gateway will not continue to look in APISIX variables or NGINX variables.

In other words, custom variables will overwrite variables of the same names defined in APISIX variables or NGINX variables, to better meet requirements of your specific use cases.

Variable Syntax​

A valid variable name can include letters, digits, underscores (_), and periods (.).

Escaped variables with a backslash (\) are not treated as variables, for example, \$variable_name.

Simple and Braced Forms​

A variable can be referenced in two forms:

  • $variable_name
  • ${variable_name}

Both forms are supported; however, the braced form is required in certain contexts to ensure correct parsing.

The unbraced form $variable is valid when the following character cannot be part of a variable name. For example, the following forms are equivalent:

  • $http_host and ${http_host}
  • $arg_username-$arg_userid and ${arg_username}-${arg_userid}

When a variable is followed by a character that could belong to a variable name, the parser will incorrectly interpret it as a longer variable name. For example, with https://$http_baseurl.com, the parser would treat the entire string http_baseurl.com as the variable, which is incorrect. In this case, you should use the braced form https://${http_baseurl}.com to clearly delimit the variable.

You would also need the braced form if you use the ?? operator.

Default Values with ??​

You can specify a default value for a variable using the ?? operator. If the variable is not defined, the value after the operator will be used.

ExampleBehavior
${http_username ?? anonymous}If the HTTP request header username is defined, its value is used; otherwise the string anonymous is used.
${http_count ?? 10}If the HTTP request header count is defined, its value is used; otherwise the string 10 is used.