Skip to main content

A robust SDK and CLI for n8n workflow automation with DevOps capabilities

Project description

n8n-flow-manager ๐Ÿš€

n8n-flow-manager is a robust, production-ready Python SDK and CLI for the n8n automation platform. Unlike simple HTTP wrappers, this package is designed for DevOps workflows, providing type-safe models, async operations, workflow templating, and CI/CD integration capabilities.

PyPI version Python 3.9+ License: MIT Tests Coverage


โœจ Features

Core Capabilities

  • โšก Async-First Design: Built on httpx for high-performance async operations
  • ๐Ÿ›ก๏ธ Type Safety: Complete Pydantic models for workflows, executions, and credentials
  • ๐Ÿ”„ Smart Polling: Execute workflows and wait for completion with intelligent status checking
  • ๐Ÿ“ Jinja2 Templating: Inject environment-specific variables into workflow definitions
  • ๐Ÿค– Powerful CLI: Terminal commands for backup, deploy, sync, and manage workflows
  • ๐Ÿ” Secure: API key authentication with proper error handling and retries
  • ๐Ÿ“ฆ Zero Config: Works with environment variables or explicit configuration

What Makes It Different?

Feature n8n-flow-manager Generic HTTP Clients
Type Validation โœ… Pydantic models โŒ Raw dicts
Async Support โœ… Native asyncio โš ๏ธ Sync only
Smart Execution โœ… run_and_wait() โŒ Manual polling
Templating โœ… Jinja2 built-in โŒ Not included
CLI Tools โœ… Full featured โŒ None
Error Handling โœ… Custom exceptions โš ๏ธ Generic errors

๐Ÿ“‚ Project Structure

n8n-flow-manager/
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ n8n_manager/
โ”‚       โ”œโ”€โ”€ __init__.py           # Public API exports
โ”‚       โ”œโ”€โ”€ client.py             # Main async client
โ”‚       โ”œโ”€โ”€ exceptions.py         # Custom error types
โ”‚       โ”œโ”€โ”€ api/                  # API modules by resource
โ”‚       โ”‚   โ”œโ”€โ”€ workflows.py      # Workflow operations
โ”‚       โ”‚   โ”œโ”€โ”€ executions.py     # Execution management
โ”‚       โ”‚   โ””โ”€โ”€ credentials.py    # Credential handling
โ”‚       โ”œโ”€โ”€ models/               # Pydantic data models
โ”‚       โ”‚   โ”œโ”€โ”€ workflow.py       # Workflow structures
โ”‚       โ”‚   โ”œโ”€โ”€ execution.py      # Execution states
โ”‚       โ”‚   โ””โ”€โ”€ credential.py     # Credential types
โ”‚       โ”œโ”€โ”€ cli/                  # Command-line interface
โ”‚       โ”‚   โ””โ”€โ”€ main.py           # Typer CLI app
โ”‚       โ””โ”€โ”€ utils/                # Helper utilities
โ”‚           โ””โ”€โ”€ templating.py     # Jinja2 template engine
โ”œโ”€โ”€ tests/                        # Pytest test suite
โ”œโ”€โ”€ examples/                     # Usage examples
โ”œโ”€โ”€ pyproject.toml                # Poetry configuration
โ””โ”€โ”€ README.md                     # This file

๐Ÿš€ Installation

Requirements

  • Python 3.9 or higher
  • n8n instance (cloud or self-hosted)

Install from PyPI

# Install with pip
pip install n8n-flow-manager

# Install with poetry
poetry add n8n-flow-manager

# Install CLI globally with pipx
pipx install n8n-flow-manager

Install from Source

# Clone the repository
git clone https://github.com/Mgobeaalcoba/n8n-flow-manager.git
cd n8n-flow-manager

# Install with Poetry (recommended)
poetry install --with dev

Install CLI Globally (Use n8n-py anywhere)

# Create wrapper script
mkdir -p ~/.local/bin
cat > ~/.local/bin/n8n-py << 'EOF'
#!/bin/bash
cd /path/to/n8n-flow-manager
poetry run n8n-py "$@"
EOF
chmod +x ~/.local/bin/n8n-py

# Add to PATH (if not already)
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

# Now use directly anywhere:
n8n-py health
n8n-py list-workflows

Configuration

Create a .env file in your project root:

N8N_API_KEY=your_api_key_here
N8N_BASE_URL=https://n8n.example.com

Or export as environment variables:

export N8N_API_KEY="your_api_key_here"
export N8N_BASE_URL="https://n8n.example.com"

Getting Your API Key

  1. Open your n8n instance
  2. Go to Settings โ†’ API
  3. Generate a new API key
  4. Copy and save it securely

๐Ÿ› ๏ธ Usage Guide

1. Python SDK Usage

Basic Client Usage

import asyncio
from n8n_manager import N8NClient

async def main():
    # Initialize client (reads from environment)
    async with N8NClient() as client:

        # List all active workflows
        workflows = await client.workflows.list(active=True)
        for wf in workflows:
            print(f"Workflow: {wf.name} (ID: {wf.id})")

        # Get specific workflow
        workflow = await client.workflows.get("workflow_id")
        print(f"Nodes: {len(workflow.nodes)}")

        # Execute workflow and wait for result
        execution = await client.executions.run_and_wait(
            workflow_id="workflow_id",
            timeout=60
        )
        print(f"Status: {execution.status}")
        print(f"Success: {execution.is_successful}")

asyncio.run(main())

Creating Workflows Programmatically

from n8n_manager import N8NClient
from n8n_manager.models.workflow import Workflow, Node

async def create_simple_workflow():
    async with N8NClient() as client:
        workflow = Workflow(
            name="Python-Created Workflow",
            active=False,
            nodes=[
                Node(
                    name="Start",
                    type="n8n-nodes-base.start",
                    position=[250, 300],
                    parameters={}
                ),
                Node(
                    name="Set Data",
                    type="n8n-nodes-base.set",
                    position=[450, 300],
                    parameters={
                        "values": {
                            "string": [
                                {"name": "message", "value": "Hello from Python!"}
                            ]
                        }
                    }
                )
            ],
            connections={
                "Start": {
                    "main": [[{"node": "Set Data", "type": "main", "index": 0}]]
                }
            }
        )

        created = await client.workflows.create(workflow)
        print(f"Created workflow: {created.id}")

Using Templates

from n8n_manager.utils.templating import load_workflow_from_file

# Load workflow with template variables
workflow = load_workflow_from_file(
    "templates/data_sync.json",
    variables={
        "environment": "production",
        "api_endpoint": "https://api.example.com",
        "timeout": 30
    }
)

async with N8NClient() as client:
    deployed = await client.workflows.create(workflow)
    print(f"Deployed: {deployed.name}")

2. CLI Usage

The CLI provides powerful commands for workflow management.

Example Output:

$ n8n-py health
โœ“ Connection healthy!
  API URL: https://n8n.example.com/

$ n8n-py list-workflows
                              Workflows (33 found)
โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”“
โ”ƒ ID               โ”ƒ Name                           โ”ƒ Active โ”ƒ Nodes โ”ƒ
โ”กโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”ฉ
โ”‚ 1RDHBsmLkkTptybX โ”‚ Production Data Sync           โ”‚ โœ“      โ”‚ 6     โ”‚
โ”‚ 2V3iCBkiOAPVzrUr โ”‚ Customer Onboarding            โ”‚ โœ—      โ”‚ 7     โ”‚
โ”‚ 8qGqx5TW1QA7T8P9 โ”‚ Error Notifications            โ”‚ โœ“      โ”‚ 2     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Commands

# List all workflows
n8n-py list-workflows

# List only active workflows
n8n-py list-workflows --active

Get Workflow Details

# Display workflow info
n8n-py get-workflow <workflow_id>

# Save workflow to file
n8n-py get-workflow <workflow_id> --output workflow.json

Deploy Workflows

# Deploy from JSON file
n8n-py deploy workflow.json

# Deploy with template variables
n8n-py deploy template.json --var environment=prod --var timeout=30

# Deploy and activate immediately
n8n-py deploy workflow.json --activate

Backup Workflows

# Backup all workflows
n8n-py backup --output ./backups

# Backup only active workflows
n8n-py backup --output ./backups --active-only

Execute Workflows

# Execute and wait for completion
n8n-py execute <workflow_id>

# Execute without waiting
n8n-py execute <workflow_id> --no-wait

# Execute with input data
n8n-py execute <workflow_id> --input data.json

Activate/Deactivate

# Activate workflow
n8n-py activate <workflow_id>

# Deactivate workflow
n8n-py deactivate <workflow_id>

Health Check

# Verify connection to n8n
n8n-py health

๐Ÿ“š Advanced Examples

CI/CD Integration

Use in GitHub Actions for automated deployments:

# .github/workflows/deploy-n8n.yml
name: Deploy n8n Workflows

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install n8n-flow-manager
        run: pip install -e .

      - name: Deploy workflows
        env:
          N8N_API_KEY: ${{ secrets.N8N_API_KEY }}
          N8N_BASE_URL: ${{ secrets.N8N_BASE_URL }}
        run: |
          n8n-py deploy workflows/production.json --activate

Environment-Specific Deployments

import asyncio
from n8n_manager import N8NClient
from n8n_manager.utils.templating import load_workflow_from_file

ENVIRONMENTS = {
    "dev": {
        "api_endpoint": "https://dev.api.example.com",
        "webhook_path": "webhook-dev",
        "timeout": 10
    },
    "prod": {
        "api_endpoint": "https://api.example.com",
        "webhook_path": "webhook",
        "timeout": 30
    }
}

async def deploy_to_environment(env: str):
    workflow = load_workflow_from_file(
        "templates/api_workflow.json",
        variables=ENVIRONMENTS[env]
    )

    async with N8NClient() as client:
        deployed = await client.workflows.create(workflow)
        await client.workflows.activate(deployed.id)
        print(f"Deployed to {env}: {deployed.id}")

# Deploy to production
asyncio.run(deploy_to_environment("prod"))

Monitoring and Logging

async def monitor_executions(workflow_id: str):
    async with N8NClient() as client:
        executions = await client.executions.list(
            workflow_id=workflow_id,
            limit=50
        )

        for execution in executions:
            if execution.is_failed:
                print(f"โŒ Failed: {execution.id} at {execution.started_at}")
            elif execution.is_successful:
                print(f"โœ… Success: {execution.id}")

๐Ÿงช Testing

Run the test suite with pytest:

# Install dev dependencies
poetry install --with dev

# Run all tests
poetry run pytest

# Run with coverage
poetry run pytest --cov=src/n8n_manager --cov-report=html

# Run specific test file
poetry run pytest tests/test_client.py

๐Ÿ”ง Development

Setting Up Development Environment

# Clone repository
git clone https://github.com/yourusername/n8n-flow-manager.git
cd n8n-flow-manager

# Install with dev dependencies
poetry install --with dev

# Install pre-commit hooks
poetry run pre-commit install

# Run linting
poetry run black src/ tests/
poetry run ruff src/ tests/

# Type checking
poetry run mypy src/

Project Roadmap

  • Core client with async support
  • Pydantic models for type safety
  • Workflow, execution, and credential APIs
  • CLI with Typer
  • Jinja2 templating
  • Smart execution polling
  • Webhook management API
  • Tag management
  • Bulk operations
  • Workflow validation before deploy
  • Integration tests with mock n8n server

๐Ÿ“– API Reference

N8NClient

Main client for interacting with n8n API.

Methods:

  • workflows - WorkflowAPI instance
  • executions - ExecutionAPI instance
  • credentials - CredentialAPI instance
  • health_check() - Verify API connection

WorkflowAPI

Methods:

  • list(active=None, tags=None) - List workflows
  • get(workflow_id) - Get workflow by ID
  • create(workflow) - Create new workflow
  • update(workflow_id, workflow) - Update workflow
  • delete(workflow_id) - Delete workflow
  • activate(workflow_id) - Activate workflow
  • deactivate(workflow_id) - Deactivate workflow

ExecutionAPI

Methods:

  • list(workflow_id=None, limit=100, status=None) - List executions
  • get(execution_id) - Get execution details
  • trigger_workflow(workflow_id, input_data=None) - Trigger execution
  • wait_for_execution(execution_id, timeout=300) - Wait for completion
  • run_and_wait(workflow_id, input_data=None, timeout=300) - Trigger and wait
  • retry(execution_id) - Retry failed execution
  • delete(execution_id) - Delete execution

CredentialAPI

Methods:

  • list(credential_type=None) - List credentials
  • get(credential_id) - Get credential by ID
  • create(credential) - Create credential
  • update(credential_id, credential) - Update credential
  • delete(credential_id) - Delete credential

๐Ÿค Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Contribution Guidelines

  • Write tests for new features
  • Follow existing code style (Black + Ruff)
  • Update documentation as needed
  • Add type hints to all functions
  • Keep commits atomic and well-described

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Acknowledgments

  • n8n - The workflow automation platform
  • httpx - Async HTTP client
  • Pydantic - Data validation
  • Typer - CLI framework
  • Rich - Terminal formatting

๐Ÿ“ž Support


๐ŸŽฏ Use Cases

DevOps & CI/CD

  • Automate workflow deployments across environments
  • Version control your n8n workflows in Git
  • Integrate with GitLab/GitHub Actions pipelines

Disaster Recovery

  • Scheduled backups of all workflows
  • Quick restore capabilities
  • Environment replication

Multi-Tenant Management

  • Programmatically create workflows for new clients
  • Template-based workflow generation
  • Bulk operations across workflows

Monitoring & Observability

  • Track execution success rates
  • Monitor workflow health
  • Automated alerting on failures

Made with โค๏ธ for the n8n community

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

n8n_flow_manager-0.1.1.tar.gz (24.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

n8n_flow_manager-0.1.1-py3-none-any.whl (24.6 kB view details)

Uploaded Python 3

File details

Details for the file n8n_flow_manager-0.1.1.tar.gz.

File metadata

  • Download URL: n8n_flow_manager-0.1.1.tar.gz
  • Upload date:
  • Size: 24.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.12 Darwin/25.2.0

File hashes

Hashes for n8n_flow_manager-0.1.1.tar.gz
Algorithm Hash digest
SHA256 ae1e73bcfd49e2ae78e6a717f7779709ef407ea4e6ec2710510c83fb587355c4
MD5 4f3759ee69af600aaa1e87037a748bfa
BLAKE2b-256 10ca317e586b8360a96cb4a995d759ac505332628bf8c0a2f8f8c727d1a38f4f

See more details on using hashes here.

File details

Details for the file n8n_flow_manager-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: n8n_flow_manager-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 24.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.12 Darwin/25.2.0

File hashes

Hashes for n8n_flow_manager-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 43cdc24ec2a22f8fd139e2edf9118a9707962d958cee83a706d737f2d4019e39
MD5 e4805feeeba39c5e82b0975863e84ec9
BLAKE2b-256 f817b739b4ae70abb45cc1218bf143c6d9ec6201fb00e30cb79aed37def42a84

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page