{"id":29480877,"url":"https://github.com/cgast/n8n-backend","last_synced_at":"2026-05-10T07:51:20.424Z","repository":{"id":304152551,"uuid":"1016593052","full_name":"cgast/n8n-backend","owner":"cgast","description":"A comprehensive FastAPI backend service designed to provide webhooks, complex function packages, and seamless n8n workflow integration. This service acts as a bridge between n8n and your business logic implementations, offering a clean, scalable architecture with async PostgreSQL support and Redis caching.","archived":false,"fork":false,"pushed_at":"2025-07-09T08:36:17.000Z","size":50,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-11T13:18:56.223Z","etag":null,"topics":["backend-api","custom-nodes","fastapi","n8n","postgres","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cgast.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-09T08:36:14.000Z","updated_at":"2025-07-09T08:46:59.000Z","dependencies_parsed_at":"2025-07-11T13:19:41.925Z","dependency_job_id":"15c51a19-f363-4d8d-9960-6bfd6d403f67","html_url":"https://github.com/cgast/n8n-backend","commit_stats":null,"previous_names":["cgast/n8n-backend"],"tags_count":null,"template":true,"template_full_name":null,"purl":"pkg:github/cgast/n8n-backend","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgast%2Fn8n-backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgast%2Fn8n-backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgast%2Fn8n-backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgast%2Fn8n-backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cgast","download_url":"https://codeload.github.com/cgast/n8n-backend/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgast%2Fn8n-backend/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265366221,"owners_count":23753474,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend-api","custom-nodes","fastapi","n8n","postgres","python"],"created_at":"2025-07-14T23:11:46.034Z","updated_at":"2025-10-12T17:40:42.244Z","avatar_url":"https://github.com/cgast.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# n8n-backend: FastAPI Backend with n8n Integration\n\nA comprehensive FastAPI backend service designed to provide webhooks, complex function packages, and seamless n8n workflow integration. This service acts as a bridge between n8n and your business logic implementations, offering a clean, scalable architecture with async PostgreSQL support and Redis caching.\n\n## 🚀 Quick Start\n\n### Prerequisites\n- Docker and Docker Compose\n- Python 3.11+ (for local development)\n- Node.js 18.10+ and pnpm 8.1+ (for n8n nodes)\n\n### 30-Second Setup\n\n```bash\n# Clone and start the development environment\ngit clone \u003crepository-url\u003e\ncd n8n-backend\ndocker-compose up --build\n\n# Run database migrations\ndocker-compose exec app alembic upgrade head\n```\n\n**Services will be available at:**\n- 🌐 FastAPI Application: http://localhost:8000\n- 📚 API Documentation: http://localhost:8000/docs\n- 🗄️ pgAdmin: http://localhost:5051 (dev@n8n-backend.local / dev123)\n- 🔴 Redis: localhost:6380\n- 🐘 PostgreSQL: localhost:5433\n\n### Test Your Setup\n\n```bash\n# Health check\ncurl http://localhost:8000/health\n\n# Create your first webhook\ncurl -X POST http://localhost:8000/api/v1/webhooks/ \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"my-first-webhook\",\n    \"description\": \"Test webhook for business logic\",\n    \"endpoint\": \"test-endpoint\",\n    \"method\": \"POST\"\n  }'\n\n# Execute the webhook\ncurl -X POST http://localhost:8000/api/v1/webhooks/execute/test-endpoint \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"message\": \"Hello from my business logic!\"}'\n```\n\n## 📋 Table of Contents\n\n- [Features](#-features)\n- [Architecture Overview](#-architecture-overview)\n- [Project Structure](#-project-structure)\n- [Quick Start](#-quick-start)\n- [Business Logic Integration](#-business-logic-integration)\n- [n8n Integration](#-n8n-integration)\n- [API Reference](#-api-reference)\n- [How-To Guides](#-how-to-guides)\n- [Development](#-development)\n- [Deployment](#-deployment)\n- [Troubleshooting](#-troubleshooting)\n\n## ✨ Features\n\n### Core Backend Features\n- **FastAPI Framework**: Modern, fast web framework with automatic API documentation\n- **Async PostgreSQL**: High-performance database operations with SQLAlchemy 2.0\n- **pgvector Support**: Ready for AI/ML integrations with vector database capabilities\n- **Redis Integration**: Caching and background task support\n- **Docker Compose**: Complete development and production environment\n- **Clean Architecture**: Repository pattern, service layer, and dependency injection\n- **Comprehensive Testing**: Async test suite with pytest\n- **Database Migrations**: Alembic for schema management\n\n### Business Logic Integration\n- **Webhook Management**: Dynamic webhook creation and execution for your business logic\n- **Function Domains**: Organized business logic packages with versioning\n- **Flexible API Design**: Easy integration of custom business operations\n- **Authentication Ready**: Multiple auth methods (API Key, Bearer Token, etc.)\n- **Data Processing**: Built-in data transformation, validation, and export capabilities\n\n### n8n Integration Features\n- **Custom n8n Nodes**: Pre-built nodes for seamless workflow integration\n- **HTTP Request Architecture**: Clean separation between n8n and business logic\n- **Auto-Registration**: Webhooks automatically register with your backend\n- **Debug Support**: Comprehensive logging and debugging capabilities\n- **Scalable Design**: Backend and n8n scale independently\n\n## 🏗️ Architecture Overview\n\nThe integration follows the **HTTP Request Nodes** approach, providing clean separation of concerns:\n\n```mermaid\ngraph LR\n    A[n8n Workflow] --\u003e B[Custom n8n Node]\n    B --\u003e C[HTTP Request]\n    C --\u003e D[FastAPI Backend]\n    D --\u003e E[Your Business Logic]\n    D --\u003e F[Database/Redis]\n    E --\u003e G[Response]\n    G --\u003e B\n    B --\u003e H[n8n Output]\n```\n\n### Benefits\n- ✅ **Separation of Concerns**: Business logic stays in FastAPI\n- ✅ **Maintainability**: Updates don't require rebuilding n8n nodes\n- ✅ **Scalability**: FastAPI backend scales independently\n- ✅ **Reusability**: Endpoints serve multiple clients\n- ✅ **Flexibility**: Easy to add new operations and authentication\n\n## 📁 Project Structure\n\n```\n├── app/                                 # FastAPI Application\n│   ├── api/\n│   │   ├── dependencies/                # FastAPI dependency injection\n│   │   └── routes/                      # API endpoint definitions\n│   │       ├── webhooks.py              # Webhook management\n│   │       ├── function_domains.py      # Business logic packages\n│   │       ├── n8n_operations.py        # n8n-specific endpoints\n│   │       └── health.py                # Health checks\n│   ├── core/                            # Configuration and database setup\n│   ├── db/\n│   │   ├── models/                      # SQLAlchemy models\n│   │   └── repositories/                # Data access layer\n│   ├── models/\n│   │   ├── domain/                      # Business entity schemas\n│   │   └── utility_schemas/             # Common validation schemas\n│   └── services/                        # Business logic layer\n├── n8n-nodes/                           # n8n Node Package\n│   ├── credentials/\n│   │   └── YourCompanyApi.credentials.ts\n│   ├── nodes/\n│   │   └── YourCompany/\n│   │       ├── Webhook/                 # Webhook management nodes\n│   │       ├── FunctionDomain/          # Function domain operations\n│   │       └── BusinessLogic/           # Your business logic nodes\n│   └── package.json\n├── migrations/                          # Database migration files\n├── tests/                               # Test suite\n├── scripts/                             # Utility scripts\n├── docker-compose.yml                   # Production configuration\n├── docker-compose.override.yml          # Development overrides\n└── pyproject.toml                       # Python dependencies\n```\n\n## 🔧 Business Logic Integration\n\n### Step 1: Define Your Business Logic\n\nCreate your business logic as FastAPI endpoints. The system provides several patterns:\n\n#### Pattern 1: Direct Webhook Integration\nPerfect for simple business operations:\n\n```python\n# app/api/routes/my_business_logic.py\nfrom fastapi import APIRouter, Depends\nfrom app.services.my_service import MyBusinessService\n\nrouter = APIRouter()\n\n@router.post(\"/process-order\")\nasync def process_order(\n    order_data: dict,\n    service: MyBusinessService = Depends()\n):\n    \"\"\"Your business logic for processing orders\"\"\"\n    result = await service.process_order(order_data)\n    return {\"success\": True, \"order_id\": result.id}\n```\n\n#### Pattern 2: Function Domain Integration\nFor complex, organized business logic packages:\n\n```python\n# app/api/routes/function_domains.py\n@router.post(\"/\")\nasync def create_function_domain(\n    domain: FunctionDomainCreate,\n    service: FunctionDomainService = Depends(get_function_domain_service)\n):\n    \"\"\"Create a new business logic package\"\"\"\n    return await service.create_function_domain(domain)\n```\n\n#### Pattern 3: n8n Operations Integration\nFor operations specifically designed for n8n workflows:\n\n```python\n# app/api/routes/n8n_operations.py\n@router.post(\"/user-management\")\nasync def user_management_operation(request: NodeRequest):\n    \"\"\"Handle user management operations from n8n\"\"\"\n    operation = request.operation\n    data = request.data\n    \n    if operation == \"create_user\":\n        # Your user creation logic\n        result = await create_user_logic(data)\n    elif operation == \"get_user\":\n        # Your user retrieval logic\n        result = await get_user_logic(data)\n    \n    return NodeResponse(success=True, data=result)\n```\n\n### Step 2: Register Your Endpoints\n\nAdd your business logic routes to the main application:\n\n```python\n# app/main.py\nfrom app.api.routes import my_business_logic\n\napplication.include_router(\n    my_business_logic.router,\n    prefix=f\"{settings.API_V1_STR}/my-business\",\n    tags=[\"my-business\"]\n)\n```\n\n### Step 3: Create Database Models (if needed)\n\n```python\n# app/db/models/my_model.py\nfrom app.db.models.base import Base\nfrom sqlalchemy import Column, Integer, String, DateTime\n\nclass MyBusinessEntity(Base):\n    __tablename__ = \"my_business_entities\"\n    \n    id = Column(Integer, primary_key=True)\n    name = Column(String, nullable=False)\n    created_at = Column(DateTime, default=datetime.utcnow)\n```\n\n### Step 4: Implement Services\n\n```python\n# app/services/my_service.py\nfrom app.db.repositories.my_repository import MyRepository\n\nclass MyBusinessService:\n    def __init__(self, repository: MyRepository):\n        self.repository = repository\n    \n    async def process_order(self, order_data: dict):\n        # Your business logic here\n        return await self.repository.create(order_data)\n```\n\n### Step 5: Test Your Integration\n\n```bash\n# Test your business logic endpoint\ncurl -X POST http://localhost:8000/api/v1/my-business/process-order \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"customer_id\": 123, \"items\": [{\"id\": 1, \"quantity\": 2}]}'\n```\n\n## 🔗 n8n Integration\n\n### Installation\n\n#### 1. Install n8n Nodes\n\n```bash\n# From the n8n-nodes directory\ncd n8n-nodes\npnpm install\npnpm build\n\n# Install in your n8n instance\nnpm install /path/to/n8n-nodes\n```\n\n#### 2. Configure n8n Credentials\n\n1. Go to n8n **Settings** → **Credentials**\n2. Add \"Your Company API\" credential\n3. Configure:\n   - **Server URL**: `http://localhost:8000` (or your backend URL)\n   - **Authentication Method**: Choose your preferred method\n   - **API Key/Bearer Token**: If using authentication\n\n#### 3. Test Connection\n\nUse the credential test feature to verify connectivity to your FastAPI backend.\n\n### Available n8n Nodes\n\n#### Webhook Manager Node\nManage webhooks in your FastAPI backend:\n\n```json\n{\n  \"operation\": \"create\",\n  \"name\": \"Order Processing Webhook\",\n  \"endpoint\": \"order-webhook\",\n  \"method\": \"POST\",\n  \"description\": \"Handles new order notifications\"\n}\n```\n\n#### Webhook Trigger Node\nStart workflows when webhooks are received:\n\n```json\n{\n  \"webhookEndpoint\": \"order-notifications\",\n  \"autoRegister\": true,\n  \"webhookName\": \"Order Processing Trigger\",\n  \"responseMode\": \"onReceived\"\n}\n```\n\n#### Function Domain Node\nManage business logic packages:\n\n```json\n{\n  \"operation\": \"create\",\n  \"name\": \"E-commerce Operations\",\n  \"description\": \"Handles all e-commerce related functions\",\n  \"config\": {\n    \"version\": \"1.0.0\",\n    \"environment\": \"production\"\n  }\n}\n```\n\n#### User Management Node\nHandle user operations:\n\n```json\n{\n  \"operation\": \"create_user\",\n  \"email\": \"john.doe@example.com\",\n  \"firstName\": \"John\",\n  \"lastName\": \"Doe\",\n  \"password\": \"secure_password\"\n}\n```\n\n#### Data Processing Node\nProcess data using your backend:\n\n```json\n{\n  \"operation\": \"transform_data\",\n  \"transformationRules\": {\n    \"name\": {\"type\": \"uppercase\"},\n    \"price\": {\"type\": \"multiply\", \"factor\": 1.1}\n  }\n}\n```\n\n### Workflow Examples\n\n#### Example 1: Order Processing Workflow\n\n```\nWebhook Trigger (order-received)\n    ↓ [Order data]\nUser Management (get customer details)\n    ↓ [Customer + Order data]\nData Processing (validate order data)\n    ↓ [Validated order]\nWebhook Manager (execute fulfillment webhook)\n    ↓ [Fulfillment response]\n```\n\n#### Example 2: Data Pipeline Workflow\n\n```\nHTTP Request (fetch data from external API)\n    ↓ [Raw data]\nData Processing (transform data)\n    ↓ [Transformed data]\nData Processing (validate data)\n    ↓ [Validated data]\nData Processing (export to CSV)\n    ↓ [Export URL]\n```\n\n## 📖 API Reference\n\n### Core Endpoints\n\n#### Health Check\n```bash\nGET /health\n```\n\n#### Webhook Management\n```bash\n# List webhooks\nGET /api/v1/webhooks/\n\n# Create webhook\nPOST /api/v1/webhooks/\n{\n  \"name\": \"webhook-name\",\n  \"description\": \"Description\",\n  \"endpoint\": \"endpoint-name\",\n  \"method\": \"POST\"\n}\n\n# Get webhook\nGET /api/v1/webhooks/{id}\n\n# Update webhook\nPUT /api/v1/webhooks/{id}\n\n# Delete webhook\nDELETE /api/v1/webhooks/{id}\n\n# Execute webhook\nPOST /api/v1/webhooks/execute/{endpoint}\n\n# Test webhook (with debug info)\nPOST /api/v1/webhooks/test/{endpoint}\n```\n\n#### Function Domain Management\n```bash\n# List function domains\nGET /api/v1/function-domains/\n\n# Create function domain\nPOST /api/v1/function-domains/\n{\n  \"name\": \"domain-name\",\n  \"description\": \"Description\",\n  \"config\": {}\n}\n\n# Get function domain\nGET /api/v1/function-domains/{id}\n\n# Update function domain\nPUT /api/v1/function-domains/{id}\n\n# Delete function domain\nDELETE /api/v1/function-domains/{id}\n```\n\n#### n8n Integration Endpoints\n```bash\n# User management operations\nPOST /api/v1/n8n/user-management\n{\n  \"operation\": \"create_user|get_user|update_user|delete_user\",\n  \"data\": {...}\n}\n\n# Data processing operations\nPOST /api/v1/n8n/data-processing\n{\n  \"operation\": \"transform_data|validate_data|aggregate_data|filter_data|enrich_data|export_data\",\n  \"data\": {...}\n}\n```\n\n### Request/Response Examples\n\n#### User Management Request\n```json\nPOST /api/v1/n8n/user-management\n{\n  \"operation\": \"create_user\",\n  \"data\": {\n    \"email\": \"john.doe@example.com\",\n    \"password\": \"secure_password\",\n    \"first_name\": \"John\",\n    \"last_name\": \"Doe\"\n  }\n}\n```\n\n#### Data Processing Request\n```json\nPOST /api/v1/n8n/data-processing\n{\n  \"operation\": \"transform_data\",\n  \"data\": {\n    \"transformation_rules\": {\n      \"name\": {\"type\": \"uppercase\"},\n      \"price\": {\"type\": \"multiply\", \"factor\": 1.1}\n    }\n  },\n  \"input_data\": {\n    \"name\": \"product name\",\n    \"price\": 100\n  }\n}\n```\n\n#### Standard Response Format\n```json\n{\n  \"success\": true,\n  \"data\": {\n    \"original_data\": {\"name\": \"product name\", \"price\": 100},\n    \"transformed_data\": {\"name\": \"PRODUCT NAME\", \"price\": 110},\n    \"processed_at\": \"2025-01-07T09:00:00Z\"\n  }\n}\n```\n\n## 📚 How-To Guides\n\n### How to Add New Business Logic\n\n#### 1. Create the Business Logic Endpoint\n\n```python\n# app/api/routes/my_new_feature.py\nfrom fastapi import APIRouter, Depends\nfrom app.services.my_new_service import MyNewService\n\nrouter = APIRouter()\n\n@router.post(\"/process\")\nasync def process_my_data(\n    data: dict,\n    service: MyNewService = Depends()\n):\n    result = await service.process(data)\n    return {\"success\": True, \"result\": result}\n```\n\n#### 2. Create the Service Layer\n\n```python\n# app/services/my_new_service.py\nclass MyNewService:\n    async def process(self, data: dict):\n        # Your business logic here\n        processed_data = self.transform_data(data)\n        return processed_data\n    \n    def transform_data(self, data: dict):\n        # Implementation\n        return data\n```\n\n#### 3. Register the Router\n\n```python\n# app/main.py\nfrom app.api.routes import my_new_feature\n\napplication.include_router(\n    my_new_feature.router,\n    prefix=f\"{settings.API_V1_STR}/my-new-feature\",\n    tags=[\"my-new-feature\"]\n)\n```\n\n#### 4. Create Database Models (if needed)\n\n```python\n# app/db/models/my_new_model.py\nfrom app.db.models.base import Base\nfrom sqlalchemy import Column, Integer, String\n\nclass MyNewEntity(Base):\n    __tablename__ = \"my_new_entities\"\n    \n    id = Column(Integer, primary_key=True)\n    name = Column(String, nullable=False)\n```\n\n#### 5. Run Migration\n\n```bash\n# Create migration\ndocker-compose exec app alembic revision --autogenerate -m \"Add my new entity\"\n\n# Apply migration\ndocker-compose exec app alembic upgrade head\n```\n\n### How to Create Custom n8n Nodes\n\n#### 1. Create Node File\n\n```typescript\n// n8n-nodes/nodes/YourCompany/MyNewFeature/MyNewFeature.node.ts\nimport { INodeType, INodeTypeDescription } from 'n8n-workflow';\n\nexport class MyNewFeature implements INodeType {\n    description: INodeTypeDescription = {\n        displayName: 'My New Feature',\n        name: 'myNewFeature',\n        group: ['transform'],\n        version: 1,\n        description: 'Process data with my new feature',\n        defaults: {\n            name: 'My New Feature',\n        },\n        inputs: ['main'],\n        outputs: ['main'],\n        credentials: [\n            {\n                name: 'yourCompanyApi',\n                required: true,\n            },\n        ],\n        properties: [\n            {\n                displayName: 'Operation',\n                name: 'operation',\n                type: 'options',\n                options: [\n                    {\n                        name: 'Process Data',\n                        value: 'process',\n                    },\n                ],\n                default: 'process',\n            },\n        ],\n    };\n\n    async execute(this: IExecuteFunctions): Promise\u003cINodeExecutionData[][]\u003e {\n        // Implementation\n    }\n}\n```\n\n#### 2. Build and Install\n\n```bash\ncd n8n-nodes\npnpm build\nnpm install /path/to/n8n-nodes\n```\n\n### How to Set Up Authentication\n\n#### 1. Configure FastAPI Authentication\n\n```python\n# app/core/auth.py\nfrom fastapi import HTTPException, Security\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\nsecurity = HTTPBearer()\n\nasync def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):\n    if credentials.credentials != \"your-secret-token\":\n        raise HTTPException(status_code=401, detail=\"Invalid token\")\n    return credentials.credentials\n```\n\n#### 2. Protect Your Endpoints\n\n```python\n# app/api/routes/protected_route.py\nfrom app.core.auth import verify_token\n\n@router.post(\"/protected-endpoint\")\nasync def protected_endpoint(\n    data: dict,\n    token: str = Depends(verify_token)\n):\n    # Your protected business logic\n    return {\"message\": \"Access granted\"}\n```\n\n#### 3. Configure n8n Credentials\n\nUpdate your n8n credentials to include the authentication token.\n\n### How to Add Data Validation\n\n#### 1. Create Pydantic Models\n\n```python\n# app/models/domain/my_data.py\nfrom pydantic import BaseModel, validator\n\nclass MyDataInput(BaseModel):\n    name: str\n    email: str\n    age: int\n    \n    @validator('email')\n    def validate_email(cls, v):\n        if '@' not in v:\n            raise ValueError('Invalid email format')\n        return v\n    \n    @validator('age')\n    def validate_age(cls, v):\n        if v \u003c 0 or v \u003e 150:\n            raise ValueError('Age must be between 0 and 150')\n        return v\n```\n\n#### 2. Use in Endpoints\n\n```python\n@router.post(\"/validate-data\")\nasync def validate_data(data: MyDataInput):\n    # Data is automatically validated\n    return {\"message\": \"Data is valid\", \"data\": data}\n```\n\n### How to Add Caching\n\n#### 1. Configure Redis Caching\n\n```python\n# app/services/cached_service.py\nimport redis\nimport json\nfrom app.core.config import settings\n\nredis_client = redis.from_url(settings.REDIS_URL)\n\nclass CachedService:\n    async def get_cached_data(self, key: str):\n        cached = redis_client.get(key)\n        if cached:\n            return json.loads(cached)\n        \n        # Fetch data from database or external API\n        data = await self.fetch_data()\n        \n        # Cache for 1 hour\n        redis_client.setex(key, 3600, json.dumps(data))\n        return data\n```\n\n### How to Add Background Tasks\n\n#### 1. Create Background Task\n\n```python\n# app/services/background_service.py\nfrom fastapi import BackgroundTasks\n\ndef process_in_background(data: dict):\n    # Long-running task\n    time.sleep(10)\n    print(f\"Processed: {data}\")\n\n@router.post(\"/async-process\")\nasync def async_process(\n    data: dict,\n    background_tasks: BackgroundTasks\n):\n    background_tasks.add_task(process_in_background, data)\n    return {\"message\": \"Task started in background\"}\n```\n\n## 🛠️ Development\n\n### Local Development Setup\n\n#### Without Docker\n\n```bash\n# Install dependencies\npip install -e .[dev]\n\n# Set up environment\ncp .env.example .env\n# Edit .env with your configuration\n\n# Run the application\nuvicorn app.main:app --reload\n```\n\n#### With Docker (Recommended)\n\n```bash\n# Start development environment\ndocker-compose up --build\n\n# Run commands in container\ndocker-compose exec app pytest\ndocker-compose exec app alembic upgrade head\n```\n\n### Development Workflow\n\n#### 1. Code Quality\n\n```bash\n# Format code\ndocker-compose exec app black .\ndocker-compose exec app isort .\n\n# Lint code\ndocker-compose exec app flake8\ndocker-compose exec app mypy app\n```\n\n#### 2. Testing\n\n```bash\n# Run all tests\ndocker-compose exec app pytest\n\n# Run specific test file\ndocker-compose exec app pytest tests/unit_tests/test_api/test_webhooks.py\n\n# Run with coverage\ndocker-compose exec app pytest --cov=app\n```\n\n#### 3. Database Operations\n\n```bash\n# Create migration\ndocker-compose exec app alembic revision --autogenerate -m \"Description\"\n\n# Apply migrations\ndocker-compose exec app alembic upgrade head\n\n# Rollback migration\ndocker-compose exec app alembic downgrade -1\n\n# Reset database\ndocker-compose exec app alembic downgrade base\ndocker-compose exec app alembic upgrade head\n```\n\n#### 4. n8n Node Development\n\n```bash\n# Build n8n nodes\ncd n8n-nodes\npnpm build\n\n# Watch for changes\npnpm build:watch\n\n# Lint TypeScript\npnpm lint\n\n# Format code\npnpm format\n```\n\n### Environment Configuration\n\nKey environment variables in `.env`:\n\n```bash\n# Database\nDATABASE_URL=postgresql+asyncpg://user:password@localhost:5433/dbname\n\n# Redis\nREDIS_URL=redis://localhost:6380\n\n# Application\nENVIRONMENT=development\nDEBUG=true\nSECRET_KEY=your-secret-key\n\n# API\nAPI_V1_STR=/api/v1\nPROJECT_NAME=n8n-backend\n\n# CORS\nBACKEND_CORS_ORIGINS=[\"http://localhost:3000\", \"http://localhost:8080\"]\n```\n\n## 🚀 Deployment\n\n### Production Deployment\n\n#### Using Docker Compose\n\n```bash\n# Production deployment\ndocker-compose -f docker-compose.yml up --build -d\n\n# Check logs\ndocker-compose logs -f app\n```\n\n#### Using Coolify or Similar Platforms\n\n1. **Set environment variables** in your platform\n2. **Configure the build** to use `docker-compose.yml`\n3. **Set up health checks** pointing to `/health`\n4. **Configure domains** for your services\n\n#### Environment Variables for Production\n\n```bash\n# Database (use managed database service)\nDATABASE_URL=postgresql+asyncpg://user:password@db-host:5432/dbname\n\n# Redis (use managed Redis service)\nREDIS_URL=redis://redis-host:6379\n\n# Application\nENVIRONMENT=production\nDEBUG=false\nSECRET_KEY=your-production-secret-key\n\n# Security\nALLOWED_HOSTS=[\"yourdomain.com\", \"api.yourdomain.com\"]\n```\n\n### Production Services\n\n- **FastAPI Application**: Port 8000\n- **pgAdmin**: Port 5050 (admin@n8n-backend.local / admin)\n- **PostgreSQL**: Port 5432\n- **Redis**: Port 6379\n\n### Health Checks\n\nConfigure your deployment platform to use:\n- **Health Check URL**: `/health`\n- **Expected Response**: `{\"status\": \"healthy\"}`\n- **Timeout**: 30 seconds\n- **Interval**: 60 seconds\n\n### Scaling Considerations\n\n#### Horizontal Scaling\n- Run multiple FastAPI instances behind a load balancer\n- Use managed database and Redis services\n- Configure session affinity if needed\n\n#### Performance Optimization\n- Enable Redis caching for frequently accessed data\n- Use database connection pooling\n- Implement proper indexing on database tables\n- Use async operations throughout the application\n\n## 🔍 Troubleshooting\n\n### Common Issues\n\n#### 1. Connection Failed\n**Symptoms**: n8n nodes can't connect to FastAPI backend\n\n**Solutions**:\n- ✅ Verify FastAPI backend is running: `curl http://localhost:8000/health`\n- ✅ Check server URL in n8n credentials\n- ✅ Ensure CORS is configured: Check `BACKEND_CORS_ORIGINS` in `.env`\n- ✅ Verify network connectivity between n8n and backend\n\n#### 2. Authentication Errors\n**Symptoms**: 401 Unauthorized responses\n\n**Solutions**:\n- ✅ Verify API key/token is correct\n- ✅ Check authentication method selection in n8n credentials\n- ✅ Ensure FastAPI backend accepts the auth method\n- ✅ Check token expiration if using JWT\n\n#### 3. Database Connection Issues\n**Symptoms**: Database connection errors, migration failures\n\n**Solutions**:\n- ✅ Check database is running: `docker-compose ps`\n- ✅ Verify DATABASE_URL in `.env`\n- ✅ Check database logs: `docker-compose logs postgres`\n- ✅ Ensure database exists and user has permissions\n\n#### 4. n8n Nodes Not Loading\n**Symptoms**: Custom nodes don't appear in n8n\n\n**Solutions**:\n- ✅ Restart n8n after node installation\n- ✅ Check n8n logs for loading errors\n- ✅ Verify package is properly installed: `npm list @your-company/n8n-nodes`\n- ✅ Check node package.json configuration\n\n#### 5. Webhook Execution Failures\n**Symptoms**: Webhooks return errors or don't execute\n\n**Solutions**:\n- ✅ Test webhook directly: `curl -X POST http://localhost:8000/api/v1/webhooks/test/endpoint`\n- ✅ Check FastAPI logs for errors\n- ✅ Verify webhook exists in database\n- ✅ Check request payload format\n\n### Debug Mode\n\n#### Enable Debug Logging\n\n```python\n# app/core/config.py\nimport logging\n\nif settings.DEBUG:\n    logging.basicConfig(level=logging.DEBUG)\n```\n\n#### n8n Debug Mode\n\nEnable debug mode in webhook triggers to see detailed request/response information.\n\n#### Database Query Debugging\n\n```python\n# app/core/database.py\nengine = create_async_engine(\n    settings.DATABASE_URL,\n    echo=settings.DEBUG,  # Logs all SQL queries\n)\n```\n\n### Performance Issues\n\n#### Slow API Responses\n\n**Diagnosis**:\n```bash\n# Check response times\ncurl -w \"@curl-format.txt\" -o /dev/null -s http://localhost:8000/api/v1/webhooks/\n\n# Monitor database queries\ndocker-compose logs postgres | grep \"duration:\"\n```\n\n**Solutions**:\n- ✅ Add database indexes for frequently queried fields\n- ✅ Implement Redis caching for expensive operations\n- ✅ Use async operations throughout the application\n- ✅ Optimize database queries\n\n#### High Memory Usage\n\n**Diagnosis**:\n```bash\n# Check container memory usage\ndocker stats\n\n# Check application memory\ndocker-compose exec app python -c \"import psutil; print(f'Memory: {psutil.virtual_memory().percent}%')\"\n```\n\n**Solutions**:\n- ✅ Implement proper connection pooling\n- ✅ Add memory limits to Docker containers\n- ✅ Use streaming for large data processing\n- ✅ Implement proper garbage collection\n\n### Getting Help\n\n1. **Check Logs**:\n   ```bash\n   # FastAPI logs\n   docker-compose logs app\n   \n   # Database logs\n   docker-compose logs postgres\n   \n   # Redis logs\n   docker-compose logs redis\n   \n   # n8n logs (if running n8n in Docker)\n   docker-compose logs n8n\n   ```\n\n2. **Test Components Individually**:\n   ```bash\n   # Test FastAPI health\n   curl http://localhost:8000/health\n   \n   # Test database connection\n   docker-compose exec app python -c \"from app.core.database import engine; print('DB OK')\"\n   \n   # Test Redis connection\n   docker-compose exec app python -c \"import redis; r=redis.from_url('redis://redis:6379'); r.ping(); print('Redis OK')\"\n   ```\n\n3. **Enable Verbose Logging**:\n   ```bash\n   # Set DEBUG=true in .env\n   echo \"DEBUG=true\" \u003e\u003e .env\n   docker-compose restart app\n   ```\n\n## 📄 Configuration Reference\n\n### Environment Variables\n\n| Variable | Description | Default | Required |\n|----------|-------------|---------|----------|\n| `DATABASE_URL` | PostgreSQL connection string | - | ✅ |\n| `REDIS_URL` | Redis connection string | - | ✅ |\n| `ENVIRONMENT` | Environment (development/production) | development | ❌ |\n| `DEBUG` | Enable debug mode | false | ❌ |\n| `SECRET_KEY` | Application secret key | - | ✅ |\n| `API_V1_STR` | API version prefix | /api/v1 | ❌ |\n| `PROJECT_NAME` | Project name | n8n-backend | ❌ |\n| `BACKEND_CORS_ORIGINS` | Allowed CORS origins | [] | ❌ |\n\n### Docker Compose Services\n\n| Service | Port | Description |\n|---------|------|-------------|\n| `app` | 8000 | FastAPI application |\n| `postgres` | 5432/5433 | PostgreSQL database |\n| `redis` | 6379/6380 | Redis cache |\n| `pgadmin` | 5050/5051 | Database administration |\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature/my-new-feature`\n3. Make your changes\n4. Add tests for new functionality\n5. Run the test suite: `docker-compose exec app pytest`\n6. Run code quality checks:\n   ```bash\n   docker-compose exec app black .\n   docker-compose exec app isort .\n   docker-compose exec app flake8\n   docker-compose exec app mypy app\n   ```\n7. Commit your changes: `git commit -am 'Add my new feature'`\n8. Push to the branch: `git push origin feature/my-new-feature`\n9. Submit a pull request\n\n## 📜 License\n\n[Add your license information here]\n\n## 🆘 Support\n\nFor support and questions:\n\n1. **Check the Documentation**: Review this README and the troubleshooting section\n2. **Check Logs**: Enable debug mode and review application logs\n3. **Test Components**: Use the provided test commands to isolate issues\n4. **Community**: Open an issue on GitHub with detailed information about your problem\n\n## 🎯 Next Steps\n\nAfter setting up your n8n-backend integration:\n\n1. **Customize Business Logic**: Replace placeholder implementations with your real business logic\n2. **Add Authentication**: Implement proper authentication and authorization\n3. **Create Custom Nodes**: Build additional n8n nodes for your specific use cases\n4. **Add Monitoring**: Implement logging, metrics, and monitoring for production\n5. **Scale**: Configure horizontal scaling and performance optimization\n6. **Document**: Create user guides and API documentation for your team\n\n---\n\n**Ready to integrate your business logic with n8n? Start with the [Quick Start](#-quick-start) section and follow the [Business Logic Integration](#-business-logic-integration) guide!**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcgast%2Fn8n-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcgast%2Fn8n-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcgast%2Fn8n-backend/lists"}