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
List[str]List of actions this handler supports
async def action_name()Each action is implemented as an async method
Args: / Returns:Structured docstrings for automatic schema parsing
Execution Modes
Different execution environments for handlers
Sandbox Mode
Default mode with Docker isolation and security restrictions
Trusted Mode
For validated system handlers with fewer restrictions
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
passDocstring 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
Complex Types
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
Dangerous Functions
Sandbox Execution
Docker-based isolation with resource limits and restrictions
128MB default30s defaultConfigurableRestrictedSecurity 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-codeSchema Parsing
Parse action schemas from code automatically
POST /api/dev-mode/handlers/parse-action-schemasSandbox Testing
Test execution in isolated environment
POST /api/dev-mode/handlers/test-executionTesting Features
Built-in testing capabilities for handler development
AST parsingMulti-layer checksAuto-parsingSandbox modeBest 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
/api/dev-mode/handlersCreate 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)"
}'/api/dev-mode/handlersList 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>"
/api/dev-mode/handlers/availableList Available (System + Owned)
List system handlers and the current user's handlers.
Query Parameters
skip(number)Offset (default 0)limit(number)Max 200category(string)Optional categoryResponse
{
"data": []
}cURL Example
curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/available" \ + -H "Authorization: Bearer <your_access_token>"
/api/dev-mode/handlers/publicList Public Handlers
List public handlers, optionally only validated ones.
Query Parameters
skip(number)Offset (default 0)limit(number)Max 100category(string)Optional categoryvalidated_only(boolean)Default trueResponse
{
"data": []
}cURL Example
curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/public"
/api/dev-mode/handlers/reliableReliable Handlers
Get handlers with high reliability scores.
Query Parameters
skip(number)Offset (default 0)limit(number)Max 50Response
{
"data": []
}cURL Example
curl -X GET "https://api.blocktion.io/api/dev-mode/handlers/reliable"
/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>"/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)"
}'/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>"/api/dev-mode/handlers/{handler_id}/publishPublish 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>"/api/dev-mode/handlers/validateValidate 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"
}'/api/dev-mode/handlers/validate-dataValidate 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"
}
}'/api/dev-mode/handlers/validate-codeValidate 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)"
}'/api/dev-mode/handlers/{handler_id}/executeExecute 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)"
}'/api/dev-mode/handlers/test-executionTest 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)"
}'/api/dev-mode/handlers/validate-sandboxValidate 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)"
}'/api/dev-mode/handlers/parse-action-schemasParse 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)"
}'