Skip to main content
This document explains the detailed usage of a specific policy. If you are using Apinizer policy structure for the first time or want to learn the general working principles of policies, we recommend reading the What is Policy? page first.

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 (API Proxy Server) request pipeline.
  • Script Policy enables centralized management of operations such as masking, enrichment, or adapting error messages for incoming data 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 maintains performance by engaging only in specified endpoint or header combinations through the condition engine.

Working Principle

  1. Request Arrival: For each HTTP/HTTPS request arriving at the API Gateway, the source IP address of the request is identified.
  2. Policy Check: If the 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 used or is Apinizer default?
  3. Script Engine Execution: According to the selected executionType (SYNC/ASYNC) and scriptLanguage (Groovy/Javascript) values, the script is executed in the determined pipeline region; request/response body, header, and parameter maps can be updated.
  4. Decision Making:
    • Match Found: Updated message components as a result of the script are written back to the pipeline, defined statusCode and message are returned in case of error.
    • No Match: Script is skipped, request/response continues with default flow.
  5. Error Handling: Customizable HTTP status code and error message are returned for requests that do not comply with the policy rule.

Features and Capabilities

Basic Features

  • ExecutionType Management (Sync/Async): Determines whether the script will be executed synchronously or in the background; asynchronous mode does not block the endpoint in long-running operations.
  • Dual Script Language Support: Enables teams to use the language they are familiar with by choosing between Groovy and Javascript.
  • Context Variable Library: Provides ready variable maps for From Client, To Backend, From Backend, and To Client flows; readable/writable fields are clearly separated.
  • Active/Passive Status Control: Easily change the active or passive status of the policy (active/passive toggle). In passive state, the policy is not applied but its configuration is preserved.
  • Condition-Based Application: Determine when the policy will be applied by creating complex conditions with Query Builder (e.g., only for specific endpoints or header values).

Advanced Features

  • Script Test Laboratory: Running scripts with sample header/param/body data for different pipeline segments and examining results with integrated test window.
  • Dependency Tracking: Seeing which API Proxies or groups the policy is used in with Used Proxies/Policy Groups sections and performing change impact analysis.
  • Dynamic Context Value Selection: Automatic copying from EnumScriptContextValue to use date, environment, or proxy metadata information within the script.
  • 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 Group. Bulk policy assignment to Proxy Groups. Centralized update and deployment operations.
  • Deploy and Versioning: Deploy policy changes to live environment. See which API Proxies use it (Policy Usage). Proxy Group and Policy Group usage reports.

Usage Scenarios

ScenarioSituationSolution (Policy Application)Expected Behavior / Result
Request Header InjectionExternal system requests additional headersrequestHeaderMapToTargetAPI['X-Partner-Code']='ACME' is written in From Client → To Backend script.Backend call is made with required headers.
Sensitive Field MaskingID number is present in responseSensitive field is replaced with **** using regex in To Client script.Masked data is returned to client.
Dynamic Endpoint RoutingSome customers should be routed to different backend URLScript sets customizedBackendResourceUrl field according to condition.Request is routed to appropriate target service.
Conditional Error ReturnAccess should be stopped for certain API keysScript assigns responseErrorMessageToClient and statusCodeToClient=403.Client receives 403 and customized message.
JWT EnrichmentNeed to produce context based on JWT claim valueScript reads claim and writes customVariableMap['roleLevel']=....Subsequent policies use enriched value.
Header-Based Rate FlagThrottling should be triggered in headers coming to certain sourceScript analyzes header and adds requestHeaderMapToTargetAPI['X-Throttle']='true'.Throttling policies read the flag and limit speed.
Advanced Logging (optional)Need to prepare request/response log for audit purposesScript writes customVariableMap['auditPayload']=JSON.stringify(...).Log collection policy uses the data.

Configuring Policy Parameters

At this step, users can create a new policy or configure existing policy parameters to define access rules. The defined parameters directly affect how the policy works (e.g., which IPs will be allowed, geographical restrictions, conditional activations, etc.). This way, the policy can be customized according to organization-specific requirements and managed centrally.

Creating a New Script Policy

Script Policy

Configuration Steps

StepDescription / Operation
Step 1: Going to Creation Page- Go to Development → Global Settings → Global Policies → Script Policy section from the left menu.
- Click the [+ Create] button at the top right.
Step 2: Entering Basic InformationPolicy Status: Shows Active/Passive status. New policies are active by default.

Name (Required): Example: Production_ScriptPolicy
- Enter a unique name, it cannot start with a space.
- System automatically checks. Green checkmark: available. Red cross: existing name.

Description: Example: “Adds campaign header in request pipeline”
- Max. 1000 characters.
- Explain the purpose of the policy.
Step 3: ExecutionType Selection- Select Sync or Async in the Execution Type section.
- When Sync is selected, script runs synchronously in gateway pipeline.
- Async is suitable for not keeping client waiting in long-running operations and triggers side channel.
Step 4: Script Language Configuration- Select Javascript or Groovy under Script Language.
- Selection determines syntax and IntelliSense of code editor.
- Changing language does not affect existing script body but updates execution mode.
Step 5: Script Body and Variable Management- Write or paste your script in the code editor.
- Copy fields like requestHeaderMapToTargetAPI, responseBodyTextToClient from variable tags to clipboard with one click.
- You can transfer data to other policies through customVariableMap.
- Open test dialog with Try It button and run script with sample inputs.
Step 6: Defining Condition (Optional)- Go to the 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/*
If no condition is defined, the policy is always active

For details, you can refer to: Conditions
Step 7: Customizing Error Message (Optional)- Go to the Error Message Customization tab.
- Customize the message to be returned when access is denied.

Default:
{ "statusCode": 403, "message": "[Default error message]" }

Custom:
{ "statusCode": 403, "errorCode": "[CUSTOM_ERROR_CODE]", "message": "[Custom message]" }
Step 8: Saving- Click the [Save] button at the top right.

Checklist: Unique name. Required fields filled. At least one script body line exists

Result:
- Policy is added to the list.
- Can be linked to APIs.
- If it’s a global policy, it is automatically applied.
For the description of Conditions and Error Message Customization panels, you can review the Conditions and Error Message Customization sections on the What is Policy? page.

Deleting the Policy

For the deletion steps of this policy and the operations to be applied when it is in use, you can refer to the Removing Policy from Flow section on the Policy Management page.

Exporting/Importing the Policy

For the export and import steps of this policy, you can refer to the Export/Import page.

Linking the Policy to API

For the process of how this policy will be linked to APIs, you can refer to the Linking Policy to API section on the Policy Management page.

Advanced Features

FeatureDescription 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

CategoryDescription / Recommendations
Script ConfigurationBad: Writing all logic in a single function.
Good: Breaking logic into functions.
Best: Keeping common functions in shared modules and keeping script simple.
Error ManagementBad: Swallowing errors and waiting for default 500.
Good: Setting responseErrorMessageToClient in error cases.
Best: Setting both message and statusCodeToClient value according to business scenario.
VersioningBad: 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 UsageBad: Allowing policy to run on every request.
Good: Adding basic path condition.
Best: Specifying conditions with header, method, and environment combinations.
Performance MonitoringBad: 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 AreaDescription / Warnings
Data MaskingMask personal data in response, perform regex validation in script.
Input ValidationCheck expected format in parameters taken into script, return error code if incorrect.
Exception ManagementCatch unexpected errors with try/catch blocks, log them, provide limited information to user.
External CallsIf you will make external system calls within script, set timeout and retry limits; prefer async mode.
Authorization LogicPrevent unauthorized access by centralizing header or JWT claim checks in script.

Things to Avoid

CategoryDescription / Warnings
Long-Running OperationsWhy avoid: Blocks gateway threads in Sync mode.
Alternative: Switch to Async mode or delegate to background service.
Hard-coded URLWhy avoid: Script breaks when environment changes.
Alternative: Use context value or environment variables.
Untested Code in Global ScriptWhy avoid: Affects all API Proxy traffic.
Alternative: Test as local script first, then globalize.
Leaving Error Message EmptyWhy avoid: Client receives ambiguous error.
Alternative: Set descriptive message in Error Message Customization section.

Performance Tips

CriterionRecommendation / Impact
Script ComplexityRecommendation: Keep loops and parsing operations minimal.
Impact: Gateway latency decreases.
Data StructuresRecommendation: Use lightweight map instead of ready libraries for large JSON transformations.
Impact: Reduces memory usage.
Condition EngineRecommendation: Do not define conditions when not needed; if defined, keep specific.
Impact: Policy evaluation time is optimized.
Async UsageRecommendation: Select Async in scripts containing network calls or long IO.
Impact: Reduces client wait time, increases throughput.
Test and MonitoringRecommendation: Track duration metric in Script Test module, log situations above limit.
Impact: Performance degradations are detected early.

Frequently Asked Questions (FAQ)

CategoryQuestionAnswer
GeneralWhen 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.
GeneralHow 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.
TechnicalWhat 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.
TechnicalHow 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.
UsageDoes script test screen affect real traffic?No, test screen works in isolation; simulates script on entered sample data.
UsageCan 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.