https://github.com/cgast/n8n-backend
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.
https://github.com/cgast/n8n-backend
backend-api custom-nodes fastapi n8n postgres python
Last synced: about 2 months ago
JSON representation
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.
- Host: GitHub
- URL: https://github.com/cgast/n8n-backend
- Owner: cgast
- Created: 2025-07-09T08:36:14.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2025-07-09T08:36:17.000Z (12 months ago)
- Last Synced: 2025-07-11T13:18:56.223Z (12 months ago)
- Topics: backend-api, custom-nodes, fastapi, n8n, postgres, python
- Language: Python
- Homepage:
- Size: 48.8 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# n8n-backend: FastAPI Backend with n8n Integration
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.
## 🚀 Quick Start
### Prerequisites
- Docker and Docker Compose
- Python 3.11+ (for local development)
- Node.js 18.10+ and pnpm 8.1+ (for n8n nodes)
### 30-Second Setup
```bash
# Clone and start the development environment
git clone
cd n8n-backend
docker-compose up --build
# Run database migrations
docker-compose exec app alembic upgrade head
```
**Services will be available at:**
- 🌐 FastAPI Application: http://localhost:8000
- 📚 API Documentation: http://localhost:8000/docs
- 🗄️ pgAdmin: http://localhost:5051 (dev@n8n-backend.local / dev123)
- 🔴 Redis: localhost:6380
- 🐘 PostgreSQL: localhost:5433
### Test Your Setup
```bash
# Health check
curl http://localhost:8000/health
# Create your first webhook
curl -X POST http://localhost:8000/api/v1/webhooks/ \
-H "Content-Type: application/json" \
-d '{
"name": "my-first-webhook",
"description": "Test webhook for business logic",
"endpoint": "test-endpoint",
"method": "POST"
}'
# Execute the webhook
curl -X POST http://localhost:8000/api/v1/webhooks/execute/test-endpoint \
-H "Content-Type: application/json" \
-d '{"message": "Hello from my business logic!"}'
```
## 📋 Table of Contents
- [Features](#-features)
- [Architecture Overview](#-architecture-overview)
- [Project Structure](#-project-structure)
- [Quick Start](#-quick-start)
- [Business Logic Integration](#-business-logic-integration)
- [n8n Integration](#-n8n-integration)
- [API Reference](#-api-reference)
- [How-To Guides](#-how-to-guides)
- [Development](#-development)
- [Deployment](#-deployment)
- [Troubleshooting](#-troubleshooting)
## ✨ Features
### Core Backend Features
- **FastAPI Framework**: Modern, fast web framework with automatic API documentation
- **Async PostgreSQL**: High-performance database operations with SQLAlchemy 2.0
- **pgvector Support**: Ready for AI/ML integrations with vector database capabilities
- **Redis Integration**: Caching and background task support
- **Docker Compose**: Complete development and production environment
- **Clean Architecture**: Repository pattern, service layer, and dependency injection
- **Comprehensive Testing**: Async test suite with pytest
- **Database Migrations**: Alembic for schema management
### Business Logic Integration
- **Webhook Management**: Dynamic webhook creation and execution for your business logic
- **Function Domains**: Organized business logic packages with versioning
- **Flexible API Design**: Easy integration of custom business operations
- **Authentication Ready**: Multiple auth methods (API Key, Bearer Token, etc.)
- **Data Processing**: Built-in data transformation, validation, and export capabilities
### n8n Integration Features
- **Custom n8n Nodes**: Pre-built nodes for seamless workflow integration
- **HTTP Request Architecture**: Clean separation between n8n and business logic
- **Auto-Registration**: Webhooks automatically register with your backend
- **Debug Support**: Comprehensive logging and debugging capabilities
- **Scalable Design**: Backend and n8n scale independently
## 🏗️ Architecture Overview
The integration follows the **HTTP Request Nodes** approach, providing clean separation of concerns:
```mermaid
graph LR
A[n8n Workflow] --> B[Custom n8n Node]
B --> C[HTTP Request]
C --> D[FastAPI Backend]
D --> E[Your Business Logic]
D --> F[Database/Redis]
E --> G[Response]
G --> B
B --> H[n8n Output]
```
### Benefits
- ✅ **Separation of Concerns**: Business logic stays in FastAPI
- ✅ **Maintainability**: Updates don't require rebuilding n8n nodes
- ✅ **Scalability**: FastAPI backend scales independently
- ✅ **Reusability**: Endpoints serve multiple clients
- ✅ **Flexibility**: Easy to add new operations and authentication
## 📁 Project Structure
```
├── app/ # FastAPI Application
│ ├── api/
│ │ ├── dependencies/ # FastAPI dependency injection
│ │ └── routes/ # API endpoint definitions
│ │ ├── webhooks.py # Webhook management
│ │ ├── function_domains.py # Business logic packages
│ │ ├── n8n_operations.py # n8n-specific endpoints
│ │ └── health.py # Health checks
│ ├── core/ # Configuration and database setup
│ ├── db/
│ │ ├── models/ # SQLAlchemy models
│ │ └── repositories/ # Data access layer
│ ├── models/
│ │ ├── domain/ # Business entity schemas
│ │ └── utility_schemas/ # Common validation schemas
│ └── services/ # Business logic layer
├── n8n-nodes/ # n8n Node Package
│ ├── credentials/
│ │ └── YourCompanyApi.credentials.ts
│ ├── nodes/
│ │ └── YourCompany/
│ │ ├── Webhook/ # Webhook management nodes
│ │ ├── FunctionDomain/ # Function domain operations
│ │ └── BusinessLogic/ # Your business logic nodes
│ └── package.json
├── migrations/ # Database migration files
├── tests/ # Test suite
├── scripts/ # Utility scripts
├── docker-compose.yml # Production configuration
├── docker-compose.override.yml # Development overrides
└── pyproject.toml # Python dependencies
```
## 🔧 Business Logic Integration
### Step 1: Define Your Business Logic
Create your business logic as FastAPI endpoints. The system provides several patterns:
#### Pattern 1: Direct Webhook Integration
Perfect for simple business operations:
```python
# app/api/routes/my_business_logic.py
from fastapi import APIRouter, Depends
from app.services.my_service import MyBusinessService
router = APIRouter()
@router.post("/process-order")
async def process_order(
order_data: dict,
service: MyBusinessService = Depends()
):
"""Your business logic for processing orders"""
result = await service.process_order(order_data)
return {"success": True, "order_id": result.id}
```
#### Pattern 2: Function Domain Integration
For complex, organized business logic packages:
```python
# app/api/routes/function_domains.py
@router.post("/")
async def create_function_domain(
domain: FunctionDomainCreate,
service: FunctionDomainService = Depends(get_function_domain_service)
):
"""Create a new business logic package"""
return await service.create_function_domain(domain)
```
#### Pattern 3: n8n Operations Integration
For operations specifically designed for n8n workflows:
```python
# app/api/routes/n8n_operations.py
@router.post("/user-management")
async def user_management_operation(request: NodeRequest):
"""Handle user management operations from n8n"""
operation = request.operation
data = request.data
if operation == "create_user":
# Your user creation logic
result = await create_user_logic(data)
elif operation == "get_user":
# Your user retrieval logic
result = await get_user_logic(data)
return NodeResponse(success=True, data=result)
```
### Step 2: Register Your Endpoints
Add your business logic routes to the main application:
```python
# app/main.py
from app.api.routes import my_business_logic
application.include_router(
my_business_logic.router,
prefix=f"{settings.API_V1_STR}/my-business",
tags=["my-business"]
)
```
### Step 3: Create Database Models (if needed)
```python
# app/db/models/my_model.py
from app.db.models.base import Base
from sqlalchemy import Column, Integer, String, DateTime
class MyBusinessEntity(Base):
__tablename__ = "my_business_entities"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
```
### Step 4: Implement Services
```python
# app/services/my_service.py
from app.db.repositories.my_repository import MyRepository
class MyBusinessService:
def __init__(self, repository: MyRepository):
self.repository = repository
async def process_order(self, order_data: dict):
# Your business logic here
return await self.repository.create(order_data)
```
### Step 5: Test Your Integration
```bash
# Test your business logic endpoint
curl -X POST http://localhost:8000/api/v1/my-business/process-order \
-H "Content-Type: application/json" \
-d '{"customer_id": 123, "items": [{"id": 1, "quantity": 2}]}'
```
## 🔗 n8n Integration
### Installation
#### 1. Install n8n Nodes
```bash
# From the n8n-nodes directory
cd n8n-nodes
pnpm install
pnpm build
# Install in your n8n instance
npm install /path/to/n8n-nodes
```
#### 2. Configure n8n Credentials
1. Go to n8n **Settings** → **Credentials**
2. Add "Your Company API" credential
3. Configure:
- **Server URL**: `http://localhost:8000` (or your backend URL)
- **Authentication Method**: Choose your preferred method
- **API Key/Bearer Token**: If using authentication
#### 3. Test Connection
Use the credential test feature to verify connectivity to your FastAPI backend.
### Available n8n Nodes
#### Webhook Manager Node
Manage webhooks in your FastAPI backend:
```json
{
"operation": "create",
"name": "Order Processing Webhook",
"endpoint": "order-webhook",
"method": "POST",
"description": "Handles new order notifications"
}
```
#### Webhook Trigger Node
Start workflows when webhooks are received:
```json
{
"webhookEndpoint": "order-notifications",
"autoRegister": true,
"webhookName": "Order Processing Trigger",
"responseMode": "onReceived"
}
```
#### Function Domain Node
Manage business logic packages:
```json
{
"operation": "create",
"name": "E-commerce Operations",
"description": "Handles all e-commerce related functions",
"config": {
"version": "1.0.0",
"environment": "production"
}
}
```
#### User Management Node
Handle user operations:
```json
{
"operation": "create_user",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe",
"password": "secure_password"
}
```
#### Data Processing Node
Process data using your backend:
```json
{
"operation": "transform_data",
"transformationRules": {
"name": {"type": "uppercase"},
"price": {"type": "multiply", "factor": 1.1}
}
}
```
### Workflow Examples
#### Example 1: Order Processing Workflow
```
Webhook Trigger (order-received)
↓ [Order data]
User Management (get customer details)
↓ [Customer + Order data]
Data Processing (validate order data)
↓ [Validated order]
Webhook Manager (execute fulfillment webhook)
↓ [Fulfillment response]
```
#### Example 2: Data Pipeline Workflow
```
HTTP Request (fetch data from external API)
↓ [Raw data]
Data Processing (transform data)
↓ [Transformed data]
Data Processing (validate data)
↓ [Validated data]
Data Processing (export to CSV)
↓ [Export URL]
```
## 📖 API Reference
### Core Endpoints
#### Health Check
```bash
GET /health
```
#### Webhook Management
```bash
# List webhooks
GET /api/v1/webhooks/
# Create webhook
POST /api/v1/webhooks/
{
"name": "webhook-name",
"description": "Description",
"endpoint": "endpoint-name",
"method": "POST"
}
# Get webhook
GET /api/v1/webhooks/{id}
# Update webhook
PUT /api/v1/webhooks/{id}
# Delete webhook
DELETE /api/v1/webhooks/{id}
# Execute webhook
POST /api/v1/webhooks/execute/{endpoint}
# Test webhook (with debug info)
POST /api/v1/webhooks/test/{endpoint}
```
#### Function Domain Management
```bash
# List function domains
GET /api/v1/function-domains/
# Create function domain
POST /api/v1/function-domains/
{
"name": "domain-name",
"description": "Description",
"config": {}
}
# Get function domain
GET /api/v1/function-domains/{id}
# Update function domain
PUT /api/v1/function-domains/{id}
# Delete function domain
DELETE /api/v1/function-domains/{id}
```
#### n8n Integration Endpoints
```bash
# User management operations
POST /api/v1/n8n/user-management
{
"operation": "create_user|get_user|update_user|delete_user",
"data": {...}
}
# Data processing operations
POST /api/v1/n8n/data-processing
{
"operation": "transform_data|validate_data|aggregate_data|filter_data|enrich_data|export_data",
"data": {...}
}
```
### Request/Response Examples
#### User Management Request
```json
POST /api/v1/n8n/user-management
{
"operation": "create_user",
"data": {
"email": "john.doe@example.com",
"password": "secure_password",
"first_name": "John",
"last_name": "Doe"
}
}
```
#### Data Processing Request
```json
POST /api/v1/n8n/data-processing
{
"operation": "transform_data",
"data": {
"transformation_rules": {
"name": {"type": "uppercase"},
"price": {"type": "multiply", "factor": 1.1}
}
},
"input_data": {
"name": "product name",
"price": 100
}
}
```
#### Standard Response Format
```json
{
"success": true,
"data": {
"original_data": {"name": "product name", "price": 100},
"transformed_data": {"name": "PRODUCT NAME", "price": 110},
"processed_at": "2025-01-07T09:00:00Z"
}
}
```
## 📚 How-To Guides
### How to Add New Business Logic
#### 1. Create the Business Logic Endpoint
```python
# app/api/routes/my_new_feature.py
from fastapi import APIRouter, Depends
from app.services.my_new_service import MyNewService
router = APIRouter()
@router.post("/process")
async def process_my_data(
data: dict,
service: MyNewService = Depends()
):
result = await service.process(data)
return {"success": True, "result": result}
```
#### 2. Create the Service Layer
```python
# app/services/my_new_service.py
class MyNewService:
async def process(self, data: dict):
# Your business logic here
processed_data = self.transform_data(data)
return processed_data
def transform_data(self, data: dict):
# Implementation
return data
```
#### 3. Register the Router
```python
# app/main.py
from app.api.routes import my_new_feature
application.include_router(
my_new_feature.router,
prefix=f"{settings.API_V1_STR}/my-new-feature",
tags=["my-new-feature"]
)
```
#### 4. Create Database Models (if needed)
```python
# app/db/models/my_new_model.py
from app.db.models.base import Base
from sqlalchemy import Column, Integer, String
class MyNewEntity(Base):
__tablename__ = "my_new_entities"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
```
#### 5. Run Migration
```bash
# Create migration
docker-compose exec app alembic revision --autogenerate -m "Add my new entity"
# Apply migration
docker-compose exec app alembic upgrade head
```
### How to Create Custom n8n Nodes
#### 1. Create Node File
```typescript
// n8n-nodes/nodes/YourCompany/MyNewFeature/MyNewFeature.node.ts
import { INodeType, INodeTypeDescription } from 'n8n-workflow';
export class MyNewFeature implements INodeType {
description: INodeTypeDescription = {
displayName: 'My New Feature',
name: 'myNewFeature',
group: ['transform'],
version: 1,
description: 'Process data with my new feature',
defaults: {
name: 'My New Feature',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'yourCompanyApi',
required: true,
},
],
properties: [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Process Data',
value: 'process',
},
],
default: 'process',
},
],
};
async execute(this: IExecuteFunctions): Promise {
// Implementation
}
}
```
#### 2. Build and Install
```bash
cd n8n-nodes
pnpm build
npm install /path/to/n8n-nodes
```
### How to Set Up Authentication
#### 1. Configure FastAPI Authentication
```python
# app/core/auth.py
from fastapi import HTTPException, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
async def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):
if credentials.credentials != "your-secret-token":
raise HTTPException(status_code=401, detail="Invalid token")
return credentials.credentials
```
#### 2. Protect Your Endpoints
```python
# app/api/routes/protected_route.py
from app.core.auth import verify_token
@router.post("/protected-endpoint")
async def protected_endpoint(
data: dict,
token: str = Depends(verify_token)
):
# Your protected business logic
return {"message": "Access granted"}
```
#### 3. Configure n8n Credentials
Update your n8n credentials to include the authentication token.
### How to Add Data Validation
#### 1. Create Pydantic Models
```python
# app/models/domain/my_data.py
from pydantic import BaseModel, validator
class MyDataInput(BaseModel):
name: str
email: str
age: int
@validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email format')
return v
@validator('age')
def validate_age(cls, v):
if v < 0 or v > 150:
raise ValueError('Age must be between 0 and 150')
return v
```
#### 2. Use in Endpoints
```python
@router.post("/validate-data")
async def validate_data(data: MyDataInput):
# Data is automatically validated
return {"message": "Data is valid", "data": data}
```
### How to Add Caching
#### 1. Configure Redis Caching
```python
# app/services/cached_service.py
import redis
import json
from app.core.config import settings
redis_client = redis.from_url(settings.REDIS_URL)
class CachedService:
async def get_cached_data(self, key: str):
cached = redis_client.get(key)
if cached:
return json.loads(cached)
# Fetch data from database or external API
data = await self.fetch_data()
# Cache for 1 hour
redis_client.setex(key, 3600, json.dumps(data))
return data
```
### How to Add Background Tasks
#### 1. Create Background Task
```python
# app/services/background_service.py
from fastapi import BackgroundTasks
def process_in_background(data: dict):
# Long-running task
time.sleep(10)
print(f"Processed: {data}")
@router.post("/async-process")
async def async_process(
data: dict,
background_tasks: BackgroundTasks
):
background_tasks.add_task(process_in_background, data)
return {"message": "Task started in background"}
```
## 🛠️ Development
### Local Development Setup
#### Without Docker
```bash
# Install dependencies
pip install -e .[dev]
# Set up environment
cp .env.example .env
# Edit .env with your configuration
# Run the application
uvicorn app.main:app --reload
```
#### With Docker (Recommended)
```bash
# Start development environment
docker-compose up --build
# Run commands in container
docker-compose exec app pytest
docker-compose exec app alembic upgrade head
```
### Development Workflow
#### 1. Code Quality
```bash
# Format code
docker-compose exec app black .
docker-compose exec app isort .
# Lint code
docker-compose exec app flake8
docker-compose exec app mypy app
```
#### 2. Testing
```bash
# Run all tests
docker-compose exec app pytest
# Run specific test file
docker-compose exec app pytest tests/unit_tests/test_api/test_webhooks.py
# Run with coverage
docker-compose exec app pytest --cov=app
```
#### 3. Database Operations
```bash
# Create migration
docker-compose exec app alembic revision --autogenerate -m "Description"
# Apply migrations
docker-compose exec app alembic upgrade head
# Rollback migration
docker-compose exec app alembic downgrade -1
# Reset database
docker-compose exec app alembic downgrade base
docker-compose exec app alembic upgrade head
```
#### 4. n8n Node Development
```bash
# Build n8n nodes
cd n8n-nodes
pnpm build
# Watch for changes
pnpm build:watch
# Lint TypeScript
pnpm lint
# Format code
pnpm format
```
### Environment Configuration
Key environment variables in `.env`:
```bash
# Database
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5433/dbname
# Redis
REDIS_URL=redis://localhost:6380
# Application
ENVIRONMENT=development
DEBUG=true
SECRET_KEY=your-secret-key
# API
API_V1_STR=/api/v1
PROJECT_NAME=n8n-backend
# CORS
BACKEND_CORS_ORIGINS=["http://localhost:3000", "http://localhost:8080"]
```
## 🚀 Deployment
### Production Deployment
#### Using Docker Compose
```bash
# Production deployment
docker-compose -f docker-compose.yml up --build -d
# Check logs
docker-compose logs -f app
```
#### Using Coolify or Similar Platforms
1. **Set environment variables** in your platform
2. **Configure the build** to use `docker-compose.yml`
3. **Set up health checks** pointing to `/health`
4. **Configure domains** for your services
#### Environment Variables for Production
```bash
# Database (use managed database service)
DATABASE_URL=postgresql+asyncpg://user:password@db-host:5432/dbname
# Redis (use managed Redis service)
REDIS_URL=redis://redis-host:6379
# Application
ENVIRONMENT=production
DEBUG=false
SECRET_KEY=your-production-secret-key
# Security
ALLOWED_HOSTS=["yourdomain.com", "api.yourdomain.com"]
```
### Production Services
- **FastAPI Application**: Port 8000
- **pgAdmin**: Port 5050 (admin@n8n-backend.local / admin)
- **PostgreSQL**: Port 5432
- **Redis**: Port 6379
### Health Checks
Configure your deployment platform to use:
- **Health Check URL**: `/health`
- **Expected Response**: `{"status": "healthy"}`
- **Timeout**: 30 seconds
- **Interval**: 60 seconds
### Scaling Considerations
#### Horizontal Scaling
- Run multiple FastAPI instances behind a load balancer
- Use managed database and Redis services
- Configure session affinity if needed
#### Performance Optimization
- Enable Redis caching for frequently accessed data
- Use database connection pooling
- Implement proper indexing on database tables
- Use async operations throughout the application
## 🔍 Troubleshooting
### Common Issues
#### 1. Connection Failed
**Symptoms**: n8n nodes can't connect to FastAPI backend
**Solutions**:
- ✅ Verify FastAPI backend is running: `curl http://localhost:8000/health`
- ✅ Check server URL in n8n credentials
- ✅ Ensure CORS is configured: Check `BACKEND_CORS_ORIGINS` in `.env`
- ✅ Verify network connectivity between n8n and backend
#### 2. Authentication Errors
**Symptoms**: 401 Unauthorized responses
**Solutions**:
- ✅ Verify API key/token is correct
- ✅ Check authentication method selection in n8n credentials
- ✅ Ensure FastAPI backend accepts the auth method
- ✅ Check token expiration if using JWT
#### 3. Database Connection Issues
**Symptoms**: Database connection errors, migration failures
**Solutions**:
- ✅ Check database is running: `docker-compose ps`
- ✅ Verify DATABASE_URL in `.env`
- ✅ Check database logs: `docker-compose logs postgres`
- ✅ Ensure database exists and user has permissions
#### 4. n8n Nodes Not Loading
**Symptoms**: Custom nodes don't appear in n8n
**Solutions**:
- ✅ Restart n8n after node installation
- ✅ Check n8n logs for loading errors
- ✅ Verify package is properly installed: `npm list @your-company/n8n-nodes`
- ✅ Check node package.json configuration
#### 5. Webhook Execution Failures
**Symptoms**: Webhooks return errors or don't execute
**Solutions**:
- ✅ Test webhook directly: `curl -X POST http://localhost:8000/api/v1/webhooks/test/endpoint`
- ✅ Check FastAPI logs for errors
- ✅ Verify webhook exists in database
- ✅ Check request payload format
### Debug Mode
#### Enable Debug Logging
```python
# app/core/config.py
import logging
if settings.DEBUG:
logging.basicConfig(level=logging.DEBUG)
```
#### n8n Debug Mode
Enable debug mode in webhook triggers to see detailed request/response information.
#### Database Query Debugging
```python
# app/core/database.py
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG, # Logs all SQL queries
)
```
### Performance Issues
#### Slow API Responses
**Diagnosis**:
```bash
# Check response times
curl -w "@curl-format.txt" -o /dev/null -s http://localhost:8000/api/v1/webhooks/
# Monitor database queries
docker-compose logs postgres | grep "duration:"
```
**Solutions**:
- ✅ Add database indexes for frequently queried fields
- ✅ Implement Redis caching for expensive operations
- ✅ Use async operations throughout the application
- ✅ Optimize database queries
#### High Memory Usage
**Diagnosis**:
```bash
# Check container memory usage
docker stats
# Check application memory
docker-compose exec app python -c "import psutil; print(f'Memory: {psutil.virtual_memory().percent}%')"
```
**Solutions**:
- ✅ Implement proper connection pooling
- ✅ Add memory limits to Docker containers
- ✅ Use streaming for large data processing
- ✅ Implement proper garbage collection
### Getting Help
1. **Check Logs**:
```bash
# FastAPI logs
docker-compose logs app
# Database logs
docker-compose logs postgres
# Redis logs
docker-compose logs redis
# n8n logs (if running n8n in Docker)
docker-compose logs n8n
```
2. **Test Components Individually**:
```bash
# Test FastAPI health
curl http://localhost:8000/health
# Test database connection
docker-compose exec app python -c "from app.core.database import engine; print('DB OK')"
# Test Redis connection
docker-compose exec app python -c "import redis; r=redis.from_url('redis://redis:6379'); r.ping(); print('Redis OK')"
```
3. **Enable Verbose Logging**:
```bash
# Set DEBUG=true in .env
echo "DEBUG=true" >> .env
docker-compose restart app
```
## 📄 Configuration Reference
### Environment Variables
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `DATABASE_URL` | PostgreSQL connection string | - | ✅ |
| `REDIS_URL` | Redis connection string | - | ✅ |
| `ENVIRONMENT` | Environment (development/production) | development | ❌ |
| `DEBUG` | Enable debug mode | false | ❌ |
| `SECRET_KEY` | Application secret key | - | ✅ |
| `API_V1_STR` | API version prefix | /api/v1 | ❌ |
| `PROJECT_NAME` | Project name | n8n-backend | ❌ |
| `BACKEND_CORS_ORIGINS` | Allowed CORS origins | [] | ❌ |
### Docker Compose Services
| Service | Port | Description |
|---------|------|-------------|
| `app` | 8000 | FastAPI application |
| `postgres` | 5432/5433 | PostgreSQL database |
| `redis` | 6379/6380 | Redis cache |
| `pgadmin` | 5050/5051 | Database administration |
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/my-new-feature`
3. Make your changes
4. Add tests for new functionality
5. Run the test suite: `docker-compose exec app pytest`
6. Run code quality checks:
```bash
docker-compose exec app black .
docker-compose exec app isort .
docker-compose exec app flake8
docker-compose exec app mypy app
```
7. Commit your changes: `git commit -am 'Add my new feature'`
8. Push to the branch: `git push origin feature/my-new-feature`
9. Submit a pull request
## 📜 License
[Add your license information here]
## 🆘 Support
For support and questions:
1. **Check the Documentation**: Review this README and the troubleshooting section
2. **Check Logs**: Enable debug mode and review application logs
3. **Test Components**: Use the provided test commands to isolate issues
4. **Community**: Open an issue on GitHub with detailed information about your problem
## 🎯 Next Steps
After setting up your n8n-backend integration:
1. **Customize Business Logic**: Replace placeholder implementations with your real business logic
2. **Add Authentication**: Implement proper authentication and authorization
3. **Create Custom Nodes**: Build additional n8n nodes for your specific use cases
4. **Add Monitoring**: Implement logging, metrics, and monitoring for production
5. **Scale**: Configure horizontal scaling and performance optimization
6. **Document**: Create user guides and API documentation for your team
---
**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!**