Automate Your E-commerce: Sync Products from Google Sheets to WooCommerce with Python & APIs

Petyo Eremiev
20.08.2025

Introduction

Managing a WooCommerce store with hundreds of products can be a daunting task. Manually adding, updating, and tracking each item is time-consuming, repetitive, and prone to errors. What if you could manage your entire product catalog from a simple Google Sheet and have it automatically sync with your online store?

In this comprehensive guide, we'll build a powerful automation script using Python that does exactly that. We will connect to the Google Sheets API to read product data and use the WooCommerce REST API to create or update products in your store. By the end, you'll have a fully functional tool that can save you hours of manual work. Let's get started!

Prerequisites

Before we write any code, make sure you have the following:

  • WooCommerce store with admin access.
  • Google account.
  • Python 3 installed on your machine.
  • A code editor like VS Code.
  • Basic understanding of Python and how APIs work.

Part 1: Setting Up the WooCommerce API

First, we need to tell WooCommerce to allow our script to make changes. We do this by generating API keys.

  1. Log in to your WordPress admin dashboard.
  2. Navigate to WooCommerce > Settings > Advanced > REST API.
  3. Click "Add key".
  4. Give your key a Description (e.g., "Google Sheets Sync"), choose your user, and set Permissions to "Read/Write".
  5. Click "Generate API key".

Important: WooCommerce will show you a Consumer Key and a Consumer Secret. Copy and save these somewhere safe immediately. You will not be able to see the secret again!

Part 2: Setting Up the Google Sheets API

This is the most involved setup process, so follow carefully.

  1. Create a Google Cloud Platform Project: Go to the Google Cloud Console and create a new project.
  2. Enable the APIs: In your new project, go to the "APIs & Services" dashboard. Click "+ ENABLE APIS AND SERVICES", search for "Google Drive API" and "Google Sheets API", and enable both.
  3. Create Service Account Credentials:
    • Go to "Credentials" and click "+ CREATE CREDENTIALS" -> "Service account".
    • Give it a name (e.g., "woocommerce-sheet-manager") and click "Create and Continue".
    • Grant it the "Editor" role for now, then click "Done".
  4. Generate a JSON Key:
    • Find the service account you just created in the list of credentials.
    • Click on it, go to the "KEYS" tab, click "ADD KEY" -> "Create new key".
    • Choose JSON as the type and click "Create". A .json file will be downloaded. Treat this file like a password! Save it in your project directory.
  5. Share Your Google Sheet:
    • Open the .json file you downloaded. Inside, you'll find a client_email address (e.g., ...gserviceaccount.com). Copy it.
    • Create a new Google Sheet and click the "Share" button.
    • Paste the client_email into the sharing dialog and give it "Editor" permissions.

Part 3: Preparing Your Google Sheet

Create a sheet with clear column headers. For this example, we'll use:

skunametyperegular_pricedescriptionimage_url
TSHIRT-001Cool T-Shirtsimple19.99A very cool shirt.https://.../image.jpg
HOODIE-002Warm Hoodiesimple39.99A very warm hoodie.https://.../image2.jpg

Експортиране в Таблици

The header names should match the fields in the WooCommerce API for simplicity. The SKU is crucial for checking if a product already exists.

Part 4: The Python Script

Now for the fun part! Create a new folder for your project, place your Google API .json key file inside, and create a file named sync_products.py.

Step 1: Install Libraries Open your terminal and install the necessary Python packages:

Bash

pip install gspread oauth2client woocommerce

Step 2: Write the Code Paste the following code into sync_products.py. Be sure to fill in the placeholder variables at the top.

Python

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from woocommerce import API

# --- CONFIGURATION ---
# WooCommerce API credentials
WC_STORE_URL = "https://your-store.com"
WC_CONSUMER_KEY = "ck_xxxxxxxxxxxx"
WC_CONSUMER_SECRET = "cs_xxxxxxxxxxxx"

# Google Sheets API credentials
GOOGLE_SHEET_NAME = "Your Google Sheet Name" # The name of your spreadsheet
GOOGLE_API_JSON_FILE = "your-credentials-file.json" # The path to your downloaded JSON key

# --- INITIALIZE APIS ---
def connect_to_woocommerce():
    """Initializes and returns the WooCommerce API client."""
    wcapi = API(
        url=WC_STORE_URL,
        consumer_key=WC_CONSUMER_KEY,
        consumer_secret=WC_CONSUMER_SECRET,
        version="wc/v3"
    )
    return wcapi

def connect_to_google_sheets():
    """Initializes and returns the Google Sheets client."""
    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
    creds = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_API_JSON_FILE, scope)
    client = gspread.authorize(creds)
    sheet = client.open(GOOGLE_SHEET_NAME).sheet1  # Get the first sheet
    return sheet.get_all_records() # Returns a list of dictionaries

# --- MAIN LOGIC ---
def sync_products():
    """Main function to sync products from Google Sheets to WooCommerce."""
    print("Connecting to APIs...")
    wcapi = connect_to_woocommerce()
    products_from_sheet = connect_to_google_sheets()
    
    print(f"Found {len(products_from_sheet)} products in the Google Sheet.")

    for product in products_from_sheet:
        sku = product.get('sku')
        if not sku:
            print(f"Skipping product with no SKU: {product.get('name')}")
            continue

        print(f"Processing product with SKU: {sku}...")

        # Prepare product data for WooCommerce API
        data = {
            "name": product.get('name'),
            "type": product.get('type', 'simple'),
            "sku": sku,
            "regular_price": str(product.get('regular_price', '0')),
            "description": product.get('description', ''),
            "images": [
                {
                    "src": product.get('image_url')
                }
            ] if product.get('image_url') else []
        }

        # Check if product with this SKU already exists
        response = wcapi.get("products", params={"sku": sku})
        existing_products = response.json()

        if existing_products:
            # Update existing product
            product_id = existing_products[0]['id']
            print(f"Product exists (ID: {product_id}). Updating...")
            wcapi.put(f"products/{product_id}", data)
        else:
            # Create new product
            print("Product does not exist. Creating...")
            wcapi.post("products", data)

    print("Synchronization complete!")

# --- RUN SCRIPT ---
if __name__ == "__main__":
    sync_products()

Running the Script & Verifying the Results

  1. Fill in your details in the CONFIGURATION section of the script.
  2. Open your terminal in the project directory.
  3. Run the script:Bashpython sync_products.py

You should see output in your terminal as the script processes each row. After it's done, go to the Products section in your WooCommerce dashboard. Your new products should be there!

Next Steps & Improvements

This script is a fantastic starting point. Here’s how you could make it even better:

  • Error Handling: Add try...except blocks to handle network issues or API errors gracefully.
  • Scheduling: Use a cron job (on Linux/Mac) or Task Scheduler (on Windows) to run the script automatically every day.
  • Syncing Stock: Add an "stock_quantity" column to your sheet and sync inventory levels.
  • Variable Products: Extend the logic to handle product variations (e.g., different sizes or colors).

Conclusion

You have successfully bridged the gap between a simple spreadsheet and a powerful e-commerce platform. By leveraging the APIs of Google Sheets and WooCommerce, you've created a scalable and efficient workflow for managing your products. This automation not only saves time but also ensures data consistency across your platforms. Happy automating!

Leave a Reply

Your email address will not be published. Required fields are marked *

By Data Source
By Category

woocommerceOpenCart_logo.svgShopify_logo_2018.svgMagento logoWebhooks 3
KPI dashboards - BOOST your PROFIT with Thinkclicks

Copyright © 2025 ThinkClicks.biz

Privacy Policy
About ThinkClicks
A sophisticated software that helps agency owners, advertisers and e-commerce businesses to make data-informed decisions,save time in analyzing and have more profit.

linkedin iconfacebook icontwitter icon
KPI dashboards - BOOST your PROFIT with Thinkclicks
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.