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:
| Variable | Description |
|---|---|
upstream_addr | IP address and port, or UNIX-domain socket path, of the upstream server. |
remote_addr | Client address. |
request_method | Request method, such as GET or POST. |
request_uri | Full original request URI, including arguments. |
server_name | Name of the server that accepted the request. |
status | Response 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. |
uri | Current normalized request URI, which can change during request processing. |
http_user_agent | Value 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 Name | Description |
|---|---|
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. |
method | HTTP request method, such as GET or POST. The equivalent NGINX variable is request_method. |
balancer_ip | Upstream server IP. |
balancer_port | Upstream server port. |
consumer_name | Consumer username. |
consumer_group_id | Inherited runtime variable for a consumer group ID. API7 Gateway does not assign consumer group IDs, so this variable is unset. |
graphql_name | GraphQL operation name. |
graphql_operation | GraphQL operation type. |
graphql_root_fields | GraphQL root fields. |
route_id | Route ID. |
route_name | Route name. |
service_id | Service ID. |
service_name | Service name. |
resp_body | HTTP response body. |
mqtt_client_id | Client ID in MQTT protocol. |
redis_cmd_line | Redis command. |
rpc_time | RPC 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_host | The 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_info | JSON 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. |
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.
| Variable | Meaning and availability |
|---|---|
request_type | Request classification, such as ai_chat or ai_stream. Set when the AI proxy parses the request in access. |
request_llm_model | Model supplied by the client. Available after the AI proxy parses the request in access, when the request includes a model. |
llm_model | Model 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_stream | Whether the upstream request streams, as true or false. Set while preparing the upstream request. |
llm_tool_count | Number of tools in the final upstream request. Set while preparing that request. |
llm_end_user_id | End-user identifier extracted from the final upstream request, when the protocol exposes one. |
llm_prompt_tokens, llm_completion_tokens, llm_total_tokens | Token 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_tokens | Provider-reported cache and reasoning usage extracted from the response. Availability depends on the provider and protocol. |
llm_time_to_first_token | Time in milliseconds from sending the upstream request to receiving the first token, or the response for a non-streaming request. |
llm_has_tool_calls | Indicates that tool calls were observed in the response. |
llm_content_risk_level | Latest 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:
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
| Field | Description |
|---|---|
rate_limiting_key | Counter key that the request was counted under. |
rate_limiting_limit | Quota of the window. |
rate_limiting_remaining | Remaining quota after the request. It is 0 when the request is rejected or the counter could not be updated. |
rate_limiting_reset | Seconds 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:
- Custom Variables
- APISIX Variables
- 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_hostand${http_host}$arg_username-$arg_useridand${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.
| Example | Behavior |
|---|---|
${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. |