API & Developer Guides

How to Build a Python Script That Watches a Folder for New Design Files and Fires a Mockupanda API Request for Each One

By Mockupanda10 min read
How to Build a Python Script That Watches a Folder for New Design Files and Fires a Mockupanda API Request for Each One

If you manage a print-on-demand catalog of any real size, you already know the friction: finish a design, open your mockup tool, upload the file, pick a template, download the result, repeat. It eats hours. The fix is automation, and Python is a great tool for it.

This guide walks you through building a Python script that sits in the background, watches a folder on your machine or server, and the moment a new design file appears it sends that file to the Mockupanda API and saves the finished mockup images locally. No manual uploads, no browser tabs, no waiting around.

You don't need to be an experienced developer to follow along. If you can run a Python script from a terminal, you have everything you need.

What You'll Build and Why It Works

The script has two responsibilities: detect new files in a folder, and call the API when one appears. These are two separate problems with well-understood solutions in Python, and you can wire them together cleanly.

How File Watching Works in Python

Python's standard library includes a module called watchdog (installed via pip) that uses your operating system's native file-system events. When a file is created, modified, or moved into the watched folder, watchdog fires a callback function. That callback is where you put your API logic.

This is more reliable than polling (repeatedly checking the folder on a timer) because it reacts immediately and uses no CPU between events.

How the Mockupanda API Fits In

The Mockupanda API exposes a single endpoint for generating mockups: POST https://www.mockupanda.com/api/v1/mockups/generate. You send your artwork and one or more template IDs, and you get rendered mockup images back. You pay 1 credit per mockup generated, failed requests cost nothing, and credits never expire, so there's no risk in running this automatically.

The API supports batch mode, letting you send up to 12 template IDs in a single request using the template_ids parameter. That means one new file landing in your folder can trigger up to 12 finished mockups from a single call, which is exactly what this script relies on.

Takeaway: Before writing a line of code, understand that you're combining two things: a file-system event listener and an HTTP POST request. Keep them as two separate functions in your script and the whole thing becomes much easier to debug.

Getting Your API Key and Picking Templates

You need two things from Mockupanda before the script can run: an API key and the IDs of the templates you want to use.

Creating Your API Key

Log in to your Mockupanda dashboard, navigate to Dashboard, then API Keys, and click "Create API Key". Give the key a descriptive name like "Folder Watcher" or "Local Dev" so you can identify it later. Copy the key immediately, it starts with mpa_ and won't be shown again. Store it in an environment variable rather than hardcoding it in your script:

export MOCKUPANDA_API_KEY="mpa_your_key_here"

In your Python script, read it with os.environ.get("MOCKUPANDA_API_KEY"). This keeps your key out of version control if you ever share or commit the script.

Finding Template IDs

Browse templates in the Mockupanda editor or via the GET /templates endpoint. Each template has an ID string like bedroom-poster-01 or frame-wall-02. Decide which templates make sense for the types of files your folder will receive. For a wall art folder you might pick a handful of room scene templates. For apparel designs you'd pick product templates.

For this script, pick up to 12 template IDs and store them in a list at the top of your file. You can always change this list later without touching the rest of the script.

Takeaway: Create a dedicated API key for this script. If you ever need to revoke access or rotate credentials, you can do it without affecting other integrations.

Installing Dependencies and Setting Up the Project

This script uses three things beyond the Python standard library: watchdog for file watching, requests for HTTP calls, and python-dotenv optionally for loading environment variables from a .env file.

Project Structure

Create a folder for the project and set up a virtual environment:

mkdir mockup-watcher
cd mockup-watcher
python3 -m venv venv
source venv/bin/activate
pip install watchdog requests python-dotenv

Create two files inside the project folder:

  • watcher.py — the main script

  • .env — your API key and config (add this to .gitignore)

Your .env file:

MOCKUPANDA_API_KEY=mpa_your_key_here
WATCH_FOLDER=/Users/you/designs/incoming
OUTPUT_FOLDER=/Users/you/designs/mockups

Artwork Requirements to Keep in Mind

The API accepts JPEG, PNG, WebP, and GIF files (first frame only for GIFs). The maximum file size is 20 MB per artwork file, and files under 5 MB process faster. For best output quality, aim for 2000px or larger. Your folder watcher should skip any file that doesn't match these formats, which you'll see in the script below.

Takeaway: Use a virtual environment and a .env file from the start. It makes the script portable and keeps your credentials safe.

Writing the Full Watcher Script

Here is the complete script. Walk through it section by section so you understand what each part does.

The File Event Handler

import os
import time
import base64
import requests
from pathlib import Path
from dotenv import load_dotenv
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

load_dotenv()

API_KEY = os.environ.get("MOCKUPANDA_API_KEY")
WATCH_FOLDER = os.environ.get("WATCH_FOLDER", "./incoming")
OUTPUT_FOLDER = os.environ.get("OUTPUT_FOLDER", "./mockups")
API_URL = "https://www.mockupanda.com/api/v1/mockups/generate"

# Add or change these template IDs to match your use case
TEMPLATE_IDS = [
    "bedroom-poster-01",
    "frame-wall-02",
    "living-room-03",
]

SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}

def wait_for_file_ready(filepath, timeout=10):
    """Wait until a file stops growing (i.e., the write is complete)."""
    previous_size = -1
    elapsed = 0
    while elapsed < timeout:
        current_size = os.path.getsize(filepath)
        if current_size == previous_size and current_size > 0:
            return True
        previous_size = current_size
        time.sleep(0.5)
        elapsed += 0.5
    return False

class DesignFileHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.is_directory:
            return
        filepath = Path(event.src_path)
        if filepath.suffix.lower() not in SUPPORTED_EXTENSIONS:
            print(f"Skipping unsupported file type: {filepath.name}")
            return
        print(f"New file detected: {filepath.name}")
        if not wait_for_file_ready(str(filepath)):
            print(f"File {filepath.name} did not stabilize in time, skipping.")
            return
        generate_mockups(filepath)

The wait_for_file_ready function is important. When a large file is being copied into the watched folder, the OS fires the creation event before the file is fully written. Without this check, your API call might receive a truncated file. The function polls the file size every half second and waits until it stops growing.

The API Call Function

def generate_mockups(filepath):
    print(f"Sending {filepath.name} to Mockupanda API...")

    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }

    # Upload the file as multipart so we don't need a public URL
    with open(filepath, "rb") as f:
        response = requests.post(
            API_URL,
            headers={"Authorization": f"Bearer {API_KEY}"},
            files={"artwork": (filepath.name, f, "image/png")},
            data={
                "template_ids": ",".join(TEMPLATE_IDS),
                "response_format": "json",
            },
        )

    if response.status_code == 429:
        print("Rate limit hit. Waiting 60 seconds before retrying...")
        time.sleep(60)
        generate_mockups(filepath)
        return

    if not response.ok:
        print(f"API error {response.status_code}: {response.text}")
        return

    data = response.json()
    if not data.get("success"):
        print("API returned success=false. No credits charged.")
        return

    results = data.get("results", [])
    if not results:
        # Single template response
        results = [data]

    output_dir = Path(OUTPUT_FOLDER) / filepath.stem
    output_dir.mkdir(parents=True, exist_ok=True)

    for result in results:
        template_id = result.get("template_id", "mockup")
        image_data = base64.b64decode(result["image"])
        out_path = output_dir / f"{template_id}.jpg"
        with open(out_path, "wb") as out_file:
            out_file.write(image_data)
        print(f"Saved: {out_path}")

    print(f"Done. {len(results)} mockup(s) saved to {output_dir}")

A few things worth noting here. The script uploads the artwork file directly as a multipart form upload using the artwork parameter, so the file doesn't need to be hosted at a public URL. This is ideal for a local folder watcher. The response comes back as JSON with base64-encoded image data in each result's image field, which you decode and write to disk. Each design gets its own subfolder inside OUTPUT_FOLDER, named after the original file, so your output stays organized automatically.

The batch response format, with a results array, matches what the API returns when you use template_ids. The API returns a single-result JSON object instead of an array when you use template_id rather than template_ids, which is why there's a fallback that wraps it.

The Main Loop

def main():
    Path(WATCH_FOLDER).mkdir(parents=True, exist_ok=True)
    Path(OUTPUT_FOLDER).mkdir(parents=True, exist_ok=True)

    event_handler = DesignFileHandler()
    observer = Observer()
    observer.schedule(event_handler, str(WATCH_FOLDER), recursive=False)
    observer.start()
    print(f"Watching folder: {WATCH_FOLDER}")
    print("Press Ctrl+C to stop.")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    main()

Run it with python watcher.py. Drop a PNG or JPEG into your watch folder and watch the terminal. Within a couple of seconds the API request fires, and within a few more seconds your mockups appear in the output folder.

Takeaway: Keep the file handler and the API call as separate functions. If your API call grows more complex (adding retries, logging, notifications), you don't have to touch the file-watching logic at all.

Handling Rate Limits and Errors Gracefully

Running automation against an API means you need to think about what happens when things don't go perfectly. The Mockupanda API enforces rate limits of 100 requests per minute and 10,000 requests per day per API key. If you exceed the per-minute limit, the API returns a 429 Too Many Requests response.

Reading Rate Limit Headers

Every API response includes three headers you can use for smarter throttling:

  • X-RateLimit-Limit tells you the maximum allowed in the current window

  • X-RateLimit-Remaining tells you how many requests you have left

  • X-RateLimit-Reset gives you the Unix timestamp when the window resets

You can read these in Python with response.headers.get("X-RateLimit-Remaining") and log them or use them to decide whether to wait before the next request.

A Smarter Retry Approach

The simple retry in the script above waits a flat 60 seconds on a 429. For a more robust approach, read the X-RateLimit-Reset header and wait until that timestamp before retrying:

if response.status_code == 429:
    reset_timestamp = int(response.headers.get("X-RateLimit-Reset", time.time() + 60))
    wait_seconds = max(reset_timestamp - int(time.time()), 1)
    print(f"Rate limit hit. Waiting {wait_seconds}s before retrying.")
    time.sleep(wait_seconds)
    generate_mockups(filepath)
    return

If you're dropping many files at once, consider adding a short delay between processing each file. Because the script processes files one at a time as they arrive, this usually isn't a problem for normal use, but if you seed the folder with hundreds of files simultaneously, some throttling logic will keep you well within the per-minute limit.

Note that failed requests (network errors, invalid parameters, unsupported file types) don't consume credits, so there's no financial cost to errors. Only successfully generated mockups cost 1 credit each.

If you want to push the batch mode further, the batch mode guide covers exactly how to structure requests for 12 templates at once and handle the full response.

Takeaway: Always handle 429 responses explicitly and use the rate limit headers rather than guessing how long to wait. This keeps your script well-behaved even when you're processing a large batch of queued files.

Extending the Script for Real Workflows

The base script is useful on its own, but a few additions make it production-ready.

Avoiding Duplicate Processing

If a file is updated in place or copied twice, the on_created event might fire more than once. Keep a simple set of already-processed file paths in memory:

processed_files = set()

class DesignFileHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.src_path in processed_files:
            return
        processed_files.add(event.src_path)
        # ... rest of handler

For a persistent solution across script restarts, write processed paths to a small text file or SQLite database.

Moving Processed Files

After a successful API call, move the original design file to an archive subfolder rather than leaving it in the watch folder. This gives you a clean record of what has been processed and prevents reprocessing if you restart the script.

import shutil

archive_dir = Path(WATCH_FOLDER) / "archive"
archive_dir.mkdir(exist_ok=True)
shutil.move(str(filepath), archive_dir / filepath.name)

Running the Script as a Background Service

On macOS and Linux you can run the script persistently using a simple systemd service (Linux) or launchd plist (macOS), or just run it in a screen or tmux session on a server. This way it's always listening, even if you close your terminal.

If you're building this as part of a larger automation pipeline, the Sets feature via API is worth reading about. Instead of maintaining a list of template IDs in your script, you can save a named Set in Mockupanda and pass a single set_id to the API, making it easy to update your template list without touching your code.

Takeaway: Add duplicate-file protection and archiving from the start. These are small additions that prevent confusing bugs and make the script safe to run long-term.

Putting It All Together

By combining Python's watchdog library with the Mockupanda API, you've built a system that turns folder management into automated mockup generation. Drop a design file in, walk away, and come back to finished listing images organized by design name and template ID.

The full workflow is:

  1. Get your API key from Dashboard, then API Keys in your Mockupanda account

  2. Choose up to 12 template IDs to include in every request

  3. Install watchdog, requests, and python-dotenv

  4. Run watcher.py and point it at your incoming designs folder

  5. Drop any JPEG, PNG, WebP, or GIF file (up to 20 MB) into the folder

  6. Find your mockups in the output folder within a few seconds

From here you can extend the script to send mockups directly to Shopify, trigger a Slack notification, or log every generation to a spreadsheet. The API is straightforward enough that any of those additions are small tasks once the core loop is running.

If you eventually want the same kind of automation in JavaScript, the equivalent Node.js script approach covers pulling an entire Set via API in a single command, which pairs well with the folder watcher pattern described here.