AltScore
Workflow Builder/Task Reference

Custom Tasks

Custom tasks extend the capabilities of Workflow Builder V2 by allowing you to execute arbitrary code, call external APIs, and integrate with legacy systems. This guide covers the three primary custom task types: Python, HTTP, and SOAP.

Python Task

The Python Task enables you to execute custom Python code within your workflow. This is ideal for complex calculations, data transformations, and business logic that cannot be achieved with built-in tasks.

Purpose

Use Python tasks when you need to:

  • Perform complex mathematical calculations
  • Transform data structures between incompatible formats
  • Implement custom business logic and rules
  • Process arrays and collections with specialized algorithms
  • Handle edge cases that standard tasks cannot address

Writing Code

Python tasks receive input data through an inputs dictionary and return results that become the task output.

Basic Structure:

# Access input values
value = inputs.get('variable_name', default_value)
 
# Perform your logic
result = process(value)
 
# Return output (becomes task output)
return result

Complete Example - Risk Score Calculation:

# Calculate risk score based on financial metrics
income = inputs.get('annual_income', 0)
debt = inputs.get('total_debt', 0)
employment_years = inputs.get('employment_years', 0)
 
# Calculate debt-to-income ratio
if income > 0:
    debt_ratio = debt / income
else:
    debt_ratio = 1.0
 
# Apply business rules
risk_score = 100
 
# Deduct points for high debt ratio
if debt_ratio > 0.5:
    risk_score -= 30
elif debt_ratio > 0.3:
    risk_score -= 15
 
# Add points for employment stability
if employment_years >= 5:
    risk_score += 20
elif employment_years >= 2:
    risk_score += 10
 
# Determine risk level
if risk_score >= 80:
    risk_level = 'low'
elif risk_score >= 50:
    risk_level = 'medium'
else:
    risk_level = 'high'
 
return {
    'debt_ratio': round(debt_ratio, 4),
    'risk_score': risk_score,
    'risk_level': risk_level,
    'factors': {
        'debt_impact': -30 if debt_ratio > 0.5 else (-15 if debt_ratio > 0.3 else 0),
        'employment_impact': 20 if employment_years >= 5 else (10 if employment_years >= 2 else 0)
    }
}

Available Libraries

The Python runtime includes the standard library and commonly used external packages:

PackageVersionUse Case
pandas2.xData manipulation and analysis
numpy1.xNumerical computations
datetimestdlibDate and time operations
jsonstdlibJSON parsing and serialization
restdlibRegular expressions
mathstdlibMathematical functions
decimalstdlibPrecise decimal arithmetic
collectionsstdlibSpecialized container types

Additional packages may be available depending on your platform configuration. Contact your administrator to request specific packages for your workflows.

Input/Output Schema

Define explicit schemas to enable variable autocomplete and validation:

Input Schema Configuration:

FieldTypeDescription
namestringVariable name as it appears in inputs dict
typestringData type: string, number, boolean, object, array
requiredbooleanWhether the input must be provided
descriptionstringDocumentation for the input

Output Schema Configuration:

FieldTypeDescription
namestringOutput field name
typestringData type of the output field
schemaobjectJSON Schema for complex objects

Example Schema Definition:

{
  "inputs": [
    {
      "name": "annual_income",
      "type": "number",
      "required": true,
      "description": "Borrower's annual income in USD"
    },
    {
      "name": "total_debt",
      "type": "number",
      "required": true,
      "description": "Total outstanding debt in USD"
    }
  ],
  "outputs": [
    {
      "name": "risk_level",
      "type": "string",
      "description": "Calculated risk category: low, medium, or high"
    },
    {
      "name": "debt_ratio",
      "type": "number",
      "description": "Debt-to-income ratio"
    }
  ]
}

Timeout Configuration

SettingDefaultMaximumDescription
Execution Timeout30 seconds120 secondsMaximum time for code execution

Long-running computations should be optimized or split into multiple tasks. If your code consistently approaches the timeout limit, consider refactoring the logic or processing data in smaller batches.

Security

Python tasks run with the following restrictions:

  • No filesystem access: Cannot read or write files
  • No network access: Cannot make HTTP requests (use HTTP Task instead)
  • No subprocess execution: Cannot spawn child processes
  • No imports: Only pre-approved packages are available

HTTP Task

The HTTP Task enables your workflow to communicate with external REST APIs. Use it to fetch data, submit information, or trigger actions in third-party systems.

Purpose

Use HTTP tasks to:

  • Retrieve data from external APIs
  • Submit application data to partner systems
  • Trigger webhooks and notifications
  • Integrate with microservices in your architecture
  • Query databases through REST interfaces

Configuration

Configure HTTP tasks through the Properties Panel with the following options:

Basic Configuration:

PropertyDescriptionExample
URLEndpoint to call (supports variable interpolation)https://api.example.com/v1/users
MethodHTTP methodGET, POST, PUT, PATCH, DELETE
HeadersKey-value pairs for request headersContent-Type: application/json
Query ParametersURL query string parameterspage=1&limit=50
BodyRequest payload (for POST, PUT, PATCH)JSON, form data, or raw

Example Configuration:

{
  "url": "https://api.example.com/users/{{nodes.fetch.outputs.user_id}}",
  "method": "GET",
  "headers": {
    "Authorization": "Bearer {{workflow.variables.api_token}}",
    "Content-Type": "application/json",
    "X-Request-ID": "{{workflow.variables.request_id}}"
  },
  "queryParams": {
    "include": "profile,settings",
    "format": "full"
  }
}

POST Request with Body:

{
  "url": "https://api.example.com/applications",
  "method": "POST",
  "headers": {
    "Authorization": "Bearer {{workflow.variables.api_token}}",
    "Content-Type": "application/json"
  },
  "body": {
    "borrower_id": "{{workflow.variables.borrower_id}}",
    "loan_amount": "{{nodes.calculate.outputs.approved_amount}}",
    "term_months": 36,
    "submitted_at": "{{workflow.variables.timestamp}}"
  }
}

Authentication Methods

The HTTP task supports multiple authentication schemes:

Bearer Token:

{
  "headers": {
    "Authorization": "Bearer {{workflow.variables.access_token}}"
  }
}

Basic Authentication:

{
  "auth": {
    "type": "basic",
    "username": "{{workflow.variables.api_username}}",
    "password": "{{workflow.variables.api_password}}"
  }
}

API Key (Header):

{
  "headers": {
    "X-API-Key": "{{workflow.variables.api_key}}"
  }
}

API Key (Query Parameter):

{
  "queryParams": {
    "api_key": "{{workflow.variables.api_key}}"
  }
}

Never hardcode credentials in your HTTP task configuration. Always use workflow variables for API keys, tokens, and passwords. Credentials stored in workflow variables are encrypted at rest.

Response Handling

HTTP task responses are automatically parsed and made available to downstream tasks:

Output FieldTypeDescription
statusnumberHTTP status code (200, 404, 500, etc.)
headersobjectResponse headers as key-value pairs
bodyobject/stringParsed response body (JSON parsed automatically)
durationnumberRequest duration in milliseconds

Accessing Response Data:

{{nodes.http_task.outputs.status}}
{{nodes.http_task.outputs.body.data.user.name}}
{{nodes.http_task.outputs.headers.x-rate-limit-remaining}}

Timeout and Retry

SettingDefaultMaximumDescription
Timeout30 seconds300 seconds (5 minutes)Time to wait for response
Retry Count05Number of retry attempts on failure
Retry Delay1 second30 secondsWait time between retries

Retry Policy Configuration:

{
  "retry": {
    "enabled": true,
    "maxAttempts": 3,
    "delay": 2000,
    "backoffMultiplier": 2,
    "retryOn": [500, 502, 503, 504]
  }
}

Enable retries for external APIs that may experience intermittent failures. Use exponential backoff (backoffMultiplier > 1) to avoid overwhelming a struggling service.

SOAP Task

The SOAP Task enables integration with legacy SOAP web services. Use this when connecting to enterprise systems that expose SOAP/XML interfaces.

Purpose

Use SOAP tasks to:

  • Integrate with legacy enterprise systems
  • Connect to government and financial institution APIs
  • Access services that only provide WSDL interfaces
  • Communicate with older ERP and CRM systems

Configuration

PropertyDescriptionExample
WSDL URLLocation of the WSDL definitionhttps://service.example.com/api?wsdl
OperationThe SOAP operation to invokeGetCustomerDetails
Request BodyXML template for the requestSee example below
HeadersSOAP headers for authenticationWS-Security tokens

Example Configuration:

{
  "wsdlUrl": "https://legacy.bank.com/services/customer?wsdl",
  "operation": "GetCustomerDetails",
  "soapHeaders": {
    "Security": {
      "UsernameToken": {
        "Username": "{{workflow.variables.soap_username}}",
        "Password": "{{workflow.variables.soap_password}}"
      }
    }
  }
}

Request Body Template:

<GetCustomerDetailsRequest xmlns="http://legacy.bank.com/schemas">
  <CustomerId>{{workflow.variables.customer_id}}</CustomerId>
  <IncludeAccounts>true</IncludeAccounts>
  <IncludeHistory>false</IncludeHistory>
</GetCustomerDetailsRequest>

XML Namespace Handling

SOAP services often require specific XML namespaces. Configure them in the task settings:

{
  "namespaces": {
    "cust": "http://legacy.bank.com/schemas/customer",
    "common": "http://legacy.bank.com/schemas/common"
  }
}

Response Parsing

SOAP responses are automatically parsed from XML to JSON:

Output FieldTypeDescription
bodyobjectParsed response body as JSON
rawstringOriginal XML response
headersobjectSOAP response headers

Complex XML structures with attributes and namespaces are flattened to JSON. Test your SOAP tasks thoroughly to understand the exact output structure.

Input/Output Schemas

All custom tasks benefit from explicit schema definitions. Schemas enable:

  • Variable autocomplete: The editor suggests available fields
  • Type validation: Catch type mismatches before execution
  • Documentation: Self-documenting task interfaces
  • Error prevention: Identify missing required inputs early

Defining Input Schemas

{
  "inputs": [
    {
      "name": "borrower_id",
      "type": "string",
      "required": true,
      "description": "Unique identifier for the borrower"
    },
    {
      "name": "include_history",
      "type": "boolean",
      "required": false,
      "default": false,
      "description": "Whether to include transaction history"
    },
    {
      "name": "filters",
      "type": "object",
      "required": false,
      "schema": {
        "type": "object",
        "properties": {
          "start_date": { "type": "string", "format": "date" },
          "end_date": { "type": "string", "format": "date" },
          "status": { "type": "array", "items": { "type": "string" } }
        }
      },
      "description": "Optional filters for the query"
    }
  ]
}

Defining Output Schemas

{
  "outputs": [
    {
      "name": "result",
      "type": "object",
      "schema": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean" },
          "data": {
            "type": "object",
            "properties": {
              "id": { "type": "string" },
              "score": { "type": "number" },
              "category": { "type": "string" }
            }
          },
          "errors": {
            "type": "array",
            "items": { "type": "string" }
          }
        }
      }
    }
  ]
}

Supported Types

TypeDescriptionExample
stringText values"hello"
numberInteger or decimal numbers42, 3.14
booleanTrue or falsetrue
objectJSON objects{"key": "value"}
arrayLists of values[1, 2, 3]

Timeout Configuration

Each task type has specific timeout constraints:

Task TypeDefaultMinimumMaximum
Python30s5s120s
HTTP30s5s300s
SOAP60s10s300s

Configuring Timeouts

In the task Properties Panel, navigate to the Advanced tab to configure timeout:

{
  "timeout": {
    "duration": 45000,
    "unit": "milliseconds"
  }
}

Tasks that exceed their timeout are terminated and marked as failed. The workflow continues based on your error handling configuration (fail workflow, continue with default, or follow error branch).

Security Considerations

Credential Management

  • Never hardcode credentials in task configurations
  • Use workflow variables with the "secret" flag for sensitive values
  • Rotate API keys regularly and update workflow variables
  • Use least-privilege API keys that only have required permissions

Python Task Security

  • Code runs without network or filesystem access
  • Only pre-approved libraries are available
  • Execution time and resources are limited
  • Code is not persisted after execution

HTTP Task Security

  • All requests are logged for audit purposes
  • Rate limiting prevents abuse of external APIs
  • SSL/TLS is enforced for all HTTPS endpoints
  • Certificate validation is enabled by default

SOAP Task Security

  • WS-Security standards supported for authentication
  • Certificate-based authentication available
  • Request/response logging for compliance

Audit Logging

All custom task executions are logged with:

  • Timestamp and execution ID
  • Input parameters (secrets redacted)
  • Output summary
  • Duration and status
  • Error details if applicable

Audit logs are retained according to your organization's data retention policy. Contact your administrator to access execution logs for compliance and debugging purposes.

Best Practices

Python Tasks

  1. Keep code focused: Each Python task should do one thing well
  2. Handle edge cases: Always provide default values for optional inputs
  3. Return structured data: Use dictionaries with clear field names
  4. Avoid infinite loops: Ensure all loops have proper termination conditions
  5. Test locally first: Validate your logic before deploying to workflows

HTTP Tasks

  1. Use variable interpolation: Never hardcode URLs or credentials
  2. Enable retries: Configure retry policies for external API calls
  3. Set appropriate timeouts: Balance between reliability and responsiveness
  4. Handle errors gracefully: Use conditional branches for error responses
  5. Log request IDs: Include correlation IDs for debugging

SOAP Tasks

  1. Cache WSDL references: Avoid fetching WSDL on every execution
  2. Handle namespace carefully: Verify namespace mappings match the service
  3. Test with the provider: Validate requests against the actual service
  4. Plan for deprecation: Legacy services may be retired; have alternatives ready