Deploying DreamFactory
Introduction
DreamFactory is a powerful open-source REST API platform that automatically generates secure, fully documented REST APIs for databases, file storage systems, external web services, and more. Built with PHP and Laravel, DreamFactory eliminates the need to write boilerplate API code, allowing developers to focus on building features instead of managing API infrastructure.
DreamFactory transforms your data sources into production-ready APIs within minutes, supporting:
- Database REST APIs: Instant REST APIs for SQL (MySQL, PostgreSQL, SQL Server) and NoSQL databases (MongoDB, DynamoDB, Cassandra)
- File Storage APIs: Access local files, AWS S3, Azure Blob Storage, and Google Cloud Storage through unified REST endpoints
- External Service Integration: Connect to SOAP, REST APIs, email services, and more with consistent API interfaces
- Automatic API Documentation: Interactive Swagger/OpenAPI documentation generated automatically for all APIs
- Role-Based Access Control (RBAC): Fine-grained security with user roles, permissions, and API key management
- Server-Side Scripting: Customize API behavior with JavaScript, PHP, Python, or Node.js scripts
- API Caching: Built-in Redis support for high-performance API response caching
- Schema Management: Database schema explorer and management tools
- Multi-Tenancy Support: Manage multiple applications and environments from a single instance
This comprehensive guide walks you through deploying DreamFactory on Klutch.sh using Docker, configuring databases for the system and API services, setting up persistent storage, managing environment variables, and implementing production best practices for scalable API development.
Prerequisites
Before you begin deploying DreamFactory on Klutch.sh, ensure you have:
- A Klutch.sh account (sign up here)
- A GitHub repository for your DreamFactory deployment configuration
- Basic understanding of Docker containers, REST APIs, and databases
- A MySQL or PostgreSQL database for DreamFactory system data (can be deployed on Klutch.sh)
- (Optional) Redis instance for API caching and improved performance
- Access to the Klutch.sh dashboard
Understanding DreamFactory Architecture
DreamFactory consists of several key components:
- Web Application: PHP/Laravel-based admin interface for managing APIs, users, and services
- API Engine: Core REST API framework that handles authentication, routing, and service connections
- System Database: MySQL or PostgreSQL database storing DreamFactory configuration, users, roles, and API definitions
- Redis Cache (optional): Improves performance by caching API responses and session data
- File Storage: Persistent storage for uploaded files, scripts, and application assets
When deployed on Klutch.sh, DreamFactory automatically detects your Dockerfile and builds a container that includes PHP, Apache/Nginx web server, and all necessary dependencies. The platform manages SSL certificates, traffic routing, and provides persistent storage for your API configurations and data.
Project Structure
A minimal repository structure for deploying DreamFactory on Klutch.sh:
dreamfactory-deployment/├── Dockerfile├── .dockerignore├── .gitignore├── README.md└── docker.env.exampleThis streamlined structure allows Klutch.sh to automatically detect and build your DreamFactory container without requiring application source code, as the official DreamFactory Docker image includes everything needed.
Creating Your Dockerfile
Klutch.sh automatically detects a Dockerfile in the root directory of your repository. Create a Dockerfile that uses the official DreamFactory image:
Option 1: Basic Dockerfile (Quick Start)
FROM dreamfactorysoftware/df-docker:latest
# Expose DreamFactory's default portEXPOSE 80
# Health check for monitoringHEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \ CMD curl -f http://localhost/api/v2/system/environment || exit 1
# Use the default entrypoint from the base imageImportant Notes:
- The official DreamFactory image runs Apache web server on port 80
- Includes PHP 8.1+ with all required extensions
- Comes pre-configured with Laravel and DreamFactory application code
Option 2: Production Dockerfile with Custom Configuration
FROM dreamfactorysoftware/df-docker:4.11.0
# Install additional PHP extensions if neededRUN apt-get update && apt-get install -y \ php-redis \ php-mongodb \ && rm -rf /var/lib/apt/lists/*
# Set working directoryWORKDIR /opt/dreamfactory
# Expose the application portEXPOSE 80
# Health check for production monitoringHEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \ CMD curl -f http://localhost/api/v2/system/environment || exit 1
# Use default entrypoint and commandVersion Pinning: Always pin to a specific DreamFactory version (e.g., 4.11.0) for reproducible production deployments.
Option 3: Custom Dockerfile with Scripts and Plugins
FROM dreamfactorysoftware/df-docker:4.11.0
# Install additional system dependenciesRUN apt-get update && apt-get install -y \ php-redis \ php-mongodb \ php-pgsql \ php-sqlsrv \ curl \ git \ && rm -rf /var/lib/apt/lists/*
# Copy custom server-side scripts (optional)COPY ./scripts /opt/dreamfactory/storage/scripting
# Copy custom configuration files (optional)# COPY ./config /opt/dreamfactory/config
# Set correct permissionsRUN chown -R www-data:www-data /opt/dreamfactory/storage
# Expose portEXPOSE 80
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \ CMD curl -f http://localhost/api/v2/system/environment || exit 1Custom Scripts: DreamFactory supports server-side scripting in JavaScript, PHP, Python, and Node.js. Place scripts in /opt/dreamfactory/storage/scripting to make them available to your APIs.
Deploying to Klutch.sh
Follow these detailed steps to deploy DreamFactory on Klutch.sh with persistent storage and proper configuration.
Prerequisites: Deploy System Database
Before deploying DreamFactory, you need a MySQL or PostgreSQL database for system data:
-
Deploy MySQL or PostgreSQL: Follow the MySQL deployment guide or PostgreSQL deployment guide to create a database instance on Klutch.sh
-
Create DreamFactory Database:
For MySQL:
CREATE DATABASE dreamfactory CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;CREATE USER 'dreamfactory'@'%' IDENTIFIED BY 'secure-password-here';GRANT ALL PRIVILEGES ON dreamfactory.* TO 'dreamfactory'@'%';FLUSH PRIVILEGES;For PostgreSQL:
CREATE DATABASE dreamfactory;CREATE USER dreamfactory WITH PASSWORD 'secure-password-here';GRANT ALL PRIVILEGES ON DATABASE dreamfactory TO dreamfactory;
Note the database connection details - you’ll need them for DreamFactory’s environment variables.
(Optional) Deploy Redis for Caching
For production deployments, Redis significantly improves performance:
- Follow the Redis deployment guide to create a Redis instance
- Note the connection details for environment configuration
Deployment Steps
-
Create Your Repository
Create a new GitHub repository and add your Dockerfile:
Terminal window mkdir dreamfactory-deploymentcd dreamfactory-deployment# Create Dockerfilecat > Dockerfile << 'EOF'FROM dreamfactorysoftware/df-docker:4.11.0EXPOSE 80HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \CMD curl -f http://localhost/api/v2/system/environment || exit 1EOF# Create .gitignorecat > .gitignore << 'EOF'.env.DS_Store*.logEOF# Create READMEcat > README.md << 'EOF'# DreamFactory on Klutch.shProduction-ready DreamFactory REST API platform deployment.## Quick Start1. Deploy MySQL/PostgreSQL database2. Configure environment variables in Klutch.sh dashboard3. Deploy this repository4. Access DreamFactory at your assigned URL5. Complete initial setup wizard## Documentation- DreamFactory Docs: https://wiki.dreamfactory.com/- Klutch.sh Docs: https://docs.klutch.sh/EOF# Initialize git and pushgit initgit add .git commit -m "Initial DreamFactory deployment setup"git remote add origin https://github.com/YOUR_USERNAME/dreamfactory-deployment.gitgit push -u origin main -
Access the Klutch.sh Dashboard
Navigate to klutch.sh/app and log in to your account.
-
Create a New Project
- Click “New Project” in the dashboard
- Enter a project name (e.g., “API Platform”)
- Select your preferred region for deployment
-
Create a New Application
- Within your project, click “New App”
- Name your application (e.g., “DreamFactory”)
- Connect your GitHub repository containing the Dockerfile
-
Configure Build Settings
Klutch.sh automatically detects the Dockerfile in your repository root. If your Dockerfile is in a subdirectory, specify the build context path in the dashboard.
-
Set Up Persistent Storage
DreamFactory requires persistent storage for configuration, logs, and uploaded files:
- In the app settings, navigate to the “Volumes” section
- Click “Add Volume”
- Set the mount path to
/opt/dreamfactory/storage/app - Set the volume size (recommended: 10GB minimum for production)
- Click “Add” to attach the volume
Critical: The
/opt/dreamfactory/storage/appdirectory stores:- File storage service data
- Server-side scripts
- Package files
- Cache files (if not using Redis)
- Log files
-
Configure Environment Variables
In the app settings, add the following required environment variables:
Database Configuration (MySQL example):
Terminal window DB_DRIVER=mysqlDB_HOST=your-mysql-app.klutch.shDB_PORT=8000DB_DATABASE=dreamfactoryDB_USERNAME=dreamfactoryDB_PASSWORD=your-secure-passwordDatabase Configuration (PostgreSQL example):
Terminal window DB_DRIVER=pgsqlDB_HOST=your-postgres-app.klutch.shDB_PORT=8000DB_DATABASE=dreamfactoryDB_USERNAME=dreamfactoryDB_PASSWORD=your-secure-passwordApplication Configuration:
Terminal window APP_KEY=base64:YOUR_32_CHAR_RANDOM_STRING_HEREAPP_ENV=productionAPP_DEBUG=falseAPP_URL=https://your-app-name.klutch.shRedis Configuration (Optional but Recommended):
Terminal window CACHE_DRIVER=redisREDIS_CLIENT=phpredisREDIS_HOST=your-redis-app.klutch.shREDIS_PORT=8000REDIS_PASSWORD=your-redis-passwordEmail Configuration (Optional):
Terminal window MAIL_MAILER=smtpMAIL_HOST=smtp.example.comMAIL_PORT=587MAIL_USERNAME=your-smtp-usernameMAIL_PASSWORD=your-smtp-passwordMAIL_ENCRYPTION=tlsMAIL_FROM_ADDRESS=noreply@example.comMAIL_FROM_NAME=DreamFactoryGenerating APP_KEY:
Generate a secure application key:
Terminal window # Using opensslopenssl rand -base64 32# Or using PHP (if available locally)php artisan key:generate --showPrefix the generated key with
base64:when adding to environment variables.Security Best Practice: Always mark sensitive values like passwords, API keys, and APP_KEY as “Secret” in the Klutch.sh dashboard.
-
Configure Traffic Settings
- In the “Networking” section, select HTTP as the traffic type
- Set the internal port to 80 (DreamFactory’s default Apache port)
- Enable automatic HTTPS/SSL (provided by Klutch.sh)
-
Deploy the Application
- Review all settings
- Click “Deploy” to start the build process
- Klutch.sh will:
- Clone your repository
- Detect the Dockerfile
- Build the container image
- Deploy to your selected region
- Provision persistent storage
- Configure networking and SSL
- Run database migrations
-
Monitor Deployment Progress
- View real-time build logs in the dashboard
- Wait for the deployment status to show “Running”
- Initial startup may take 2-4 minutes as DreamFactory initializes the database and runs migrations
Once deployment completes, your DreamFactory instance will be accessible at https://your-app-name.klutch.sh.
Initial Setup and Configuration
After your DreamFactory instance is deployed, complete the initial setup through the web interface:
First-Time Setup Wizard
-
Access Your DreamFactory Instance
Navigate to
https://your-app-name.klutch.shin your browser. -
Create Administrator Account
On the setup page, create your first admin user:
- First Name: Your first name
- Last Name: Your last name
- Email: Admin email address (used for login)
- Password: Strong, unique password
- Confirm Password: Re-enter password
-
Review System Information
DreamFactory displays system information including:
- PHP version
- Database connection status
- Available services
- Installed extensions
-
Complete Setup
Click “Complete Setup” to finish initialization. You’ll be redirected to the DreamFactory admin interface.
Accessing the Admin Interface
The DreamFactory admin interface is your central hub for:
- Creating and managing APIs
- Configuring database connections
- Managing users and roles
- Setting up API keys
- Viewing API documentation
- Monitoring API usage
Login URL: https://your-app-name.klutch.sh
Use the email and password you created during setup to log in.
Creating Your First REST API
DreamFactory makes it incredibly easy to create REST APIs from existing data sources. Here’s a quick walkthrough:
Connecting a Database Service
-
Navigate to Services
In the admin interface, click Services in the left sidebar.
-
Create New Service
- Click the Create button in the top right
- Select Database from the service type dropdown
- Choose your database type (MySQL, PostgreSQL, MongoDB, etc.)
-
Configure Database Connection
For a MySQL database deployed on Klutch.sh:
Name: mysql_apiLabel: MySQL APIDescription: Production MySQL database APIActive: ✓Connection:Host: your-mysql-app.klutch.shPort: 8000Database: your_databaseUsername: your_usernamePassword: your_passwordAdvanced:Connection String: (leave empty for standard connection)Additional Options: (optional JSON configuration) -
Test Connection
Click “Test Connection” to verify DreamFactory can reach your database.
-
Save Service
Click “Save” to create the service. DreamFactory will:
- Connect to the database
- Introspect the schema
- Generate REST API endpoints for all tables
- Create automatic API documentation
Accessing Your New API
Once created, your database is immediately accessible via REST API:
Base URL: https://your-app-name.klutch.sh/api/v2/mysql_api
Common Endpoints:
GET /api/v2/mysql_api/_table/users- List all usersGET /api/v2/mysql_api/_table/users/1- Get user by IDPOST /api/v2/mysql_api/_table/users- Create new userPUT /api/v2/mysql_api/_table/users/1- Update userDELETE /api/v2/mysql_api/_table/users/1- Delete userGET /api/v2/mysql_api/_schema- Get database schema
Creating an API Key
To access your APIs, you need an API key:
-
Navigate to Apps
Click Apps in the left sidebar.
-
Create New App
- Click Create button
- Enter an app name (e.g., “Mobile App”)
- Select app type: “API Key”
- Choose role (start with “All Access” for testing, create custom roles for production)
- Click “Save”
-
Copy API Key
Your API key will be displayed. Copy it for use in your applications.
Important: Store API keys securely. They provide access to your APIs.
Making API Requests
Use your API key in the X-DreamFactory-API-Key header:
# List all userscurl https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users \ -H "X-DreamFactory-API-Key: YOUR_API_KEY"
# Create a new usercurl -X POST https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users \ -H "X-DreamFactory-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "resource": [{ "username": "johndoe", "email": "john@example.com", "first_name": "John", "last_name": "Doe" }] }'
# Get user by IDcurl https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users/1 \ -H "X-DreamFactory-API-Key: YOUR_API_KEY"
# Update usercurl -X PUT https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users/1 \ -H "X-DreamFactory-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "email": "newemail@example.com" }'
# Delete usercurl -X DELETE https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users/1 \ -H "X-DreamFactory-API-Key: YOUR_API_KEY"Sample Code: Connecting from Applications
Here are examples of connecting to your DreamFactory APIs from various programming languages:
JavaScript (Node.js)
const axios = require('axios');
const DREAMFACTORY_URL = 'https://your-app-name.klutch.sh/api/v2';const API_KEY = 'YOUR_API_KEY';const SERVICE_NAME = 'mysql_api';
// Configure axios instanceconst api = axios.create({ baseURL: DREAMFACTORY_URL, headers: { 'X-DreamFactory-API-Key': API_KEY, 'Content-Type': 'application/json' }});
// Get all usersasync function getUsers() { try { const response = await api.get(`/${SERVICE_NAME}/_table/users`); console.log('Users:', response.data); return response.data.resource; } catch (error) { console.error('Error fetching users:', error.response?.data || error.message); }}
// Create a new userasync function createUser(userData) { try { const response = await api.post(`/${SERVICE_NAME}/_table/users`, { resource: [userData] }); console.log('Created user:', response.data); return response.data; } catch (error) { console.error('Error creating user:', error.response?.data || error.message); }}
// Update userasync function updateUser(userId, updates) { try { const response = await api.put(`/${SERVICE_NAME}/_table/users/${userId}`, updates); console.log('Updated user:', response.data); return response.data; } catch (error) { console.error('Error updating user:', error.response?.data || error.message); }}
// Delete userasync function deleteUser(userId) { try { const response = await api.delete(`/${SERVICE_NAME}/_table/users/${userId}`); console.log('Deleted user:', response.data); return response.data; } catch (error) { console.error('Error deleting user:', error.response?.data || error.message); }}
// Example usage(async () => { await getUsers();
await createUser({ username: 'janedoe', email: 'jane@example.com', first_name: 'Jane', last_name: 'Doe' });})();Python
import requestsimport json
DREAMFACTORY_URL = 'https://your-app-name.klutch.sh/api/v2'API_KEY = 'YOUR_API_KEY'SERVICE_NAME = 'mysql_api'
headers = { 'X-DreamFactory-API-Key': API_KEY, 'Content-Type': 'application/json'}
# Get all usersdef get_users(): response = requests.get( f'{DREAMFACTORY_URL}/{SERVICE_NAME}/_table/users', headers=headers )
if response.status_code == 200: users = response.json()['resource'] print(f'Found {len(users)} users') return users else: print(f'Error: {response.status_code} - {response.text}') return []
# Create a new userdef create_user(user_data): payload = { 'resource': [user_data] }
response = requests.post( f'{DREAMFACTORY_URL}/{SERVICE_NAME}/_table/users', headers=headers, json=payload )
if response.status_code in [200, 201]: print('User created successfully') return response.json() else: print(f'Error creating user: {response.status_code} - {response.text}') return None
# Update userdef update_user(user_id, updates): response = requests.put( f'{DREAMFACTORY_URL}/{SERVICE_NAME}/_table/users/{user_id}', headers=headers, json=updates )
if response.status_code == 200: print(f'User {user_id} updated successfully') return response.json() else: print(f'Error updating user: {response.status_code} - {response.text}') return None
# Delete userdef delete_user(user_id): response = requests.delete( f'{DREAMFACTORY_URL}/{SERVICE_NAME}/_table/users/{user_id}', headers=headers )
if response.status_code == 200: print(f'User {user_id} deleted successfully') return True else: print(f'Error deleting user: {response.status_code} - {response.text}') return False
# Example usageif __name__ == '__main__': # Get all users users = get_users()
# Create new user new_user = create_user({ 'username': 'pythonuser', 'email': 'python@example.com', 'first_name': 'Python', 'last_name': 'Developer' })PHP
<?php
class DreamFactoryClient { private $baseUrl; private $apiKey; private $serviceName;
public function __construct($baseUrl, $apiKey, $serviceName) { $this->baseUrl = rtrim($baseUrl, '/'); $this->apiKey = $apiKey; $this->serviceName = $serviceName; }
private function request($method, $endpoint, $data = null) { $url = $this->baseUrl . '/' . ltrim($endpoint, '/');
$ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'X-DreamFactory-API-Key: ' . $this->apiKey, 'Content-Type: application/json' ]);
if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } elseif ($method === 'PUT') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } elseif ($method === 'DELETE') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); }
$response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
return [ 'status' => $httpCode, 'data' => json_decode($response, true) ]; }
public function getUsers() { return $this->request('GET', "/{$this->serviceName}/_table/users"); }
public function createUser($userData) { $payload = ['resource' => [$userData]]; return $this->request('POST', "/{$this->serviceName}/_table/users", $payload); }
public function updateUser($userId, $updates) { return $this->request('PUT', "/{$this->serviceName}/_table/users/{$userId}", $updates); }
public function deleteUser($userId) { return $this->request('DELETE', "/{$this->serviceName}/_table/users/{$userId}"); }}
// Usage example$df = new DreamFactoryClient( 'https://your-app-name.klutch.sh/api/v2', 'YOUR_API_KEY', 'mysql_api');
// Get all users$result = $df->getUsers();echo "Users: " . json_encode($result['data'], JSON_PRETTY_PRINT) . "\n";
// Create new user$newUser = $df->createUser([ 'username' => 'phpuser', 'email' => 'php@example.com', 'first_name' => 'PHP', 'last_name' => 'Developer']);echo "Created: " . json_encode($newUser['data'], JSON_PRETTY_PRINT) . "\n";
?>Go
package main
import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http")
const ( DreamFactoryURL = "https://your-app-name.klutch.sh/api/v2" APIKey = "YOUR_API_KEY" ServiceName = "mysql_api")
type User struct { ID int `json:"id,omitempty"` Username string `json:"username"` Email string `json:"email"` FirstName string `json:"first_name"` LastName string `json:"last_name"`}
type ResourceResponse struct { Resource []User `json:"resource"`}
type CreateRequest struct { Resource []User `json:"resource"`}
func makeRequest(method, endpoint string, body interface{}) (*http.Response, error) { var req *http.Request var err error
url := fmt.Sprintf("%s/%s", DreamFactoryURL, endpoint)
if body != nil { jsonData, _ := json.Marshal(body) req, err = http.NewRequest(method, url, bytes.NewBuffer(jsonData)) } else { req, err = http.NewRequest(method, url, nil) }
if err != nil { return nil, err }
req.Header.Set("X-DreamFactory-API-Key", APIKey) req.Header.Set("Content-Type", "application/json")
client := &http.Client{} return client.Do(req)}
func getUsers() ([]User, error) { resp, err := makeRequest("GET", fmt.Sprintf("%s/_table/users", ServiceName), nil) if err != nil { return nil, err } defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result ResourceResponse if err := json.Unmarshal(body, &result); err != nil { return nil, err }
return result.Resource, nil}
func createUser(user User) error { payload := CreateRequest{ Resource: []User{user}, }
resp, err := makeRequest("POST", fmt.Sprintf("%s/_table/users", ServiceName), payload) if err != nil { return err } defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 { fmt.Println("User created successfully") return nil }
body, _ := ioutil.ReadAll(resp.Body) return fmt.Errorf("error creating user: %s", string(body))}
func main() { // Get all users users, err := getUsers() if err != nil { fmt.Printf("Error fetching users: %v\n", err) return }
fmt.Printf("Found %d users\n", len(users)) for _, user := range users { fmt.Printf("- %s (%s)\n", user.Username, user.Email) }
// Create new user newUser := User{ Username: "gouser", Email: "go@example.com", FirstName: "Go", LastName: "Developer", }
if err := createUser(newUser); err != nil { fmt.Printf("Error creating user: %v\n", err) }}Advanced Features
Role-Based Access Control (RBAC)
DreamFactory includes powerful role-based access control to secure your APIs:
-
Create Roles
Navigate to Roles in the admin interface and create custom roles with specific permissions:
- Name: API Read Only
- Description: Read-only access to all database tables
- Active: ✓
-
Configure Service Access
For each role, configure access to services:
- Service: mysql_api
- Component: _table/*
- Access: GET (read-only)
- Filters: (optional SQL WHERE clause)
-
Assign Roles to Apps
When creating API keys, assign appropriate roles to limit access.
Server-Side Scripting
Add custom business logic to your APIs with server-side scripts:
-
Navigate to Scripts
Click Scripts in the left sidebar.
-
Create New Script
- Name: validate_user
- Type: Pre-Process (runs before API request)
- Service: mysql_api
- Endpoint: _table/users
- Active: ✓
-
Write Script Logic
Example JavaScript validation script:
// Validate user email formatif (event.request.method === 'POST' || event.request.method === 'PUT') {var users = event.request.payload.resource;users.forEach(function(user) {if (!user.email || !user.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {throw 'Invalid email format: ' + user.email;}// Add server timestampuser.updated_at = new Date().toISOString();});event.request.payload.resource = users;} -
Test Script
DreamFactory scripts execute automatically when API endpoints are called.
API Caching
Enable caching for improved performance:
-
Configure Redis Cache
Ensure Redis environment variables are set (see deployment steps).
-
Enable Cache for Service
When editing a service:
- Cache Enabled: ✓
- Cache TTL: 300 (seconds)
-
Cache Headers
DreamFactory automatically adds cache headers to responses:
X-DreamFactory-Cache: HITCache-Control: max-age=300
File Storage APIs
DreamFactory can expose file storage as REST APIs:
-
Create File Service
- Navigate to Services → Create
- Select File Storage → Local File Storage
- Name: files
- Container: storage (maps to
/opt/dreamfactory/storage/app)
-
Access File API
Terminal window # Upload filecurl -X POST https://your-app-name.klutch.sh/api/v2/files/documents/report.pdf \-H "X-DreamFactory-API-Key: YOUR_API_KEY" \--data-binary @report.pdf# Download filecurl https://your-app-name.klutch.sh/api/v2/files/documents/report.pdf \-H "X-DreamFactory-API-Key: YOUR_API_KEY" \-o downloaded-report.pdf# List filescurl https://your-app-name.klutch.sh/api/v2/files/documents \-H "X-DreamFactory-API-Key: YOUR_API_KEY"
Email Service Integration
Send emails through your APIs:
-
Create Email Service
- Navigate to Services → Create
- Select Email → SMTP
- Configure SMTP settings (use environment variables configured earlier)
-
Send Email via API
Terminal window curl -X POST https://your-app-name.klutch.sh/api/v2/email \-H "X-DreamFactory-API-Key: YOUR_API_KEY" \-H "Content-Type: application/json" \-d '{"to": [{"email": "user@example.com", "name": "User Name"}],"subject": "Welcome to DreamFactory","body_text": "Thank you for signing up!","from_email": "noreply@example.com","from_name": "DreamFactory"}'
Environment Variables Reference
Complete list of DreamFactory environment variables:
Core Application Settings
| Variable | Required | Description | Default |
|---|---|---|---|
APP_KEY | Yes | Laravel application key (base64 encoded) | None |
APP_ENV | No | Application environment | production |
APP_DEBUG | No | Enable debug mode | false |
APP_URL | No | Application URL | Auto-detected |
APP_LOCALE | No | Default locale | en |
APP_TIMEZONE | No | Application timezone | UTC |
Database Configuration
| Variable | Required | Description | Default |
|---|---|---|---|
DB_DRIVER | Yes | Database driver (mysql, pgsql, sqlsrv, sqlite) | mysql |
DB_HOST | Yes | Database hostname | localhost |
DB_PORT | Yes | Database port | 3306 |
DB_DATABASE | Yes | Database name | dreamfactory |
DB_USERNAME | Yes | Database username | root |
DB_PASSWORD | Yes | Database password | None |
Cache Configuration
| Variable | Required | Description | Default |
|---|---|---|---|
CACHE_DRIVER | No | Cache driver (file, redis, memcached) | file |
REDIS_CLIENT | No | Redis client (phpredis, predis) | phpredis |
REDIS_HOST | No | Redis hostname | localhost |
REDIS_PORT | No | Redis port | 6379 |
REDIS_PASSWORD | No | Redis password | None |
REDIS_DATABASE | No | Redis database number | 0 |
Email Configuration
| Variable | Required | Description | Default |
|---|---|---|---|
MAIL_MAILER | No | Mail driver (smtp, sendmail, mailgun, etc.) | smtp |
MAIL_HOST | No | SMTP server hostname | localhost |
MAIL_PORT | No | SMTP port | 587 |
MAIL_USERNAME | No | SMTP username | None |
MAIL_PASSWORD | No | SMTP password | None |
MAIL_ENCRYPTION | No | Encryption (tls, ssl) | tls |
MAIL_FROM_ADDRESS | No | Default from address | None |
MAIL_FROM_NAME | No | Default from name | DreamFactory |
Security Settings
| Variable | Required | Description | Default |
|---|---|---|---|
DF_JWT_TTL | No | JWT token lifetime (minutes) | 60 |
DF_JWT_REFRESH_TTL | No | JWT refresh token lifetime (minutes) | 20160 |
DF_ALLOW_FOREVER_SESSIONS | No | Allow permanent sessions | false |
DF_LOGIN_ATTRIBUTE | No | User login attribute (email, username) | email |
File Storage Settings
| Variable | Required | Description | Default |
|---|---|---|---|
DF_FILE_CHUNK_SIZE | No | File upload chunk size (bytes) | 10000000 |
DF_SCRIPTING_DISABLE | No | Disable server-side scripting | false |
Production Best Practices
Security Hardening
-
Strong Application Key
Always use a cryptographically secure random string for
APP_KEY:Terminal window openssl rand -base64 32 -
Disable Debug Mode
Ensure
APP_DEBUG=falsein production to prevent exposing sensitive information. -
Use Role-Based Access
Create specific roles with minimal required permissions instead of using “All Access” roles.
-
API Rate Limiting
Configure rate limiting in DreamFactory to prevent API abuse:
- Navigate to Config → Limits
- Set per-user and per-API-key limits
-
Enable HTTPS Only
Klutch.sh provides automatic HTTPS. Ensure all API calls use
https://URLs. -
Regular Security Updates
Keep DreamFactory up to date by regularly updating your Docker image version.
Performance Optimization
-
Use Redis for Caching
Redis dramatically improves performance for frequently accessed data:
Terminal window CACHE_DRIVER=redisREDIS_CLIENT=phpredis -
Enable API Response Caching
Configure service-level caching for read-heavy APIs:
- 5-30 seconds for frequently changing data
- 5-60 minutes for relatively static data
-
Optimize Database Queries
- Use filters to limit result sets
- Add database indexes for frequently queried columns
- Use related field syntax to minimize queries
-
Connection Pooling
Ensure your database supports connection pooling for better resource utilization.
-
Monitor Resource Usage
Track CPU, memory, and disk usage in the Klutch.sh dashboard. Scale vertically if needed.
Backup Strategy
Implement comprehensive backups:
-
Database Backups
Regular backups of the DreamFactory system database:
For MySQL:
Terminal window mysqldump -h your-mysql-app.klutch.sh -P 8000 \-u dreamfactory -p dreamfactory > dreamfactory-backup-$(date +%F).sqlFor PostgreSQL:
Terminal window pg_dump -h your-postgres-app.klutch.sh -p 8000 \-U dreamfactory dreamfactory > dreamfactory-backup-$(date +%F).sql -
File Storage Backups
Back up the persistent volume containing
/opt/dreamfactory/storage/app:- Scripts
- Uploaded files
- Custom configurations
-
Export API Configurations
Periodically export service and role configurations through the admin interface for version control.
-
Automated Backup Schedule
- Daily system database backups
- Weekly full storage backups
- Monthly archive backups
- Store backups in secure offsite location (S3, etc.)
Monitoring and Logging
-
Application Logs
View DreamFactory logs in
/opt/dreamfactory/storage/logs/dreamfactory.log:- API errors
- Authentication failures
- Script execution logs
-
API Usage Monitoring
Monitor through DreamFactory admin interface:
- Navigate to API Docs → Usage
- Track request counts, response times, error rates
-
Database Performance
Monitor database query performance:
- Slow query logs
- Connection counts
- Query execution times
-
Set Up Alerts
Configure alerts for:
- High error rates
- Slow API response times
- Authentication failures
- Resource exhaustion
Troubleshooting
Application Won’t Start
Symptoms: Container starts but DreamFactory web interface is not accessible
Solutions:
- Check logs in Klutch.sh dashboard for startup errors
- Verify environment variables are correctly set (especially
APP_KEY, database settings) - Ensure persistent volume is attached to
/opt/dreamfactory/storage/app - Check that HTTP traffic type is selected with internal port 80
- Verify database connectivity from the container
Database Connection Errors
Symptoms: “Database connection failed” errors in logs
Solutions:
-
Verify database credentials in environment variables
-
Check
DB_HOSTuses the correct Klutch.sh app URL -
Ensure
DB_PORTis set to8000for Klutch.sh TCP traffic -
Test database connection manually:
Terminal window mysql -h your-mysql-app.klutch.sh -P 8000 -u dreamfactory -p -
Check database server logs for connection attempts
Cannot Create APIs or Services
Symptoms: Errors when trying to create new services or APIs
Solutions:
- Verify system database migrations completed successfully
- Check application logs for detailed error messages
- Ensure persistent storage has sufficient space
- Verify
APP_KEYis correctly set and hasn’t changed - Try clearing application cache (may require container restart)
API Authentication Failures
Symptoms: 401 Unauthorized errors when calling APIs
Solutions:
- Verify API key is correctly included in
X-DreamFactory-API-Keyheader - Check that the app associated with the API key is active
- Ensure the role assigned to the app has permissions for the requested service
- Verify JWT token hasn’t expired (check
DF_JWT_TTLsetting) - Check for typos in API key
Slow API Performance
Symptoms: API requests taking longer than expected
Solutions:
- Enable Redis caching with
CACHE_DRIVER=redis - Configure service-level caching for read-heavy endpoints
- Check database query performance and add indexes
- Monitor resource usage and scale instance if needed
- Review server-side scripts for performance bottlenecks
- Reduce result set sizes using filters and pagination
Script Execution Errors
Symptoms: Server-side scripts failing or not executing
Solutions:
- Check script syntax in the DreamFactory script editor
- Review application logs for script error details
- Verify script is attached to correct service and endpoint
- Ensure script type (pre-process/post-process) is appropriate
- Check that
DF_SCRIPTING_DISABLEis not set totrue
File Upload Issues
Symptoms: Cannot upload files or file service returns errors
Solutions:
- Verify persistent volume is attached and has sufficient space
- Check file service configuration points to correct storage path
- Ensure API key has write permissions to file service
- Verify
DF_FILE_CHUNK_SIZEis appropriate for your files - Check web server upload limits (may need custom configuration)
Scaling DreamFactory
As your API usage grows, consider these scaling strategies:
Vertical Scaling
Increase resources for your DreamFactory instance:
- Upgrade to larger instance type in Klutch.sh dashboard
- Increase persistent volume size if storage is constrained
- Recommended specs:
- Small deployments (< 1000 req/day): 512MB RAM, 0.5 CPU
- Medium deployments (1000-10000 req/day): 1GB RAM, 1 CPU
- Large deployments (10000+ req/day): 2GB+ RAM, 2+ CPU
Horizontal Scaling
For high-traffic deployments:
-
Load Balancing
Deploy multiple DreamFactory instances behind a load balancer:
- Each instance connects to the same system database
- Share persistent storage via network file system or object storage
- Use Redis for shared cache and sessions
-
Database Optimization
- Use read replicas for read-heavy APIs
- Implement database connection pooling
- Consider managed database services with auto-scaling
-
CDN Integration
Use a CDN for:
- Static file APIs
- Cached API responses
- File download services
Migrating to DreamFactory
If you’re migrating from custom API code to DreamFactory:
Migration Strategy
-
Inventory Existing APIs
Document all existing API endpoints, methods, and parameters.
-
Connect Data Sources
Add all databases, file storage, and external services to DreamFactory.
-
Create Service APIs
For each data source, create a DreamFactory service with appropriate configuration.
-
Implement Business Logic
Port custom business logic to DreamFactory server-side scripts:
- Validation rules
- Data transformations
- Authorization checks
-
Set Up Security
Configure roles and API keys matching your existing access control requirements.
-
Test Thoroughly
Compare API responses between old and new implementations:
- Response format
- Status codes
- Error handling
- Performance
-
Gradual Cutover
Migrate applications one at a time:
- Update application to use DreamFactory APIs
- Monitor for issues
- Roll back if problems occur
- Proceed to next application
-
Decommission Old APIs
Once all applications are migrated and stable, decommission legacy API infrastructure.
Additional Resources
- Klutch.sh Dashboard
- DreamFactory Documentation
- DreamFactory GitHub Repository
- DreamFactory Community Forum
- Klutch.sh Persistent Volumes Guide
- Klutch.sh Networking Guide
- MySQL Deployment Guide
- PostgreSQL Deployment Guide
- Redis Deployment Guide
Conclusion
Deploying DreamFactory on Klutch.sh provides a powerful, scalable platform for instantly generating production-ready REST APIs from your data sources. By following this guide, you’ve set up a comprehensive API platform with automatic documentation, role-based security, persistent storage, and the flexibility to connect virtually any data source or external service.
Whether you’re building mobile apps, web applications, or microservices, DreamFactory eliminates the need to write repetitive API code, allowing you to focus on building features that matter. With proper configuration, security hardening, and performance optimization, your DreamFactory deployment on Klutch.sh is ready to power your applications with enterprise-grade API infrastructure.
Start connecting your data sources, create your first APIs, and accelerate your development workflow with DreamFactory’s automatic REST API generation today.