Skip to content

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.example

This 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 port
EXPOSE 80
# Health check for monitoring
HEALTHCHECK --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 image

Important 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 needed
RUN apt-get update && apt-get install -y \
php-redis \
php-mongodb \
&& rm -rf /var/lib/apt/lists/*
# Set working directory
WORKDIR /opt/dreamfactory
# Expose the application port
EXPOSE 80
# Health check for production monitoring
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
CMD curl -f http://localhost/api/v2/system/environment || exit 1
# Use default entrypoint and command

Version 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 dependencies
RUN 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 permissions
RUN chown -R www-data:www-data /opt/dreamfactory/storage
# Expose port
EXPOSE 80
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
CMD curl -f http://localhost/api/v2/system/environment || exit 1

Custom 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:

  1. Deploy MySQL or PostgreSQL: Follow the MySQL deployment guide or PostgreSQL deployment guide to create a database instance on Klutch.sh

  2. 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:

  1. Follow the Redis deployment guide to create a Redis instance
  2. Note the connection details for environment configuration

Deployment Steps

    1. Create Your Repository

      Create a new GitHub repository and add your Dockerfile:

      Terminal window
      mkdir dreamfactory-deployment
      cd dreamfactory-deployment
      # Create Dockerfile
      cat > Dockerfile << 'EOF'
      FROM dreamfactorysoftware/df-docker:4.11.0
      EXPOSE 80
      HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
      CMD curl -f http://localhost/api/v2/system/environment || exit 1
      EOF
      # Create .gitignore
      cat > .gitignore << 'EOF'
      .env
      .DS_Store
      *.log
      EOF
      # Create README
      cat > README.md << 'EOF'
      # DreamFactory on Klutch.sh
      Production-ready DreamFactory REST API platform deployment.
      ## Quick Start
      1. Deploy MySQL/PostgreSQL database
      2. Configure environment variables in Klutch.sh dashboard
      3. Deploy this repository
      4. Access DreamFactory at your assigned URL
      5. Complete initial setup wizard
      ## Documentation
      - DreamFactory Docs: https://wiki.dreamfactory.com/
      - Klutch.sh Docs: https://docs.klutch.sh/
      EOF
      # Initialize git and push
      git init
      git add .
      git commit -m "Initial DreamFactory deployment setup"
      git remote add origin https://github.com/YOUR_USERNAME/dreamfactory-deployment.git
      git push -u origin main
    2. Access the Klutch.sh Dashboard

      Navigate to klutch.sh/app and log in to your account.

    3. Create a New Project

      • Click “New Project” in the dashboard
      • Enter a project name (e.g., “API Platform”)
      • Select your preferred region for deployment
    4. Create a New Application

      • Within your project, click “New App”
      • Name your application (e.g., “DreamFactory”)
      • Connect your GitHub repository containing the Dockerfile
    5. 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.

    6. 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/app directory stores:

      • File storage service data
      • Server-side scripts
      • Package files
      • Cache files (if not using Redis)
      • Log files
    7. Configure Environment Variables

      In the app settings, add the following required environment variables:

      Database Configuration (MySQL example):

      Terminal window
      DB_DRIVER=mysql
      DB_HOST=your-mysql-app.klutch.sh
      DB_PORT=8000
      DB_DATABASE=dreamfactory
      DB_USERNAME=dreamfactory
      DB_PASSWORD=your-secure-password

      Database Configuration (PostgreSQL example):

      Terminal window
      DB_DRIVER=pgsql
      DB_HOST=your-postgres-app.klutch.sh
      DB_PORT=8000
      DB_DATABASE=dreamfactory
      DB_USERNAME=dreamfactory
      DB_PASSWORD=your-secure-password

      Application Configuration:

      Terminal window
      APP_KEY=base64:YOUR_32_CHAR_RANDOM_STRING_HERE
      APP_ENV=production
      APP_DEBUG=false
      APP_URL=https://your-app-name.klutch.sh

      Redis Configuration (Optional but Recommended):

      Terminal window
      CACHE_DRIVER=redis
      REDIS_CLIENT=phpredis
      REDIS_HOST=your-redis-app.klutch.sh
      REDIS_PORT=8000
      REDIS_PASSWORD=your-redis-password

      Email Configuration (Optional):

      Terminal window
      MAIL_MAILER=smtp
      MAIL_HOST=smtp.example.com
      MAIL_PORT=587
      MAIL_USERNAME=your-smtp-username
      MAIL_PASSWORD=your-smtp-password
      MAIL_ENCRYPTION=tls
      MAIL_FROM_ADDRESS=noreply@example.com
      MAIL_FROM_NAME=DreamFactory

      Generating APP_KEY:

      Generate a secure application key:

      Terminal window
      # Using openssl
      openssl rand -base64 32
      # Or using PHP (if available locally)
      php artisan key:generate --show

      Prefix 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.

    8. 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)
    9. 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
    10. 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

  1. Access Your DreamFactory Instance

    Navigate to https://your-app-name.klutch.sh in your browser.

  2. 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
  3. Review System Information

    DreamFactory displays system information including:

    • PHP version
    • Database connection status
    • Available services
    • Installed extensions
  4. 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

  1. Navigate to Services

    In the admin interface, click Services in the left sidebar.

  2. 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.)
  3. Configure Database Connection

    For a MySQL database deployed on Klutch.sh:

    Name: mysql_api
    Label: MySQL API
    Description: Production MySQL database API
    Active: ✓
    Connection:
    Host: your-mysql-app.klutch.sh
    Port: 8000
    Database: your_database
    Username: your_username
    Password: your_password
    Advanced:
    Connection String: (leave empty for standard connection)
    Additional Options: (optional JSON configuration)
  4. Test Connection

    Click “Test Connection” to verify DreamFactory can reach your database.

  5. 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 users
  • GET /api/v2/mysql_api/_table/users/1 - Get user by ID
  • POST /api/v2/mysql_api/_table/users - Create new user
  • PUT /api/v2/mysql_api/_table/users/1 - Update user
  • DELETE /api/v2/mysql_api/_table/users/1 - Delete user
  • GET /api/v2/mysql_api/_schema - Get database schema

Creating an API Key

To access your APIs, you need an API key:

  1. Navigate to Apps

    Click Apps in the left sidebar.

  2. 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”
  3. 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:

Terminal window
# List all users
curl https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users \
-H "X-DreamFactory-API-Key: YOUR_API_KEY"
# Create a new user
curl -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 ID
curl https://your-app-name.klutch.sh/api/v2/mysql_api/_table/users/1 \
-H "X-DreamFactory-API-Key: YOUR_API_KEY"
# Update user
curl -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 user
curl -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 instance
const api = axios.create({
baseURL: DREAMFACTORY_URL,
headers: {
'X-DreamFactory-API-Key': API_KEY,
'Content-Type': 'application/json'
}
});
// Get all users
async 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 user
async 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 user
async 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 user
async 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 requests
import 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 users
def 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 user
def 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 user
def 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 user
def 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 usage
if __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:

  1. 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: ✓
  2. Configure Service Access

    For each role, configure access to services:

    • Service: mysql_api
    • Component: _table/*
    • Access: GET (read-only)
    • Filters: (optional SQL WHERE clause)
  3. 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:

  1. Navigate to Scripts

    Click Scripts in the left sidebar.

  2. Create New Script

    • Name: validate_user
    • Type: Pre-Process (runs before API request)
    • Service: mysql_api
    • Endpoint: _table/users
    • Active: ✓
  3. Write Script Logic

    Example JavaScript validation script:

    // Validate user email format
    if (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 timestamp
    user.updated_at = new Date().toISOString();
    });
    event.request.payload.resource = users;
    }
  4. Test Script

    DreamFactory scripts execute automatically when API endpoints are called.

API Caching

Enable caching for improved performance:

  1. Configure Redis Cache

    Ensure Redis environment variables are set (see deployment steps).

  2. Enable Cache for Service

    When editing a service:

    • Cache Enabled: ✓
    • Cache TTL: 300 (seconds)
  3. Cache Headers

    DreamFactory automatically adds cache headers to responses:

    X-DreamFactory-Cache: HIT
    Cache-Control: max-age=300

File Storage APIs

DreamFactory can expose file storage as REST APIs:

  1. Create File Service

    • Navigate to ServicesCreate
    • Select File StorageLocal File Storage
    • Name: files
    • Container: storage (maps to /opt/dreamfactory/storage/app)
  2. Access File API

    Terminal window
    # Upload file
    curl -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 file
    curl 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 files
    curl 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:

  1. Create Email Service

    • Navigate to ServicesCreate
    • Select EmailSMTP
    • Configure SMTP settings (use environment variables configured earlier)
  2. 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

VariableRequiredDescriptionDefault
APP_KEYYesLaravel application key (base64 encoded)None
APP_ENVNoApplication environmentproduction
APP_DEBUGNoEnable debug modefalse
APP_URLNoApplication URLAuto-detected
APP_LOCALENoDefault localeen
APP_TIMEZONENoApplication timezoneUTC

Database Configuration

VariableRequiredDescriptionDefault
DB_DRIVERYesDatabase driver (mysql, pgsql, sqlsrv, sqlite)mysql
DB_HOSTYesDatabase hostnamelocalhost
DB_PORTYesDatabase port3306
DB_DATABASEYesDatabase namedreamfactory
DB_USERNAMEYesDatabase usernameroot
DB_PASSWORDYesDatabase passwordNone

Cache Configuration

VariableRequiredDescriptionDefault
CACHE_DRIVERNoCache driver (file, redis, memcached)file
REDIS_CLIENTNoRedis client (phpredis, predis)phpredis
REDIS_HOSTNoRedis hostnamelocalhost
REDIS_PORTNoRedis port6379
REDIS_PASSWORDNoRedis passwordNone
REDIS_DATABASENoRedis database number0

Email Configuration

VariableRequiredDescriptionDefault
MAIL_MAILERNoMail driver (smtp, sendmail, mailgun, etc.)smtp
MAIL_HOSTNoSMTP server hostnamelocalhost
MAIL_PORTNoSMTP port587
MAIL_USERNAMENoSMTP usernameNone
MAIL_PASSWORDNoSMTP passwordNone
MAIL_ENCRYPTIONNoEncryption (tls, ssl)tls
MAIL_FROM_ADDRESSNoDefault from addressNone
MAIL_FROM_NAMENoDefault from nameDreamFactory

Security Settings

VariableRequiredDescriptionDefault
DF_JWT_TTLNoJWT token lifetime (minutes)60
DF_JWT_REFRESH_TTLNoJWT refresh token lifetime (minutes)20160
DF_ALLOW_FOREVER_SESSIONSNoAllow permanent sessionsfalse
DF_LOGIN_ATTRIBUTENoUser login attribute (email, username)email

File Storage Settings

VariableRequiredDescriptionDefault
DF_FILE_CHUNK_SIZENoFile upload chunk size (bytes)10000000
DF_SCRIPTING_DISABLENoDisable server-side scriptingfalse

Production Best Practices

Security Hardening

  1. Strong Application Key

    Always use a cryptographically secure random string for APP_KEY:

    Terminal window
    openssl rand -base64 32
  2. Disable Debug Mode

    Ensure APP_DEBUG=false in production to prevent exposing sensitive information.

  3. Use Role-Based Access

    Create specific roles with minimal required permissions instead of using “All Access” roles.

  4. API Rate Limiting

    Configure rate limiting in DreamFactory to prevent API abuse:

    • Navigate to ConfigLimits
    • Set per-user and per-API-key limits
  5. Enable HTTPS Only

    Klutch.sh provides automatic HTTPS. Ensure all API calls use https:// URLs.

  6. Regular Security Updates

    Keep DreamFactory up to date by regularly updating your Docker image version.

Performance Optimization

  1. Use Redis for Caching

    Redis dramatically improves performance for frequently accessed data:

    Terminal window
    CACHE_DRIVER=redis
    REDIS_CLIENT=phpredis
  2. 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
  3. Optimize Database Queries

    • Use filters to limit result sets
    • Add database indexes for frequently queried columns
    • Use related field syntax to minimize queries
  4. Connection Pooling

    Ensure your database supports connection pooling for better resource utilization.

  5. Monitor Resource Usage

    Track CPU, memory, and disk usage in the Klutch.sh dashboard. Scale vertically if needed.

Backup Strategy

Implement comprehensive backups:

  1. 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).sql

    For PostgreSQL:

    Terminal window
    pg_dump -h your-postgres-app.klutch.sh -p 8000 \
    -U dreamfactory dreamfactory > dreamfactory-backup-$(date +%F).sql
  2. File Storage Backups

    Back up the persistent volume containing /opt/dreamfactory/storage/app:

    • Scripts
    • Uploaded files
    • Custom configurations
  3. Export API Configurations

    Periodically export service and role configurations through the admin interface for version control.

  4. 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

  1. Application Logs

    View DreamFactory logs in /opt/dreamfactory/storage/logs/dreamfactory.log:

    • API errors
    • Authentication failures
    • Script execution logs
  2. API Usage Monitoring

    Monitor through DreamFactory admin interface:

    • Navigate to API DocsUsage
    • Track request counts, response times, error rates
  3. Database Performance

    Monitor database query performance:

    • Slow query logs
    • Connection counts
    • Query execution times
  4. 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_HOST uses the correct Klutch.sh app URL

  • Ensure DB_PORT is set to 8000 for 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_KEY is 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-Key header
  • 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_TTL setting)
  • 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_DISABLE is not set to true

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_SIZE is 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:

  1. 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
  2. Database Optimization

    • Use read replicas for read-heavy APIs
    • Implement database connection pooling
    • Consider managed database services with auto-scaling
  3. 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

  1. Inventory Existing APIs

    Document all existing API endpoints, methods, and parameters.

  2. Connect Data Sources

    Add all databases, file storage, and external services to DreamFactory.

  3. Create Service APIs

    For each data source, create a DreamFactory service with appropriate configuration.

  4. Implement Business Logic

    Port custom business logic to DreamFactory server-side scripts:

    • Validation rules
    • Data transformations
    • Authorization checks
  5. Set Up Security

    Configure roles and API keys matching your existing access control requirements.

  6. Test Thoroughly

    Compare API responses between old and new implementations:

    • Response format
    • Status codes
    • Error handling
    • Performance
  7. 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
  8. Decommission Old APIs

    Once all applications are migrated and stable, decommission legacy API infrastructure.


Additional Resources


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.