BlocktionBlocktion Docs

Documentation

Handlers

Create, validate, publish, and execute code-powered handlers

What is a Handler?

A handler is executable code plus metadata that exposes one or more actions used by blocks and workflows. Each action can define parameter and output schemas that are auto-parsed from code when possible. Handlers run in a secure sandbox (Docker) by default, and trusted mode is used for validated or system handlers. You can create, validate, publish, and execute handlers via the API.

Handlers are the core execution units in Blocktion that contain the actual business logic. They are Python classes that inherit from BaseHandler and implement specific actions. Each handler can support multiple actions, and the platform automatically parses parameter and output schemas from well-formatted docstrings.

Key Features

  • • Action-specific method implementations
  • • Automatic schema parsing from docstrings
  • • Security validation and sandbox execution
  • • Support for multiple execution modes

Use Cases

  • • HTTP API integrations
  • • Database operations
  • • Data processing and transformation
  • • External service connections

Handler Concepts

Understanding the core concepts that make handlers powerful and secure.

What is a Handler?

A handler encapsulates executable code plus metadata (actions, schemas, execution mode) used by blocks and workflows.

Actions & Schemas

Each handler exposes one or more actions with parameter/output schemas that can be auto-parsed from code.

Execution Modes

Run in sandbox (Docker) by default for safety, or trusted mode for validated/system handlers.

Security & Validation

Validation checks code safety and structure; publishing requires passing validations.

Handler Structure

Handlers follow a specific structure with clear patterns for implementation and documentation.

Class Structure

Basic structure of a handler class

SUPPORTED_ACTIONSList[str]

List of actions this handler supports

Action Methodsasync def action_name()

Each action is implemented as an async method

Docstring FormatArgs: / Returns:

Structured docstrings for automatic schema parsing

Execution Modes

Different execution environments for handlers

Sandbox Mode

Default mode with Docker isolation and security restrictions

Docker isolationResource limitsSecurity validation

Trusted Mode

For validated system handlers with fewer restrictions

Direct executionHigher performanceSystem access

Example Handler Implementation

A complete example of a handler with proper structure and documentation

class HttpHandler(BaseHandler):
    """
    Handler for HTTP operations including REST API calls.
    """
    
    SUPPORTED_ACTIONS = ["get", "post", "put", "delete"]
    
    async def get(
        self,
        params: Dict[str, Any],
        context: ExecutionContext
    ) -> Dict[str, Any]:
        """
        Execute HTTP GET request.
        
        Args:
            - url (string): The URL to make the request to
            - headers (object): Optional HTTP headers
            - params (object): Optional query parameters
            
        Returns:
            - status_code (number): HTTP response status code
            - body (object): Response body data
            - headers (object): Response headers
        """
        # Implementation here
        pass

Docstring Parsing

The platform automatically parses parameter and output schemas from well-formatted docstrings.

Args Section Format

How to document parameters in your handler methods

Parameter Documentation

"""
Args:
    - param_name (type): Description of the parameter
    - another_param (optional_type): Description with optional indicator
    - nested_param (object): Complex parameter with nested structure
        - sub_field (string): Nested field description
        - sub_value (number): Another nested field
"""
  • • Use bullet points (-) for each parameter
  • • Include type in parentheses after parameter name
  • • Support nested object documentation
  • • Optional parameters are automatically detected

Returns Section Format

How to document return values and output schemas

Output Documentation

"""
Returns:
    - field_name (type): Description of return field
    - result (object): Description of result object
    - status (string): Success or error status
    - data (array): Array of processed items
"""
  • • Document all return fields with types
  • • Use consistent naming conventions
  • • Include descriptions for clarity
  • • Support complex nested structures

Supported Types

Types that are automatically recognized and converted to JSON Schema

Primitive Types

stringnumberintegerbooleannull

Complex Types

objectarrayany

Security Features

Comprehensive security validation ensures safe execution of user-created handlers.

Static Code Analysis

AST-based analysis detects dangerous patterns and imports

Dangerous Imports

ossyssubprocessevalexec

Dangerous Functions

openfileinputcompile

Sandbox Execution

Docker-based isolation with resource limits and restrictions

Memory Limit128MB default
Timeout30s default
Network AccessConfigurable
File SystemRestricted

Security Validation Process

Multi-step validation ensures code safety before execution

Validation Steps

  • 1. Syntax Check - Valid Python syntax
  • 2. Import Analysis - Check for dangerous imports
  • 3. Function Analysis - Detect dangerous function calls
  • 4. Pattern Detection - Identify suspicious code patterns
  • 5. Schema Validation - Validate parameter/output schemas

Security Levels

  • Low - Basic validation, sandbox execution
  • Medium - Enhanced checks, limited permissions
  • High - Strict validation, minimal permissions
  • System - Trusted mode for platform handlers

Testing and Validation

Comprehensive testing tools and validation processes ensure handler reliability.

Validation Endpoints

Multiple validation options for different use cases

Code Validation

Validate handler code for security and syntax

POST /api/dev-mode/handlers/validate-code

Schema Parsing

Parse action schemas from code automatically

POST /api/dev-mode/handlers/parse-action-schemas

Sandbox Testing

Test execution in isolated environment

POST /api/dev-mode/handlers/test-execution

Testing Features

Built-in testing capabilities for handler development

Syntax ValidationAST parsing
Security AnalysisMulti-layer checks
Schema GenerationAuto-parsing
Execution TestingSandbox mode

Best Practices

Guidelines for creating secure, maintainable, and efficient handlers

Code Structure

  • • Inherit from BaseHandler and define SUPPORTED_ACTIONS
  • • Use descriptive method names that match your actions
  • • Write comprehensive docstrings with Args and Returns sections
  • • Handle errors gracefully with meaningful messages
  • • Use context.add_log() for debugging instead of print statements

Security & Performance

  • • Avoid dangerous imports and functions (os, sys, eval, etc.)
  • • Validate all inputs before processing
  • • Return structured data with clear schemas
  • • Test thoroughly with validation endpoints
  • • Monitor execution metrics and optimize accordingly

Example Handler Template

Class Definition - Inherit from BaseHandler, define SUPPORTED_ACTIONS

Action Methods - Implement async methods for each action

Docstring Format - Use Args: and Returns: sections for schema parsing

Error Handling - Use try/catch blocks and return meaningful errors

Logging - Use context.add_log() for execution tracking

Endpoints

POST/api/dev-mode/handlers

Create Handler

Create a new user handler. Auto-parses action schemas if omitted.

Request Body

{
  "name": "string (required)",
  "description": "string (required)",
  "handler_code": "string (required)",
  "requirements": "string[] (optional)",
  "supported_actions": "string[] (optional)",
  "execution_mode": "'SANDBOX' | 'TRUSTED' (optional, default SANDBOX)",
  "timeout_seconds": "number (optional, default 30)",
  "memory_limit_mb": "number (optional, default 128)",
  "category": "string (optional)",
  "tags": "string[] (optional)",
  "action_schemas": "Record<string, ActionSchema> (optional)"
}

Response

{
  "data": {
    "id": "string",
    "name": "string",
    "description": "string",
    "author_id": "string | null",
    "handler_code": "string",
    "supported_actions": [
      "get",
      "post"
    ],
    "action_schemas": {},
    "execution_mode": "SANDBOX",
    "timeout_seconds": 30,
    "memory_limit_mb": 128,
    "is_validated": false,
    "is_public": false,
    "is_system": false,
    "category": null,
    "tags": [],
    "usage_count": 0,
    "error_count": 0,
    "average_execution_time_ms": 0,
    "version": "1.0.0",
    "success_rate": 0,
    "security_level": "unknown",
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z",
    "last_used_at": null
  },
  "message": "Handler created successfully"
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers" \
+  -H "Content-Type: application/json" \
+  -H "Authorization: Bearer <your_access_token>" \
+  -d '{
  "name": "string (required)",
  "description": "string (required)",
  "handler_code": "string (required)",
  "requirements": "string[] (optional)",
  "supported_actions": "string[] (optional)",
  "execution_mode": "'SANDBOX' | 'TRUSTED' (optional, default SANDBOX)",
  "timeout_seconds": "number (optional, default 30)",
  "memory_limit_mb": "number (optional, default 128)",
  "category": "string (optional)",
  "tags": "string[] (optional)",
  "action_schemas": "Record<string, ActionSchema> (optional)"
}'
GET/api/dev-mode/handlers

List My Handlers

List handlers created by the authenticated user.

Query Parameters

skip(number)Offset (default 0)
limit(number)Page size (max 100)

Response

{
  "data": [],
  "total": 0,
  "page": 1,
  "limit": 50
}

cURL Example

curl -X GET "https://api.blocktion.io/api/dev-mode/handlers" \
+  -H "Authorization: Bearer <your_access_token>"
GET/api/dev-mode/handlers/available

List Available (System + Owned)

List system handlers and the current user's handlers.

Query Parameters

skip(number)Offset (default 0)
limit(number)Max 200
category(string)Optional category

Response

{
  "data": []
}

cURL Example

curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/available" \
+  -H "Authorization: Bearer <your_access_token>"
GET/api/dev-mode/handlers/public

List Public Handlers

List public handlers, optionally only validated ones.

Query Parameters

skip(number)Offset (default 0)
limit(number)Max 100
category(string)Optional category
validated_only(boolean)Default true

Response

{
  "data": []
}

cURL Example

curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/public"
GET/api/dev-mode/handlers/reliable

Reliable Handlers

Get handlers with high reliability scores.

Query Parameters

skip(number)Offset (default 0)
limit(number)Max 50

Response

{
  "data": []
}

cURL Example

curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/reliable"
GET/api/dev-mode/handlers/{handler_id}

Get Handler

Get a handler by ID.

Response

{
  "data": {
    "id": "string",
    "name": "string"
  }
}

cURL Example

curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/{handler_id}" \
+  -H "Authorization: Bearer <your_access_token>"
PUT/api/dev-mode/handlers/{handler_id}

Update Handler

Update handler metadata and/or code.

Request Body

{
  "name": "string (optional)",
  "description": "string (optional)",
  "handler_code": "string (optional)",
  "requirements": "string[] (optional)",
  "supported_actions": "string[] (optional)",
  "execution_mode": "'SANDBOX' | 'TRUSTED' (optional)",
  "timeout_seconds": "number (optional)",
  "memory_limit_mb": "number (optional)",
  "category": "string (optional)",
  "tags": "string[] (optional)",
  "action_schemas": "Record<string, ActionSchema> (optional)"
}

Response

{
  "data": {
    "id": "string",
    "name": "string"
  },
  "message": "Handler updated successfully"
}

cURL Example

curl -X PUT "https://api.blocktion.io/api/dev-mode/handlers/{handler_id}" \
+  -H "Content-Type: application/json" \
+  -H "Authorization: Bearer <your_access_token>" \
+  -d '{
  "name": "string (optional)",
  "description": "string (optional)",
  "handler_code": "string (optional)",
  "requirements": "string[] (optional)",
  "supported_actions": "string[] (optional)",
  "execution_mode": "'SANDBOX' | 'TRUSTED' (optional)",
  "timeout_seconds": "number (optional)",
  "memory_limit_mb": "number (optional)",
  "category": "string (optional)",
  "tags": "string[] (optional)",
  "action_schemas": "Record<string, ActionSchema> (optional)"
}'
DELETE/api/dev-mode/handlers/{handler_id}

Delete Handler

Delete a handler you own.

Response

{
  "data": null
}

cURL Example

curl -X DELETE "https://api.blocktion.io/api/dev-mode/handlers/{handler_id}" \
+  -H "Content-Type: application/json" \
+  -H "Authorization: Bearer <your_access_token>"
POST/api/dev-mode/handlers/{handler_id}/publish

Publish Handler

Publish a handler to make it public.

Response

{
  "data": {
    "id": "string",
    "is_public": true
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/{handler_id}/publish" \
+  -H "Content-Type: application/json" \
+  -H "Authorization: Bearer <your_access_token>"
POST/api/dev-mode/handlers/validate

Validate Handler (Data)

Validate handler payload without persisting.

Request Body

{
  "name": "string",
  "description": "string",
  "handler_code": "string"
}

Response

{
  "data": {
    "is_valid": true,
    "errors": [],
    "security_report": {}
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/validate" \
+  -H "Content-Type: application/json" \
+  -d '{
  "name": "string",
  "description": "string",
  "handler_code": "string"
}'
POST/api/dev-mode/handlers/validate-data

Validate Handler (Dictionary)

Validate handler data provided as an object.

Request Body

{
  "handler_data": {
    "name": "string",
    "description": "string",
    "handler_code": "string"
  }
}

Response

{
  "data": {
    "is_valid": true,
    "errors": [],
    "security_report": {}
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/validate-data" \
+  -H "Content-Type: application/json" \
+  -d '{
  "handler_data": {
    "name": "string",
    "description": "string",
    "handler_code": "string"
  }
}'
POST/api/dev-mode/handlers/validate-code

Validate Code

Validate handler code for security and correctness.

Request Body

{
  "handler_code": "string (required)"
}

Response

{
  "data": {
    "is_valid": true,
    "errors": [],
    "security_report": {}
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/validate-code" \
+  -H "Content-Type: application/json" \
+  -d '{
  "handler_code": "string (required)"
}'
POST/api/dev-mode/handlers/{handler_id}/execute

Execute Handler

Execute a saved handler securely in sandbox.

Request Body

{
  "parameters": "Record<string, any> (required)",
  "timeout_seconds": "number (optional)",
  "memory_limit_mb": "number (optional)"
}

Response

{
  "data": {
    "result": {}
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/{handler_id}/execute" \
+  -H "Content-Type: application/json" \
+  -H "Authorization: Bearer <your_access_token>" \
+  -d '{
  "parameters": "Record<string, any> (required)",
  "timeout_seconds": "number (optional)",
  "memory_limit_mb": "number (optional)"
}'
POST/api/dev-mode/handlers/test-execution

Test Execution (Unsaved Code)

Run arbitrary handler code with action and parameters without saving.

Request Body

{
  "handler_code": "string (required)",
  "action": "string (required)",
  "test_parameters": "Record<string, any> (optional)",
  "timeout_seconds": "number (optional)",
  "memory_limit_mb": "number (optional)"
}

Response

{
  "data": {
    "result": {}
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/test-execution" \
+  -H "Content-Type: application/json" \
+  -d '{
  "handler_code": "string (required)",
  "action": "string (required)",
  "test_parameters": "Record<string, any> (optional)",
  "timeout_seconds": "number (optional)",
  "memory_limit_mb": "number (optional)"
}'
POST/api/dev-mode/handlers/validate-sandbox

Validate in Sandbox

Validate by running provided code against test cases in sandbox.

Request Body

{
  "handler_code": "string (required)",
  "validation_parameters": "Array<Record<string, any>> (optional)"
}

Response

{
  "data": {
    "processed": true
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/validate-sandbox" \
+  -H "Content-Type: application/json" \
+  -d '{
  "handler_code": "string (required)",
  "validation_parameters": "Array<Record<string, any>> (optional)"
}'
POST/api/dev-mode/handlers/parse-action-schemas

Parse Action Schemas

Parse action parameter/output schemas from given code.

Request Body

{
  "code": "string (required)"
}

Response

{
  "data": {
    "action_schemas": {}
  }
}

cURL Example

curl -X POST "https://api.blocktion.io/api/dev-mode/handlers/parse-action-schemas" \
+  -H "Content-Type: application/json" \
+  -d '{
  "code": "string (required)"
}'