Category: Builder's Corner
Personalized product recommendations are the backbone of modern ecommerce. With the rise of advanced AI workflow automation, building a tailored recommendation engine is no longer reserved for tech giants. In this tutorial, you'll learn—step by step—how to build a production-ready, automated, and AI-powered product recommendation system using Python, FastAPI, and workflow automation tools.
As we covered in our complete guide to AI workflow automation for ecommerce, personalization is a critical pillar for driving repeat purchases and customer loyalty. Here, we'll go deep on the technical implementation, so you can launch your own recommendation engine, integrate it into your stack, and automate the entire workflow from data collection to delivery.
Prerequisites
- Python 3.11+ (tested with 3.11 and 3.12)
- FastAPI 0.110+ (API server)
- scikit-learn 1.5+ (machine learning models)
- pandas 2.2+ (data wrangling)
- PostgreSQL 16+ (user/product data storage)
- Docker (for containerization, optional but recommended)
- Zapier, Make, or n8n (for workflow automation; we'll use n8n as an example)
- Basic knowledge of Python, REST APIs, and SQL
Table of Contents
- Set Up Your Development Environment
- Prepare and Ingest Ecommerce Data
- Build a Recommendation Model with scikit-learn
- Expose Recommendations via FastAPI
- Automate the Workflow With n8n
- Test the End-to-End System
- Common Issues & Troubleshooting
- Next Steps
1. Set Up Your Development Environment
-
Clone the Starter Repo (Optional)
You can start from scratch or use a minimal starter template:git clone https://github.com/yourorg/ecommerce-ai-recommendation-starter.git
-
Create and Activate a Python Virtual Environment
python3 -m venv .venv source .venv/bin/activate -
Install Required Python Packages
pip install fastapi[all] scikit-learn pandas asyncpg sqlalchemy uvicorn -
Set Up PostgreSQL Locally (Docker Recommended)
docker run --name pg-ai-recsys -e POSTGRES_PASSWORD=pgpassword -p 5432:5432 -d postgres:16Tip: Use
pgAdminorpsqlto connect and manage your database. -
Install and Start n8n (Workflow Automation)
docker run -it --rm \ --name n8n-ai-recsys \ -p 5678:5678 \ -e N8N_BASIC_AUTH_ACTIVE=true \ -e N8N_BASIC_AUTH_USER=admin \ -e N8N_BASIC_AUTH_PASSWORD=adminpass \ n8nio/n8nAccess the n8n dashboard at
http://localhost:5678.
Screenshot Description: Terminal window showing successful Docker container launches for PostgreSQL and n8n, with FastAPI server running locally.
2. Prepare and Ingest Ecommerce Data
-
Design Your Database Schema
-- users table CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- products table CREATE TABLE products ( id SERIAL PRIMARY KEY, name VARCHAR(255), category VARCHAR(100), price NUMERIC, metadata JSONB ); -- interactions table CREATE TABLE interactions ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), product_id INTEGER REFERENCES products(id), type VARCHAR(50), -- e.g., 'view', 'add_to_cart', 'purchase' timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP );Connect to your PostgreSQL instance and execute these commands.
-
Load Sample Data (Python Example)
import pandas as pd import sqlalchemy engine = sqlalchemy.create_engine("postgresql+psycopg2://postgres:pgpassword@localhost:5432/postgres") users = pd.DataFrame([ {"email": "alice@example.com", "name": "Alice"}, {"email": "bob@example.com", "name": "Bob"}, ]) users.to_sql("users", engine, if_exists="append", index=False) products = pd.DataFrame([ {"name": "Wireless Earbuds", "category": "Audio", "price": 79.99, "metadata": {"brand": "SoundPlus"}}, {"name": "Smart Watch", "category": "Wearables", "price": 129.99, "metadata": {"brand": "TimeX"}}, ]) products.to_sql("products", engine, if_exists="append", index=False)Tip: For real-world use, schedule regular imports via workflow automation (see Step 5).
-
Collect User-Product Interactions
Log events such as product views, cart additions, and purchases. You can do this by writing to the
interactionstable from your ecommerce site/app. For this tutorial, insert a few manual records:INSERT INTO interactions (user_id, product_id, type) VALUES (1, 1, 'view'), (1, 2, 'purchase'), (2, 1, 'add_to_cart');
Screenshot Description: pgAdmin browser showing users, products, and interactions tables populated with sample data.
3. Build a Recommendation Model with scikit-learn
-
Extract and Prepare Features
import pandas as pd from sqlalchemy import create_engine engine = create_engine("postgresql+psycopg2://postgres:pgpassword@localhost:5432/postgres") interactions = pd.read_sql("SELECT * FROM interactions", engine) user_product = pd.pivot_table( interactions, index="user_id", columns="product_id", values="type", aggfunc="count", fill_value=0 ) print(user_product) -
Train a Simple Collaborative Filtering Model
We'll use
NearestNeighborsfor a fast, content-based approach. For production, consider matrix factorization or neural models.from sklearn.neighbors import NearestNeighbors import numpy as np user_product_matrix = user_product.values model = NearestNeighbors(metric='cosine', algorithm='brute') model.fit(user_product_matrix) def recommend_products(user_idx, n=3): distances, indices = model.kneighbors([user_product_matrix[user_idx]], n_neighbors=n+1) # Skip the first neighbor (it's the user itself) recommended_users = indices[0][1:] # Find products those users interacted with, but the original user did not user_products = set(np.where(user_product_matrix[user_idx] > 0)[0]) recs = set() for neighbor in recommended_users: neighbor_products = set(np.where(user_product_matrix[neighbor] > 0)[0]) recs.update(neighbor_products - user_products) return list(recs) print(recommend_products(0))For a deeper dive into AI-powered ecommerce tools, see our hands-on review of the best AI tools for ecommerce workflow automation in 2026.
-
Persist the Model (Optional)
import joblib joblib.dump(model, 'recommender.pkl')
Screenshot Description: Jupyter notebook displaying the user-product matrix and recommendation output for a sample user.
4. Expose Recommendations via FastAPI
-
Create a FastAPI App
from fastapi import FastAPI, HTTPException import joblib import pandas as pd from sqlalchemy import create_engine app = FastAPI() engine = create_engine("postgresql+psycopg2://postgres:pgpassword@localhost:5432/postgres") model = joblib.load('recommender.pkl') @app.get("/recommend/{user_id}") def get_recommendations(user_id: int): interactions = pd.read_sql("SELECT * FROM interactions", engine) user_product = pd.pivot_table( interactions, index="user_id", columns="product_id", values="type", aggfunc="count", fill_value=0 ) if user_id not in user_product.index: raise HTTPException(status_code=404, detail="User not found") user_idx = list(user_product.index).index(user_id) rec_indices = recommend_products(user_idx) # Map indices back to product IDs product_ids = list(user_product.columns) rec_product_ids = [product_ids[i] for i in rec_indices] # Fetch product details query = f"SELECT * FROM products WHERE id IN ({','.join(map(str, rec_product_ids))})" rec_products = pd.read_sql(query, engine).to_dict(orient='records') return {"recommendations": rec_products} -
Run the API Server
uvicorn main:app --reload --port 8000Test your endpoint:
curl http://localhost:8000/recommend/1
Screenshot Description: Browser window showing JSON API response with personalized product recommendations for user 1.
5. Automate the Workflow With n8n
-
Access the n8n Dashboard
Open
http://localhost:5678and log in with your credentials. -
Create a New Workflow
- Add a "Schedule" trigger to run your workflow daily or in real-time.
- Add a "HTTP Request" node to call your FastAPI
/recommend/{user_id}endpoint for each user. - Add an "Email" or "Webhook" node to deliver personalized recommendations (e.g., via SendGrid, Mailgun, or Slack).
Example HTTP Request Node:
Method: GET URL: http://host.docker.internal:8000/recommend/1 -
Optional: Log Recommendation Deliveries
Add another "PostgreSQL" node to log when recommendations are sent, for analytics and A/B testing.
Screenshot Description: n8n workflow canvas with connected nodes: Schedule → HTTP Request → Email.
To see how AI workflows automate other ecommerce operations, check out our AI workflow playbook for real-time inventory updates.
6. Test the End-to-End System
-
Trigger the n8n Workflow
Click "Execute Workflow" in n8n. Confirm that:
- The HTTP Request node receives a valid JSON with recommendations.
- The Email/Webhook node delivers the recommendations to the intended recipient.
-
Check Logs and API Responses
tail -f n8n.log curl http://localhost:8000/recommend/1 -
Validate Recommendations
Review the recommendations for accuracy and relevance. Tweak your model or data as needed.
Screenshot Description: Email client with a personalized product recommendation email, showing product images, titles, and links.
Common Issues & Troubleshooting
-
Database Connection Errors: Double-check your
engineURI and Docker network settings. For Dockerized FastAPI, usehost.docker.internalto connect to your local PostgreSQL. -
Model Not Updating With New Data: Schedule regular model retraining via n8n or a cron job. Use
joblib.dumpafter each retraining. -
n8n HTTP Request Fails: Ensure FastAPI is accessible from the n8n container. Use
host.docker.internalas the API host if both run in Docker. - Cold Start Latency: For large models, load them once at FastAPI startup, not per request.
- Data Drift or Cold Start Problem: For new users/products, fall back to popularity-based or category-based recommendations.
- Security: Never expose your FastAPI endpoint without authentication in production. Use API keys or OAuth.
Next Steps
- Scale to Production: Containerize your stack with Docker Compose or Kubernetes for high availability.
- Enhance Recommendation Models: Experiment with deep learning, hybrid models, or real-time personalization.
- Integrate With More Channels: Extend workflows to SMS, in-app notifications, or personalized landing pages.
- Monitor and A/B Test: Use logging and analytics to measure impact and iterate.
- Go Deeper: For a broader perspective on AI workflow automation in ecommerce—including cart recovery and fulfillment—see The Complete 2026 Guide to AI Workflow Automation for Ecommerce.
- Explore More Use Cases: See how AI workflow automation powers legal discovery and financial compliance checks in 2026.
Ready to build smarter ecommerce experiences? Start automating your personalized recommendation workflows today and stay ahead in 2026.