> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apinizer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Variable Definition

> Variable is a structure used to extract data from API traffic messages for policy needs. It is used to extract data from different parts of HTTP requests (header, parameter, body, etc.). Variables are used in policies, conditions, and other API configurations to dynamically access request/response data.

## Overview

Variable is a structure used to extract data from API traffic messages for policy needs. It is used to extract data from different parts of HTTP requests (header, parameter, body, etc.). Variables are used in policies, conditions, and other API configurations to dynamically access request/response data.

## Basic Properties

| Property    | Type             | Required | Description                                          |
| ----------- | ---------------- | -------- | ---------------------------------------------------- |
| name        | string           | Yes      | Unique name of the variable                          |
| description | string           | No       | Description for the variable                         |
| type        | EnumVariableType | Yes      | Variable type. See [Variable Types](#variable-types) |

### Note

* `name` must be unique within a project

## Variable Types

Variables support the following types:

* `HEADER` - Extract data from HTTP headers
* `PARAMETER` - Extract data from URL parameters (query, path, form)
* `BODY` - Extract data from request/response body (XML, JSON, or raw body)
* `CONTEXT_VALUES` - Extract data from system context values
* `CUSTOM` - Custom variable defined with script

## Variable Types and Required Fields

### HEADER Type

Extract data from HTTP headers.

| Field      | Type   | Required | Description                                                  |
| ---------- | ------ | -------- | ------------------------------------------------------------ |
| type       | string | Yes      | Must be `HEADER`                                             |
| headerName | string | Yes      | Name of the HTTP header field in request or response message |

#### Example

```json theme={null}
{
  "name": "apiKeyVariable",
  "description": "Extracts API key from header",
  "type": "HEADER",
  "headerName": "X-API-Key"
}
```

### PARAMETER Type

Extract data from URL parameters (query, path, or form).

| Field     | Type   | Required | Description                                                                           |
| --------- | ------ | -------- | ------------------------------------------------------------------------------------- |
| type      | string | Yes      | Must be `PARAMETER`                                                                   |
| paramType | string | Yes      | Parameter type. See [EnumVariableParameterType](#enumvariableparametertype-paramtype) |
| paramName | string | Yes      | Name of the parameter in request message                                              |
| paramPath | string | Yes\*    | Template path to use for "path" parameter (required if paramType=PATH)                |
| formName  | string | No       | Form field name (optional, used if paramType=FORM and differs from paramName)         |

### Note

* For `paramType=QUERY`: Use `paramName` only
* For `paramType=PATH`: Use `paramName` and `paramPath` (required)
* For `paramType=FORM`: Use `paramName` (required), `formName` is optional and typically same as `paramName` unless you need a different field name

### EnumVariableParameterType (paramType)

* `QUERY` - Query parameter (e.g., `?userId=123`)
* `PATH` - Path parameter (e.g., `/users/{userId}`)
* `FORM` - Form parameter (form data)

**Example 1: Query Parameter**

```json theme={null}
{
  "name": "userIdFromQuery",
  "description": "Extracts user ID from query parameter",
  "type": "PARAMETER",
  "paramType": "QUERY",
  "paramName": "userId"
}
```

**Example 2: Path Parameter**

```json theme={null}
{
  "name": "orderIdFromPath",
  "description": "Extracts order ID from path",
  "type": "PARAMETER",
  "paramType": "PATH",
  "paramName": "orderId",
  "paramPath": "/orders/{orderId}"
}
```

**Example 3: Form Parameter**

```json theme={null}
{
  "name": "usernameFromForm",
  "description": "Extracts username from form data",
  "type": "PARAMETER",
  "paramType": "FORM",
  "paramName": "username",
  "formName": "username"
}
```

### BODY Type

Extract data from request/response body (XML, JSON, or raw body).

| Field              | Type   | Required | Description                                                                            |
| ------------------ | ------ | -------- | -------------------------------------------------------------------------------------- |
| type               | string | Yes      | Must be `BODY`                                                                         |
| messageContentType | string | Yes      | Content type. See [EnumMessageContentType](#enummessagecontenttype-messagecontenttype) |
| xpathValue         | string | Yes\*    | XPath expression for XML body data (required if messageContentType=XML)                |
| jsonPathValue      | string | Yes\*    | JsonPath expression for JSON body data (required if messageContentType=JSON)           |

### EnumMessageContentType (messageContentType)

* `XML` - XML content type
* `JSON` - JSON content type
* `ALL_BODY` - Raw body content (all body)

**Example 1: XML Body**

```json theme={null}
{
  "name": "customerNameFromXml",
  "description": "Extracts customer name from XML body",
  "type": "BODY",
  "messageContentType": "XML",
  "xpathValue": "//customer/firstName"
}
```

**Example 2: JSON Body**

```json theme={null}
{
  "name": "emailFromJson",
  "description": "Extracts email address from JSON body",
  "type": "BODY",
  "messageContentType": "JSON",
  "jsonPathValue": "$.user.contact.email"
}
```

**Example 3: All Body**

```json theme={null}
{
  "name": "rawBody",
  "description": "Extracts raw body content",
  "type": "BODY",
  "messageContentType": "ALL_BODY"
}
```

### CONTEXT\_VALUES Type

Extract data from system context values.

| Field        | Type   | Required | Description                                                                   |
| ------------ | ------ | -------- | ----------------------------------------------------------------------------- |
| type         | string | Yes      | Must be `CONTEXT_VALUES`                                                      |
| contextValue | string | Yes      | Context value type. See [EnumVariableContextValue](#enumvariablecontextvalue) |
| zoneId       | string | Yes\*    | Time zone ID (required for some context values, e.g., date/time values)       |

#### Example

```json theme={null}
{
  "name": "requestTime",
  "description": "Extracts request time from system context",
  "type": "CONTEXT_VALUES",
  "contextValue": "DATETIME_EPOCH_MILLIS",
  "zoneId": "Europe/Istanbul"
}
```

### CUSTOM Type

Custom variable defined with script.

| Field          | Type    | Required | Default | Description                                                                                                             |
| -------------- | ------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------- |
| type           | string  | Yes      | -       | Must be `CUSTOM`                                                                                                        |
| initWithScript | boolean | No       | false   | Whether to initialize with script (default: false)                                                                      |
| scriptLanguage | string  | Yes\*    | -       | Script language (required if initWithScript=true). See [EnumScriptType](/api-reference/policies/policies/policy-script) |
| scriptBody     | string  | Yes\*    | -       | Script body code (required if initWithScript=true)                                                                      |

### Note

* If `initWithScript` is `true`, both `scriptLanguage` and `scriptBody` must be provided
* If `initWithScript` is `false` (default), script fields are optional

#### Example

```json theme={null}
{
  "name": "customVariable",
  "description": "Custom variable with script",
  "type": "CUSTOM",
  "initWithScript": true,
  "scriptLanguage": "JAVASCRIPT",
  "scriptBody": "return request.header['X-User-ID'];"
}
```

## EnumVariableContextValue

Context values available for `CONTEXT_VALUES` type variables.

### Request-Related Values

| Context Value                  | Description                   |
| ------------------------------ | ----------------------------- |
| `REQUEST_REMOTE_ADDRESS`       | Client IP address             |
| `REQUEST_HTTP_METHOD`          | HTTP method (GET, POST, etc.) |
| `REQUEST_CONTENT_TYPE`         | Request content type          |
| `REQUEST_PATH_INFO`            | Request path information      |
| `REQUEST_CONTEXT_PATH`         | Context path information      |
| `REQUEST_QUERY_STRING`         | URL query string parameters   |
| `REQUEST_REMOTE_USER`          | Remote user information       |
| `REQUEST_USERNAME_KEY`         | Username or key               |
| `REQUEST_REQUESTED_SESSION_ID` | Session ID                    |
| `REQUEST_REQUEST_URI`          | Request URI                   |
| `REQUEST_CHARACTER_ENCODING`   | Character encoding            |
| `REQUEST_CHARSET`              | Charset information           |
| `REQUEST_CONTENT_LENGTH`       | Content length                |
| `REQUEST_PROTOCOL`             | Protocol used                 |
| `REQUEST_SCHEME`               | Protocol scheme (http, https) |
| `REQUEST_SERVER_NAME`          | Server name                   |
| `REQUEST_SERVER_PORT`          | Server port number            |
| `REQUEST_REMOTE_HOST`          | Remote host information       |
| `REQUEST_REMOTE_PORT`          | Remote port number            |
| `REQUEST_LOCAL_NAME`           | Local server name             |
| `REQUEST_LOCAL_ADDR`           | Local IP address              |
| `REQUEST_LOCAL_PORT`           | Local port number             |
| `REQUEST_XFORWARDED_FOR`       | X-Forwarded-For header value  |

### Request Status Information

| Context Value                      | Description                               |
| ---------------------------------- | ----------------------------------------- |
| `REQUEST_IS_SOAP_TO_REST`          | Whether SOAP to REST conversion is active |
| `REQUEST_IS_APIPROXY`              | API Proxy check                           |
| `REQUEST_IS_APIPROXYGROUP`         | API Proxy Group check                     |
| `REQUEST_IS_XWWW_FORM_URL_ENCODED` | Form URL encoded format check             |
| `REQUEST_IS_FORM_DATA`             | Form data format check                    |
| `REQUEST_IS_BYTE_ARRAY`            | Byte array format check                   |
| `REQUEST_HAS_ATTACHMENT`           | Attachment check                          |
| `REQUEST_GZIP`                     | GZIP compression status                   |
| `REQUEST_DEFLATE`                  | DEFLATE compression status                |
| `REQUEST_BR`                       | Brotli compression status                 |
| `REQUEST_ZSTD`                     | Zstandard compression status              |
| `REQUEST_IDENTITY`                 | Identity encoding status                  |
| `REQUEST_COMPRESS`                 | Compress encoding status                  |
| `REQUEST_HTTP_SERVLET`             | HTTP Servlet information                  |

### Response-Related Values

| Context Value            | Description                              |
| ------------------------ | ---------------------------------------- |
| `RESPONSE_IS_BYTE_ARRAY` | Whether response is in byte array format |
| `RESPONSE_GZIP`          | GZIP compression status                  |
| `RESPONSE_DEFLATE`       | DEFLATE compression status               |
| `RESPONSE_BR`            | Brotli compression status                |
| `RESPONSE_ZSTD`          | Zstandard compression status             |
| `RESPONSE_IDENTITY`      | Identity encoding status                 |
| `RESPONSE_COMPRESS`      | Compress encoding status                 |
| `RESPONSE_STATUS_CODE`   | HTTP status code                         |
| `RESPONSE_HTTP_SERVLET`  | HTTP Servlet information                 |

### Message-Related Values

| Context Value            | Description            |
| ------------------------ | ---------------------- |
| `MESSAGE_CORRELATION_ID` | Message correlation ID |

### Environment-Related Values

| Context Value             | Description      |
| ------------------------- | ---------------- |
| `ENVIRONMENT_ID`          | Environment ID   |
| `ENVIRONMENT_NAME`        | Environment name |
| `ENVIRONMENT_CERTIFICATE` | Certificate map  |
| `ENVIRONMENT_PRIVATEKEY`  | Private key map  |
| `ENVIRONMENT_PUBLICKEY`   | Public key map   |
| `ENVIRONMENT_SECRETKEY`   | Secret key map   |
| `ENVIRONMENT_KEYSTORE`    | Keystore map     |
| `ENVIRONMENT_JWK`         | JWK map          |

### API Proxy Group/Proxy/Method Values

| Context Value                  | Description                  |
| ------------------------------ | ---------------------------- |
| `APIPROXYGROUP_ID`             | API Proxy Group ID           |
| `APIPROXYGROUP_NAME`           | API Proxy Group name         |
| `APIPROXY_ID`                  | API Proxy ID                 |
| `APIPROXY_NAME`                | API Proxy name               |
| `APIMETHOD_ID`                 | API Method ID                |
| `APIMETHOD_NAME`               | API Method name              |
| `APIMETHOD_SOAP_ACTION`        | SOAP action value            |
| `APIMETHOD_HTTPMETHOD`         | HTTP method                  |
| `APIMETHOD_ENDPOINT`           | Endpoint information         |
| `APIMETHOD_BACKEND_HTTPMETHOD` | Backend HTTP method          |
| `APIMETHOD_BACKEND_ENDPOINT`   | Backend endpoint information |

### Date/Time-Related Values

| Context Value             | Description         | zoneId Required |
| ------------------------- | ------------------- | --------------- |
| `DATETIME_YEAR`           | Year                | Yes             |
| `DATETIME_MONTH`          | Month               | Yes             |
| `DATETIME_DAY_OF_WEEK`    | Day of week         | Yes             |
| `DATETIME_DAY_OF_MONTH`   | Day of month        | Yes             |
| `DATETIME_HOUR`           | Hour                | Yes             |
| `DATETIME_MINUTE`         | Minute              | Yes             |
| `DATETIME_SECOND`         | Second              | Yes             |
| `DATETIME_EPOCH_MILLIS`   | Epoch milliseconds  | Yes             |
| `DATETIME_FORMATTED_TEXT` | Formatted date-time | Yes             |
| `DATE_FORMATTED_TEXT`     | Formatted date      | Yes             |
| `TIME_FORMATTED_TEXT`     | Formatted time      | Yes             |

**Note:** Date/time context values require `zoneId` field to be specified.

### Credential Values

| Context Value                            | Description                       |
| ---------------------------------------- | --------------------------------- |
| `CREDENTIAL_USERNAME`                    | Username                          |
| `CREDENTIAL_EMAIL`                       | Email address                     |
| `CREDENTIAL_FULLNAME`                    | Full name                         |
| `CREDENTIAL_SECRETKEY`                   | Secret key                        |
| `CREDENTIAL_CERTIFICATE`                 | Certificate                       |
| `CREDENTIAL_PUBLICKEY`                   | Public key                        |
| `CREDENTIAL_PRIVATEKEY`                  | Private key                       |
| `CREDENTIAL_KEYSTORE`                    | Keystore                          |
| `CREDENTIAL_TRUSTSTORE`                  | Truststore                        |
| `CREDENTIAL_JWK_SIGNANDVALIDATION`       | JWK for signing and validation    |
| `CREDENTIAL_JWK_ENCRYPTIONANDDECRYPTION` | JWK for encryption and decryption |

## Complete Variable Examples

### Example 1: Header Variable

```json theme={null}
{
  "name": "apiKeyVariable",
  "description": "Extracts API key from header",
  "type": "HEADER",
  "headerName": "X-API-Key"
}
```

### Example 2: Query Parameter Variable

```json theme={null}
{
  "name": "userIdFromQuery",
  "description": "Extracts user ID from query parameter",
  "type": "PARAMETER",
  "paramType": "QUERY",
  "paramName": "userId"
}
```

### Example 3: Path Parameter Variable

```json theme={null}
{
  "name": "orderIdFromPath",
  "description": "Extracts order ID from path",
  "type": "PARAMETER",
  "paramType": "PATH",
  "paramName": "orderId",
  "paramPath": "/orders/{orderId}"
}
```

### Example 4: XML Body Variable

```json theme={null}
{
  "name": "customerNameFromXml",
  "description": "Extracts customer name from XML body",
  "type": "BODY",
  "messageContentType": "XML",
  "xpathValue": "//customer/firstName"
}
```

### Example 5: JSON Body Variable

```json theme={null}
{
  "name": "emailFromJson",
  "description": "Extracts email address from JSON body",
  "type": "BODY",
  "messageContentType": "JSON",
  "jsonPathValue": "$.user.contact.email"
}
```

### Example 6: Context Variable (Client IP)

```json theme={null}
{
  "name": "clientIp",
  "description": "Extracts client IP address",
  "type": "CONTEXT_VALUES",
  "contextValue": "REQUEST_REMOTE_ADDRESS"
}
```

### Example 7: Context Variable (Date/Time)

```json theme={null}
{
  "name": "requestTime",
  "description": "Extracts request time",
  "type": "CONTEXT_VALUES",
  "contextValue": "DATETIME_EPOCH_MILLIS",
  "zoneId": "Europe/Istanbul"
}
```

### Example 8: Custom Variable

```json theme={null}
{
  "name": "customUserId",
  "description": "Custom variable to extract user ID",
  "type": "CUSTOM",
  "initWithScript": true,
  "scriptLanguage": "JAVASCRIPT",
  "scriptBody": "var header = request.header['X-User-ID']; return header ? header : request.header['Authorization'].split(' ')[1];"
}
```

## Usage in Policies

Variables are used in various policies:

* **API Based Throttling** - `targetVariableForIdentity` to identify clients
* **RLCL** - `targetVariable` for rate limiting
* **Conditions** - `firstVariable` and `secondVariable` for condition rules
* **Content Filter** - Variables to filter content
* **Redaction** - Variables to identify data to redact
* **Encryption/Decryption** - Variables for source and target data

## Notes and Warnings

* **Variable Names**:
  * Variable names must be unique within a project
  * Use descriptive names for better understanding

* **Required Fields**:
  * Each variable type has specific required fields
  * Missing required fields will cause validation errors

* **Context Values**:
  * Date/time context values require `zoneId` field
  * Use IANA time zone identifiers (e.g., "Europe/Istanbul", "America/New\_York")

* **XPath/JsonPath**:
  * XPath expressions are used for XML content
  * JsonPath expressions are used for JSON content
  * Ensure expressions are valid for the content type

* **Custom Scripts**:
  * Custom variables use scripts to extract data
  * Script language must be specified
  * Scripts have access to request/response objects

## Related Documentation

* [Enum Reference](/api-reference/appendix/enum-reference) - Enumeration values used in variables (EnumVariableType, EnumVariableParameterType, etc.)
* [Glossary](/api-reference/appendix/glossary) - Terms and definitions
* [API Based Throttling Policy](/api-reference/policies/policies/policy-api-based-throttling) - Uses variables for client identification
* [RLCL API](/api-reference/rlcl/condition/add-condition.mdx) - Uses variables for rate limit control
* [Script Policy](/api-reference/policies/policies/policy-script) - Script language types
