Skip to main content
This guide explains how to create custom hooks in SnackBase to extend functionality and automate workflows.
This guide covers code-level hooks written in Python. If you want to create hooks via the REST API without writing code, see API-Defined Hooks and the Hooks SDK Service.

Overview

Hooks allow you to execute custom code in response to events within SnackBase. They’re the primary extension mechanism for adding custom business logic.

What Can Hooks Do?

Hook System Stability

The hook registration mechanism is a STABLE API contract (v1.0). This means:
  • Hook registration syntax won’t change in breaking ways
  • Existing hooks will continue to work in future versions
  • New hook types will be additive, not breaking changes
The hook system API is stable and guaranteed to maintain backward compatibility.

Hook System Review

Hook Registration Pattern

Hooks are registered using the app.hook decorator:

Built-in Hooks

SnackBase includes built-in hooks that cannot be disabled:

Hook Categories

Hooks are organized into 8 categories:

1. App Lifecycle Hooks

2. Model Operation Hooks

3. Record Operation Hooks

4. Collection Operation Hooks

5. Auth Operation Hooks

6. User Operation Hooks

7. Request Processing Hooks

8. Custom Event Hooks

Step-by-Step Guide

Let’s create a custom hook that sends a Slack notification when a post is published.

Step 1: Create Hook File

Create hooks in a dedicated file:

Step 2: Import Hooks

Import your hooks file in app.py to register them:

Step 3: Configure Environment

Add required configuration to .env:

Step 4: Test the Hook

Hook Context

Hook Parameters

Hooks receive different parameters based on their type:

Context Object

The context object provides request information:

Advanced Features

Priority Control

Hooks execute in priority order (higher priority = earlier execution):

Conditional Execution

Only execute hooks based on conditions:

Error Handling

Handle errors gracefully in hooks:

Aborting Operations

Some before_* hooks can abort operations:

Async Database Operations

Hooks can perform database operations:

Best Practices

1. Keep Hooks Focused

Each hook should do one thing well:

2. Use Priority Wisely

Set appropriate priorities for execution order:

3. Handle Idempotency

Make hooks idempotent when possible:

4. Log Hook Execution

Add logging for debugging:

5. Avoid Blocking Operations

Keep hooks fast and non-blocking:

6. Test Hooks

Write tests for your hooks:

Examples

Example 1: Auto-Generate Slugs

Example 2: Enforce Validation

Example 3: Sync to External System

Example 4: Track Field Changes

Summary