Overview
What is its Purpose?
- Script Policy aims to solve integration requirements without writing code by applying custom business rules and data transformations in the API Proxy request pipeline.
- Script Policy enables centralized management of operations such as masking, enriching incoming data, or adapting error messages in the response pipeline.
- Script Policy makes it possible to create a global/local shared script library for consistent behavior across different environments.
- Script Policy activates only for specific endpoint or header combinations through its condition engine, maintaining performance.
Working Principle
- Request Arrival: For every HTTP/HTTPS request arriving at the API Gateway, the source IP address of the request is detected.
- Policy Check: If Script Policy is active, the system checks in the following order:
- Is a Condition defined? If so, is the condition met?
- Is the policy active (active=true)?
- Is a Variable being used or Apinizer default?
- Script Engine Execution: According to the selected executionType (SYNC/ASYNC) and scriptLanguage (Groovy/Javascript) values, the script runs in the specified pipeline region; request/response body, headers, and parameter maps can be updated.
- Decision Making:
- Match Found: Message components updated as a result of the script are written back to the pipeline; in case of error, the defined statusCode and message are returned.
- No Match: Script is skipped, request/response continues to default flow.
- Error Handling: Customizable HTTP status code and error message are returned for requests that do not comply with policy rules.
Features and Capabilities
Core Features
- ExecutionType Management (Sync/Async): Determines whether the script will run synchronously or in the background; asynchronous mode does not block the endpoint during long-running operations.
- Dual Script Language Support: Allows teams to use the language they are proficient in by choosing between Groovy and Javascript.
- Context Variable Library: Provides ready-made variable maps for From Client, To Backend, From Backend, and To Client flows; readable/writable fields are clearly separated.
- Active/Passive Status Control: Easily switch the policy’s active or passive state (active/passive toggle). Policy is not applied when passive, but configuration is retained.
- Condition-Based Application: Create complex conditions with Query Builder to determine when the policy will be applied (e.g., only for specific endpoints or header values).
Advanced Features
- Script Test Laboratory: Run scripts with sample header/param/body data for different pipeline segments using the integrated test window and examine results.
- Dependency Tracking: See which API Proxy or groups the policy is used in through Used Proxies/Policy Groups sections and perform change impact analysis.
- Dynamic Context Value Selection: Automatically copy date, environment, or proxy metadata information from EnumScriptContextValue for use within scripts.
- Export/Import Feature: Export policy configuration as a ZIP file. Import to different environments (Development, Test, Production). Version control and backup capability.
- Policy Group and Proxy Group Support: Manage multiple policies within Policy Groups. Assign policies in bulk to Proxy Groups. Centralized update and deploy operations.
- Deploy and Versioning: Deploy policy changes to production environment. View which API Proxies use it (Policy Usage). Proxy Group and Policy Group usage reports.
Usage Scenarios
| Scenario | Situation | Solution (Policy Application) | Expected Behavior / Result |
|---|---|---|---|
| Request Header Injection | External system requests additional header | Header is added via requestHeaderMapToTargetAPI in From Client → To Backend script | Backend call is made with required header |
| Sensitive Field Masking | Response contains ID number | Sensitive field is masked with regex in To Client script | Masked data is returned to client |
| Dynamic Endpoint Routing | Some customers need to be routed to different backend URL | Script sets requestBackendUrlToTargetAPI field conditionally | Request is routed to appropriate target service |
| Conditional Error Return | Access must be blocked for specific API keys | Script sets responseErrorMessageToClient and statusCodeToClient=403 | Client receives 403 and customized message |
| JWT Enrichment | Need to generate context based on JWT claim value | Script reads claim and writes to customVariableMap | Subsequent policies use enriched value |
Configuring Policy Parameters
At this step, users can create a new policy or configure existing policy parameters to define access rules.Creating New Script Policy

Configuration Steps
Step 1: Navigate to Creation Page
Go to Development → Global Settings → Global Policies → Script Policy from the left menu and click the [+ Create] button in the upper right.Step 2: Enter Basic Information
Policy Status: Shows Active/Passive status. New policies are active by default. Name - Required: Enter unique name (example: Production_ScriptPolicy). System checks automatically. Green check: available, Red cross: existing name. Description: Explain the policy’s purpose (Max. 1000 characters). Example: “Adds campaign header in request pipeline.”Step 3: ExecutionType Selection
SelectSync or Async in Execution Type section:
- When
Syncis selected, script runs synchronously in gateway pipeline Asynctriggers side channel to avoid blocking client during long operations
Step 4: Script Language Configuration
SelectJavascript or Groovy under Script Language. Selection determines code editor syntax and IntelliSense.
Step 5: Script Body and Variable Management
- Write or paste your script in the code editor
- Copy fields like requestHeaderMapToTargetAPI, responseBodyTextToClient from variable tags with one click
- You can transfer data to other policies via customVariableMap
- Open test dialog with Try It button and run script with sample inputs
Step 6: Define Condition (Optional)
Switch to Condition tab. Conditions determine when the policy will be active. Examples:- Environment-based:
Header = X-Environment, Operator = Equals, Value = production - API Key-based:
Header = X-API-Key, Starts With = PROD- - Endpoint-based:
Path = /api/admin/*
Step 7: Error Message Customization (Optional)
Go to Error Message Customization tab and customize the message to be returned when access is denied. Default:Step 8: Save
Click [Save] button in upper right. Checklist:- Unique name
- Required fields filled
- At least one script body line present
- Policy is added to list
- Can be connected to APIs
- Automatically applied if global policy
Flow Variables
Flow variables and properties that you can use within Script Policy are explained in detail in the tables below.Request Variables (Client → Apinizer)
| Variable Name | Pipeline | Direction | Type | Access | Description | Example Usage |
|---|---|---|---|---|---|---|
| requestHeaderMapFromClient | Request | Client → Apinizer | Map<String, String> | Read | Used to access header values of the original version when the request from client reaches Apinizer. | String value= requestHeaderMapFromClient.get("Content-Type"); |
| requestUrlParamMapFromClient | Request | Client → Apinizer | Map<String, String> | Read | Used to access query parameter values of the original version when the request from client reaches Apinizer. | String value= requestUrlParamMapFromClient.get("param"); |
| requestBodyTextFromClient | Request | Client → Apinizer | String | Read | Used to access body value of the original version when the request from client reaches Apinizer. | String value= requestBodyTextFromClient; |
| requestFormUrlEncodedListFromClient | Request | Client → Apinizer | List<BasicNameValuePair> | Read | Used to access “Form-URL-Encoded” parameters of the original version when the request from client reaches Apinizer. | See Form URL-Encoded Usage section for detailed example. |
| requestFormDataListFromClient | Request | Client → Apinizer | List<ApinizerRequestBodyPart> | Read | Used to access “Form-Data” parameters of the original version when the request from client reaches Apinizer. | See Form Data Usage section for detailed example. |
Request Variables (Apinizer → Backend API)
| Variable Name | Pipeline | Direction | Type | Access | Description | Example Usage |
|---|---|---|---|---|---|---|
| requestHeaderMapToTargetAPI | Request | Apinizer → Backend API | Map<String, String> | Read, Write | Used to access header values of the request going from Apinizer to Backend API. Values in this field contain changes made in the request pipeline and may differ from the original request reaching Apinizer. | String value= requestHeaderMapToTargetAPI.get("Content-Type");requestHeaderMapToTargetAPI.put("Content-Type","application/json"); |
| requestUrlParamMapToTargetAPI | Request | Apinizer → Backend API | Map<String, String> | Read, Write | Used to access query parameter values of the request going from Apinizer to Backend API. Values in this field contain changes made in the request pipeline and may differ from the original request reaching Apinizer. | String value= requestUrlParamMapToTargetAPI.get("param");requestHeaderMapToTargetAPI.put("param","value"); |
| requestBodyTextToTargetAPI | Request | Apinizer → Backend API | String | Read, Write | Used to access body value of the request going from Apinizer to Backend API. Value in this field contains changes made in the request pipeline and may differ from the original request reaching Apinizer. | String value= requestBodyTextToTargetAPI;requestBodyTextToTargetAPI= "<body>"; |
| requestFormUrlEncodedListToTargetAPI | Request | Apinizer → Backend API | List<BasicNameValuePair> | Read, Write | Used to access “Form-Url Encoded” parameter values of the request going from Apinizer to Backend API. Values in this field contain changes made in the request pipeline and may differ from the original request reaching Apinizer. | See Form URL-Encoded Usage section for detailed example. |
| requestFormDataListToTargetAPI | Request | Apinizer → Backend API | List<ApinizerRequestBodyPart> | Read, Write | Used to access “Form-Data” parameter values of the request going from Apinizer to Backend API. Values in this field contain changes made in the request pipeline and may differ from the original request reaching Apinizer. | See Form Data Usage section for detailed example. |
| requestErrorMessageToTargetAPI | Request | Apinizer → Backend API | String | Write | If you want to interrupt the flow in the request pipeline and return a message to the client, enter the message to be returned in this variable. If this message has a value after script execution, the flow is interrupted and this value is returned to the client. | requestErrorMessageToTargetAPI= "<body>"; |
| statusCodeToTargetAPI | Request | Apinizer → Backend API | Integer | Write | If you want to interrupt the flow in the request pipeline and return a message to the client, enter the status code to be returned in this variable. Entering this value alone is not sufficient to stop the flow; requestErrorMessageToTargetAPI value must also be filled for the flow to stop. | statusCodeToTargetAPI=500; |
| requestBackendUrlToTargetAPI | Request | Apinizer → Backend API | String | Write | This field can be used if you want to change the context path of the Backend API URL. The default value of this variable is empty, and if a value is set to this variable, the target context path is changed with this value. To make requestBackendUrlToTargetAPI value empty, #EMPTY# value must be entered. When this value is used, the request is routed directly to the routing address without adding any path or query. | See Backend URL Modification section for detailed examples. |
Response Variables (Backend API → Apinizer)
| Variable Name | Pipeline | Direction | Type | Access | Description | Example Usage |
|---|---|---|---|---|---|---|
| responseHeaderMapFromTargetAPI | Response | Backend API → Apinizer | Map<String, String> | Read | Used to access header values of the original version when the result from Backend API reaches Apinizer. | String value= responseHeaderMapFromTargetAPI.get("Content-Type"); |
| responseBodyTextFromTargetAPI | Response | Backend API → Apinizer | String | Read | Used to access body value of the original version when the result from Backend API reaches Apinizer. | String value= responseBodyTextFromTargetAPI; |
| statusCodeFromTargetAPI | Response | Backend API → Apinizer | Integer | Read | Used to access status code value of the original version when the result from Backend API reaches Apinizer. | int value=statusCodeFromTargetAPI; |
Response Variables (Apinizer → Client)
| Variable Name | Pipeline | Direction | Type | Access | Description | Example Usage |
|---|---|---|---|---|---|---|
| responseHeaderMapToClient | Response | Apinizer → Client | Map<String, String> | Read, Write | Used to access header values of the response returning from Apinizer to Client. Values in this field contain changes made in the response pipeline and may differ from the original response returning to Apinizer. | String value= responseHeaderMapToClient.get("Content-Type");responseHeaderMapToClient.put("Content-Type","application/json"); |
| responseBodyTextToClient | Response | Apinizer → Client | String | Read, Write | Used to access body value of the response returning from Apinizer to Client. Value in this field contains changes made in the response pipeline and may differ from the original response returning to Apinizer. | String value= responseBodyTextToClient;responseBodyTextToClient= "<body>"; |
| responseErrorMessageToClient | Response | Apinizer → Client | String | Read, Write | If you want to interrupt the flow in the response pipeline and return a message to the client, enter the message to be returned in this variable. If this message has a value after script execution, the flow is interrupted and this value is returned to the client. | responseErrorMessageToClient= "<body>"; |
| statusCodeToClient | Response | Apinizer → Client | Integer | Read, Write | If you want to interrupt the flow in the response pipeline and return a message to the client, enter the status code to be returned in this variable. Entering this value alone is not sufficient to stop the flow; responseErrorMessageToClient value must also be filled for the flow to stop. | int value=statusCodeToClient;statusCodeToClient=401; |
Detailed Usage Examples
Form URL-Encoded Usage
Form Data Usage
Backend URL Modification
Example Scenario: Current routing address: “https://apinizer.com/api” Incoming request context path: “/findByStatus?param=value” In this case, the request goes to: “https://apinizer.com/api/findByStatus?param=value” When the following code is written:Important Notes
If Script type is Groovy:
- JsonSlurper for JSON message body,
- XMLSlurper for XML message body
Message Variables
Message variables and properties that you can use within Script Policy are explained in detail in the tables below.Request Pipeline Variables
| Flow Variables | Value Location | Data Type | Allowed Operation | Description | Example Usage |
|---|---|---|---|---|---|
| request_remoteAddress | Client → Apinizer | String | Read, Write | Used to access “Remote Address” value in the request from client. | String value= request_remoteAddress;request_remoteAddress= "<new value>"; |
| request_httpMethod | Client → Apinizer | String | Read, Write | Used to access “HTTP Method” value in the request from client. | String value= request_httpMethod;request_httpMethod= "<new value>"; |
| request_contentType | Client → Apinizer | String | Read, Write | Used to access “Content Type” value in the request from client. | String value= request_contentType;request_contentType= "<new value>"; |
| request_pathInfo | Client → Apinizer | String | Read, Write | Used to access “Path Info” value in the request from client. | String value=request_pathInfo ;request_pathInfo= "<new value>"; |
| request_contextPath | Client → Apinizer | String | Read, Write | Used to access “Context Path” value in the request from client. | String value= request_contextPath;request_contextPath= "<new value>"; |
| request_queryString | Client → Apinizer | String | Read, Write | Used to access “Query String” value in the request from client. | String value= request_queryString;request_queryString= "<new value>"; |
| request_remoteUser | Client → Apinizer | String | Read, Write | Used to access “Remote User” value in the request from client. | String value= request_remoteUser;request_remoteUser= "<new value>"; |
| request_usernameOrKey | Client → Apinizer | String | Read, Write | Used to access “Username or API Key” value in the request from client. If the request is authenticated by a security policy on Apinizer, this value is assigned by Apinizer, or a value can be assigned manually with data manipulation policies. | String value= request_usernameOrKey;request_usernameOrKey= "<new value>"; |
| request_requestedSessionId | Client → Apinizer | String | Read, Write | Used to access “Requested Session Id” value in the request from client. | String value= request_requestedSessionId;request_requestedSessionId= "<new value>"; |
| request_requestURI | Client → Apinizer | String | Read, Write | Used to access “Request URI” value in the request from client. | String value= request_requestURI;request_requestURI= "<new value>"; |
| request_isSoapToRest | Client → Apinizer | boolean | Read | Information about whether the request goes to an API Proxy with SoapToRest conversion after being interpreted in Apinizer. This variable’s value can be “true” or “false”. | boolean value= request_isSoapToRest; |
| request_isApiProxy | Client → Apinizer | boolean | Read | Information about whether the request reaches API Proxy after being interpreted in Apinizer. This variable’s value can be “true” or “false”. | boolean value= request_isApiProxy; |
| request_data_isXwwwFormUrlEncoded | Client → Apinizer | boolean | Read, Write | Information about whether the request contains application/x-www-form-urlencoded header after being interpreted in Apinizer. This variable’s value can be “true” or “false”. | boolean value= request_data_isXwwwFormUrlEncoded;request_data_isXwwwFormUrlEncoded= true/false; |
Response Pipeline Variables
| Flow Variables | Value Location | Data Type | Allowed Operation | Description | Example Usage |
|---|---|---|---|---|---|
| response_data_isByteArray | Backend API → Apinizer | boolean | Read, Write | Information about whether the response contains “byte array” data after being interpreted in Apinizer. This variable’s value can be “true” or “false”. | boolean value= response_data_isByteArray;response_data_isByteArray= true/false; |
| response_encoding_gzip | Backend API → Apinizer | boolean | Read, Write | Information about whether the response data format is “gzip” after being interpreted in Apinizer. This variable’s value can be “true” or “false”. If the value is false and set to true in the script, the data returned to the client is compressed in gzip format. | boolean value= response_encoding_gzip;response_encoding_gzip= true/false; |
| response_statusCode | Backend API → Apinizer | Integer | Read, Write | Contains the status code value of the response from Backend API. | Integer value= response_statusCode;response_statusCode= 400; |
Message Variables
| Flow Variables | Value Location | Data Type | Allowed Operation | Description | Example Usage |
|---|---|---|---|---|---|
| message_correlationId | Client → Apinizer | String | Read, Write | When the request from client reaches Apinizer, Apinizer gives the request a unique ID and this ID is also added to the response. This unique ID value can be accessed with this variable. | String value= message_correlationId;message_correlationId= "<new value>"; |
| environment_id | Client → Apinizer | String | Read | Environment ID information where API traffic is received and responded. | String value= environment_id; |
| environment_name | Client → Apinizer | String | Read | Environment name information where API traffic is received and responded. | String value= environment_name; |
Environment Variables
| Flow Variables | Value Location | Data Type | Allowed Operation | Description | Example Usage |
|---|---|---|---|---|---|
| apiProxyGroup_id | Client → Apinizer | String | Read | If the request from client is handled by API Proxy Group, used to access API Proxy Group’s ID information. | String value= apiProxyGroup_id; |
| apiProxy_id | Client → Apinizer | String | Read | If the request from client is handled by API Proxy, used to access API Proxy’s ID information. | String value= apiProxy_id; |
| apiMethod_id | Client → Apinizer | String | Read | If the request from client is handled by API Proxy Method, used to access API Proxy Method’s ID information. | String value= apiMethod_id; |
| dateTime_year | Runtime | Integer | Read | Used to access year information at runtime. | Integer value= dateTime_year; |
| dateTime_month | Runtime | Integer | Read | Used to access month information at runtime. | Integer value= dateTime_month; |
| dateTime_hour | Runtime | Integer | Read | Used to access hour information at runtime. Takes values between 0 and 23. | Integer value= dateTime_hour; |
| environment_certificateMap | Runtime | Map<String, X509Certificate> | Read | Used to access “X509Certificate” values loaded in the environment at runtime. The entity name is used for access. | import java.security.cert.X509Certificate;X509Certificate obj= environment_certificateMap.get("obj-name"); |
Credential Variables
| Flow Variables | Value Location | Data Type | Allowed Operation | Description | Example Usage |
|---|---|---|---|---|---|
| credential_username | Runtime | String | Read | Used to access “username” information of the credential set before the policy. If credential doesn’t exist or is not set, its value is null. | String value= credential_username; |
| credential_email | Runtime | String | Read | Used to access “email” information of the credential set before the policy. If credential doesn’t exist or is not set, its value is null. | String value= credential_email; |
| credential_secretKey | Runtime | javax.crypto.SecretKey | Read | Used to access “Secret Key” information of the credential set before the policy. If credential doesn’t exist or is not set, its value is null. | javax.crypto.SecretKey value=credential_secretKey; |
Custom Variables
There may be a need to temporarily define variables with policies on the Request or Response pipeline and use them in the next policy. In this case, thecustomVariableMap variable is used.
| Variable Name | Type | Access | Description | Example Usage |
|---|---|---|---|---|
| customVariableMap | Map<String, String> | Read, Write | May need to temporarily define variables with policies in Request or Response pipeline and use them in the next policy. In this case, “customVariableMap” variable is used. For example; You may need to access and change the value of the “testVariable” variable created with business rule policy in the policy before the script policy of an API Proxy in the script policy. In this case, the value assigned to this variable is read by saying customVariableMap.get(“testVariable”). Similarly, to create a custom variable in the script policy, it should be used as customVariableMap.put(“testVariable”,“test value”). Thus, in the next policy, the value added in the script policy can be accessed by creating a variable of custom variable type and named “testVariable”. | String value = customVariableMap.get("testVariable");customVariableMap.put("testVariable", "test value"); |
Important Restrictions
Deleting the Policy
For steps to delete this policy and operations to be performed when it is in use, see the Removing Policy from Flow section on the Policy Management page.Exporting/Importing the Policy
For export and import steps of this policy, see the Export/Import page.Connecting Policy to API
For the process of how to connect this policy to APIs, see the Connecting Policy to API section on the Policy Management page.Advanced Features
| Feature | Description and Steps |
|---|---|
| Script Test Dialog | - Opens with Try It button.- Sample data is entered by selecting Request/Response region. - Execution result is examined as JSON and script is improved. |
| Context Value Library | - Category is selected from Context Values select component.- When selection is made, value is copied to clipboard. - Environment information is obtained by using directly in script. |
| WebSocket/gRPC Adaptation | - If proxy type is WebSocket/gRPC, variable lists are automatically narrowed. - Appropriate message flow variables are provided. - Script can manage errors in these protocols. |
Best Practices
Things to Do and Best Practices
| Category | Description / Recommendations |
|---|---|
| Script Configuration | Bad: Writing all logic in a single function. Good: Breaking logic into functions. Best: Keeping common functions in shared modules and keeping script simple. |
| Error Management | Bad: Swallowing errors and waiting for default 500. Good: Setting responseErrorMessageToClient in error cases.Best: Setting both message and statusCodeToClient value according to business scenario. |
| Versioning | Bad: Changing script directly in prod environment. Good: Taking export before changes. Best: Importing new version in test environment and deploying, then moving to live. |
| Condition Usage | Bad: Allowing policy to run on every request. Good: Adding basic path condition. Best: Specifying conditions with header, method, and environment combinations. |
| Performance Monitoring | Bad: Not tracking completion time of async scripts. Good: Monitoring script durations in logs. Best: Profiling and optimizing script if latency increases, using cache if needed. |
Security Best Practices
| Security Area | Description / Warnings |
|---|---|
| Data Masking | Mask personal data in response, perform regex validation in script. |
| Input Validation | Check expected format in parameters taken into script, return error code if incorrect. |
| Exception Management | Catch unexpected errors with try/catch blocks, log them, provide limited information to user. |
| External Calls | If you will make external system calls within script, set timeout and retry limits; prefer async mode. |
| Authorization Logic | Prevent unauthorized access by centralizing header or JWT claim checks in script. |
Things to Avoid
| Category | Description / Warnings |
|---|---|
| Long-Running Operations | Why avoid: Blocks gateway threads in Sync mode. Alternative: Switch to Async mode or delegate to background service. |
| Hard-coded URL | Why avoid: Script breaks when environment changes. Alternative: Use context value or environment variables. |
| Untested Code in Global Script | Why avoid: Affects all API Proxy traffic. Alternative: Test as local script first, then globalize. |
| Leaving Error Message Empty | Why avoid: Client receives ambiguous error. Alternative: Set descriptive message in Error Message Customization section. |
Performance Tips
| Criterion | Recommendation / Impact |
|---|---|
| Script Complexity | Recommendation: Keep loops and parsing operations minimal. Impact: Gateway latency decreases. |
| Data Structures | Recommendation: Use lightweight map instead of ready libraries for large JSON transformations. Impact: Reduces memory usage. |
| Condition Engine | Recommendation: Do not define conditions when not needed; if defined, keep specific. Impact: Policy evaluation time is optimized. |
| Async Usage | Recommendation: Select Async in scripts containing network calls or long IO. Impact: Reduces client wait time, increases throughput. |
| Test and Monitoring | Recommendation: Track duration metric in Script Test module, log situations above limit. Impact: Performance degradations are detected early. |
Frequently Asked Questions (FAQ)
| Category | Question | Answer |
|---|---|---|
| General | When should Script Policy be used? | Should be used when you want to solve data transformation and business logic needs at gateway level that are not covered by rule engine or ready policies. |
| General | How should I decide between Groovy and Javascript? | Make selection according to team expertise, existing libraries, and operations to be performed in script; if you are close to Java ecosystem choose Groovy, if you will work with frontend team you can choose Javascript. |
| Technical | What happens if script does not complete in Async mode? | Default response is returned until async process completes; results are monitored in logs, retry mechanism can be added if needed. |
| Technical | How does Context Value work? | When EnumScriptContextValue values are selected, relevant environment/metadata information is copied to clipboard; you can access runtime data by using as string within script. |
| Usage | Does script test screen affect real traffic? | No, test screen works in isolation; simulates script on entered sample data. |
| Usage | Can script policy be shared across multiple API Proxies? | When created globally, it can be used in all API Proxies; local copies provide proxy-based customization. |

