Automating E-commerce Operations with n8n and Python — A Real-World Application

n8n is a powerful, low-code automation tool that’s rapidly gaining traction among businesses and developers. With more than 220 pre-built integrations and the ability to connect to anything with an API, n8n provides a way to automate tasks and streamline workflows. From simple, one-step integrations to complex, multi-step workflows, n8n enables you to connect your tools the way you need, integrating everything from CRM systems to payment platforms. It also allows for adding custom functions, logic, and apps. Thanks to its fair-code distribution model, n8n remains open-source, self-hostable, and has a free community edition for everyone to use.

When combined with Python, n8n becomes even more powerful. Python is widely used for its simplicity and flexibility, and it can be embedded directly into n8n workflows to handle more complex logic, data manipulation, or custom operations. In this article, we will explore how n8n and Python can work together to automate key processes for an online store, such as checking inventory, adjusting prices, and sending customer notifications.

Real-World Example: Automating Inventory Management, Price Adjustment, and Notifications

Let’s imagine you run a small online store that sells electronics. As your business grows, managing inventory levels, updating prices based on market trends, and keeping customers informed about stock availability can become overwhelming. You want to automate these tasks to save time and improve efficiency. Using n8n and Python, you can easily set up a system that automatically handles inventory checks, adjusts prices dynamically, and sends personalized email notifications to customers.

Here’s how you can build this automation workflow step-by-step using n8n and Python.

Step 1: Automatically Checking Product Inventory

Your first task is to automatically check the inventory levels of products in your store. Most e-commerce platforms provide APIs to interact with their backend systems. Using n8n’s HTTP Request node, you can set up a workflow that periodically pulls inventory data from your store’s API.

Here’s an example of how you would configure the HTTP Request node to get the inventory data from the API:

{
  "nodes": [
    {
      "parameters": {
        "requestMethod": "GET",
        "url": "https://api.yourstore.com/products",
        "responseFormat": "json"
      },
      "name": "Get Inventory",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1
    }
  ]
}

This node makes a GET request to your e-commerce platform’s API and retrieves a list of products and their stock levels.

Step 2: Processing Inventory Data with Python

Next, you want to filter out the products that have low stock (for example, less than 5 units) and trigger specific actions based on the results. Python can be used here to process the data received from the API. In n8n, you can add a Code node and write the following Python script to handle the inventory logic.

# Example incoming data from API
# {"products": [{"id": 1, "name": "Laptop", "stock": 3}, {"id": 2, "name": "Keyboard", "stock": 10}]}

low_stock_threshold = 5
low_stock_items = []

for product in items[0]["json"]["products"]:
    if product["stock"] < low_stock_threshold:
        low_stock_items.append({
            "id": product["id"],
            "name": product["name"],
            "stock": product["stock"]
        })

# Output the list of low-stock items
output = {
    "low_stock_items": low_stock_items
}

This Python code processes the API data, identifies products with stock levels below the defined threshold (e.g., 5 units), and creates a list of these low-stock items. You can use this filtered data for further actions in the workflow, such as sending alerts or reordering stock.

Step 3: Adjusting Prices Based on Market Trends

Dynamic pricing is a common practice in online retail to stay competitive. In this step, you can use n8n to gather pricing information from competitor websites using an external API. After fetching the market data, you can use Python to compare prices and adjust your store’s pricing accordingly.

Here’s an example of how you might configure an HTTP Request node to get competitor pricing data:

{
  "nodes": [
    {
      "parameters": {
        "requestMethod": "GET",
        "url": "https://api.competitorpricing.com/products",
        "responseFormat": "json"
      },
      "name": "Get Competitor Pricing",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1
    }
  ]
}

Once you have the competitor data, you can use another Python code node to adjust your prices dynamically:

# Example incoming data from API
# {"products": [{"id": 1, "name": "Laptop", "price": 1000, "competitor_price": 950}]}

price_adjustment_percentage = 0.05  # Reduce price by 5%
updated_prices = []

for product in items[0]["json"]["products"]:
    competitor_price = product["competitor_price"]
    new_price = competitor_price * (1 - price_adjustment_percentage)
    
    updated_prices.append({
        "id": product["id"],
        "name": product["name"],
        "new_price": round(new_price, 2)
    })

# Output the list of updated prices
output = {
    "updated_prices": updated_prices
}

This script takes the competitor prices and reduces your store’s prices by a set percentage (e.g., 5%). The updated prices are then returned and can be sent back to your e-commerce platform via an API to update the product listings.

Step 4: Sending Email Alerts to Customers When Products Are Back in Stock

The last step is notifying customers when an out-of-stock product becomes available again. For example, if customers sign up to be alerted when a specific product is restocked, you can use Python to check for restocks and automatically send them an email.

You can use another Python code node in n8n to identify customers who should be notified:

# Example incoming data: 
# {"low_stock_items": [{"id": 1, "name": "Laptop", "stock": 0}, {"id": 2, "name": "Keyboard", "stock": 3}], "subscribers": [{"product_id": 1, "email": "customer@example.com"}]}

subscribers_to_notify = []

for item in items[0]["json"]["low_stock_items"]:
    if item["stock"] > 0:  # Product is back in stock
        for subscriber in items[0]["json"]["subscribers"]:
            if subscriber["product_id"] == item["id"]:
                subscribers_to_notify.append({
                    "product_name": item["name"],
                    "email": subscriber["email"]
                })

# Output the list of subscribers to notify
output = {
    "subscribers_to_notify": subscribers_to_notify
}

This Python script checks if any products that were out of stock have been restocked. If so, it cross-references this data with a list of customers who subscribed to alerts for those products. The list of subscribers is then passed to an email node for sending notifications.

Here’s how you might configure an email node in n8n to send the notifications:

{
  "nodes": [
    {
      "parameters": {
        "toEmail": "={{ $json[\"email\"] }}",
        "subject": "Product Back in Stock!",
        "text": "The product {{ $json[\"product_name\"] }} is back in stock. Get it while supplies last!"
      },
      "name": "Send Email",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 1
    }
  ]
}

This email node sends an alert to each customer in the list, letting them know that the product they were interested in is available again.

Using n8n and Python together, you can automate critical processes for your online store and significantly reduce manual work. This real-world example demonstrates how you can:

  1. Automatically check inventory and handle low-stock products.
  2. Adjust prices dynamically based on competitor data.
  3. Notify customers when out-of-stock products are available again.

Thank you reading this article. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!

You can find the same tutorial on Medium.com.

Leave a Reply