Working with price lists in Google Sheets: automation via API
-
Galina Ostrachinyna
Copywriter Elbuz
Google Sheets has become a popular tool for price list management due to its cloud-based nature and automation capabilities. Using the Google Sheets API and Apps Script, you can create a full-fledged pricing management system with automatic syncing to your website.
Benefits of Google Sheets for Pricing
Google Sheets offers unique features for working with price lists:
Cloud access
Manage your price lists from anywhere in the world without installing any special software. All changes are saved automatically and available in real time.
Free API
The Google Sheets API is free with a limit of 300 requests per minute per project, which is sufficient for most small and medium businesses.
Apps Script
The built-in development environment allows you to create automation scripts without additional servers. The code is executed on Google's side.
Integrations
Connect hundreds of services via Zapier, Make (Integromat), or create your own integrations via API.
Google Sheets API: Connection
To start working with the API, you need to complete several steps:
Step 1: Create a project in the Google Cloud Console
- Go to console.cloud.google.com
- Create a new project or select an existing one
- Enable Google Sheets API under "APIs & Services"
- Create credentials (OAuth 2.0 or Service Account)
Step 2: Installing the client library
For Python:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlibExample of reading data from a table (Python)
from google.oauth2 import service_account from googleapiclient.discovery import build # Authorization via Service Account SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] SERVICE_ACCOUNT_FILE = 'credentials.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) service = build('sheets', 'v4', credentials=credentials) # Table ID from URL SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Price!A2:E' # Read data sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) if not values: print('Data not found.') else: for row in values: # Process each price line product_code = row[0] product_name = row[1] price = row[2] stock = row[3] print(f'{product_code}: {product_name} - {price} rub. ({stock} pcs.)')Example of writing data (Python)
# Use scopes with edit permissions to write SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] # Prepare data values = [ ['SKU123', 'Item 1', 1500, 100], ['SKU124', 'Item 2', 2500, 50], ['SKU125', 'Item 3', 3500, 25] ] body ={ 'values': values } # Write data result = service.spreadsheets().values().update( spreadsheetId=SPREADSHEET_ID, range='Price!A2:D4', valueInputOption='RAW', body=body).execute() print(f'{result.get("updatedCells")} cells updated.')Apps Script for automation
Google Apps Script is a JavaScript framework built into Google Sheets that lets you automate tasks without external servers.
Automatic price updates on a schedule
function updatePricesFromAPI() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Price'); // URL of your API with prices var url = 'https://api.example.com/prices'; try { var response = UrlFetchApp.fetch(url, { 'method': 'get', 'headers':{ 'Authorization': 'Bearer YOUR_API_TOKEN' } }); var data = JSON.parse(response.getContentText()); // Clearing old data (starting from the 2nd row) var lastRow = sheet.getLastRow(); if (lastRow > 1) { sheet.getRange(2, 1, lastRow - 1, sheet.getLastColumn()).clearContent(); } // Write new data var row = 2; data.products.forEach(function(product) { sheet.getRange(row, 1).setValue(product.sku); sheet.getRange(row, 2).setValue(product.name); sheet.getRange(row, 3).setValue(product.price); sheet.getRange(row, 4).setValue(product.stock); sheet.getRange(row, 5).setValue(new Date()); row++; }); Logger.log('Price successfully updated: ' + (row - 2) + ' products'); } catch (e){ Logger.log('Ошибка обновления: ' + e.toString()); // Отправка уведомления на email MailApp.sendEmail( 'manager@example.com', 'Ошибка обновления прайса', 'Не удалось обновить прайс. Ошибка: ' + e.toString() ); } } // Function for setting up a trigger function setupTrigger() { // Delete old triggers var triggers = ScriptApp.getProjectTriggers(); triggers.forEach(function(trigger) { if (trigger.getHandlerFunction() === 'updatePricesFromAPI') { ScriptApp.deleteTrigger(trigger); } }); // Create a new trigger (every hour) ScriptApp.newTrigger('updatePricesFromAPI').timeBased().everyHours(1).create(); }Data validation upon input
function onEdit(e) { var sheet = e.source.getActiveSheet(); var range = e.range; // Check only the "Price" sheet if (sheet.getName()!== 'Price') return; // Check the price column (column 3) if (range.getColumn() === 3) { var value = range.getValue(); // Check for a number if (isNaN(value) || value< 0) { SpreadsheetApp.getUi().alert('Ошибка: цена должна быть положительным числом'); range.setValue(''); // Очищаем неверное значение return; } // Автоматический расчет цены с наценкой var markup = 1.3; // 30% наценка var retailPrice = value * markup; sheet.getRange(range.getRow(), 6).setValue(retailPrice.toFixed(2)); } // Проверка столбца с остатками (столбец 4) if (range.getColumn() === 4) { var stock = range.getValue(); if (isNaN(stock) || stock < 0 || stock % 1!== 0) { SpreadsheetApp.getUi().alert('Ошибка: остаток должен быть целым положительным числом'); range.setValue(''); return; } // Цветовая индикация остатков if (stock === 0) { range.setBackground('#ffcccc'); // Красный - нет на складе } else if (stock < 10) { range.setBackground('#fff3cd'); // Желтый - мало } else { range.setBackground('#d4edda'); // Зеленый - достаточно } } }Synchronization with the site
There are several ways to sync price lists from Google Sheets with your website:
Method 1: Direct reading via API (JavaScript)
// On the frontend of the site async function loadPricesFromSheet() { const SHEET_ID = 'YOUR_SHEET_ID'; const API_KEY = 'YOUR_API_KEY'; const RANGE = 'Price!A2:E'; const url = `https://sheets.googleapis.com/v4/spreadsheets/${SHEET_ID}/values/${RANGE}?key=${API_KEY}`; try { const response = await fetch(url); const data = await response.json(); const products = data.values.map(row => ({ sku: row[0], name: row[1], price: parseFloat(row[2]), stock: parseInt(row[3]), updated: row[4] } )); displayProducts(products); } catch (error){ console.error('Ошибка загрузки прайса:', error); } } function displayProducts(products) { const container = document.getElementById('products-container'); products.forEach(product => { const productHTML = ` ${product.name}
Item number: ${product.sku}
${product.price.toFixed(2)} rub.
In stock: ${product.stock} pcs.
`; container.innerHTML += productHTML; }); }Method 2: Webhook from Apps Script
// Apps Script: Sending data to the website when changing function onEdit(e) { sendUpdateToWebsite(); } function sendUpdateToWebsite() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Price'); var data = sheet.getDataRange().getValues(); // Skipping the header var products = []; for (var i = 1; i< data.length; i++) { products.push({ sku: data[i][0], name: data[i][1], price: data[i][2], stock: data[i][3] }); } var payload = { products: products, timestamp: new Date().toISOString() }; var options = { method: 'post', contentType: 'application/json', payload: JSON.stringify(payload), headers: { 'X-API-Key': 'YOUR_WEBSITE_API_KEY' } }; try { var response = UrlFetchApp.fetch('https://your-website.com/api/update-prices', options); Logger.log('Данные отправлены: ' + response.getResponseCode()); } catch (e) { Logger.log('Ошибка отправки: ' + e.toString()); } }Method 3: Export to CSV via Web App
// Apps Script: publish CSV endpoint function doGet(e) { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Price'); var data = sheet.getDataRange().getValues(); // Checking the API key if (e.parameter.key!== 'YOUR_SECRET_KEY') { return ContentService.createTextOutput('Unauthorized').setMimeType(ContentService.MimeType.TEXT); } // Generate CSV var csv = ''; data.forEach(function(row) { csv += row.join(',') + '\n'; }); return ContentService.createTextOutput(csv).setMimeType(ContentService.MimeType.CSV).downloadAsFile('price_list.csv'); }Formulas and data validation
Google Sheets offers powerful formulas to automate price list calculations:
Useful formulas for price lists
| Task | Formula | Description |
|---|---|---|
| Markup | =B2*1.3 | Price calculation with a 30% markup |
| VAT | =B2*1.2 | Adding VAT 20% |
| Discount | =B2*(1-C2/100) | Applying the discount from column C |
| Currency conversion | =B2*GOOGLEFINANCE("CURRENCY:USDEUR") | Automatic conversion at the exchange rate |
| Conditional formatting | =IF(D2<10,"Мало","В наличии") | Status by balance |
| VLOOKUP for categories | =VLOOKUP(A2,Categories!A:B,2,FALSE) | Pulling up a category by article |
| Total cost | =B2*D2 | Price × quantity |
Setting up data validation
Validation helps prevent data entry errors:
- Number range: For prices, set the minimum to 0, but the maximum can be unlimited.
- List of values: For categories, statuses, units of measurement
- Regular expressions: To check the format of the article numbers (for example, SKU-\d{5})
- Custom formula: For complex conditions (for example, =AND(B2>0, B2<1000000))
Conditional formatting for visualization
// Apps Script: Setting up conditional formatting function setupConditionalFormatting() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Price'); var range = sheet.getRange('D2:D1000'); // Column with remainders var rules = sheet.getConditionalFormatRules(); // Red: remainder = 0 var rule1 = SpreadsheetApp.newConditionalFormatRule().whenNumberEqualTo(0).setBackground('#f4cccc').setRanges([range]).build(); // Yellow: remainder< 10 var rule2 = SpreadsheetApp.newConditionalFormatRule().whenNumberLessThan(10).setBackground('#fff2cc').setRanges([range]).build(); // Зеленый: остаток > = 10 var rule3 = SpreadsheetApp.newConditionalFormatRule().whenNumberGreaterThanOrEqualTo(10).setBackground('#d9ead3').setRanges([range]).build(); rules.push(rule1, rule2, rule3); sheet.setConditionalFormatRules(rules); }Teamwork
Google Sheets is ideal for team collaboration with price lists:
Access levels
- View: Employees can only read data
- Commenting: Ability to leave comments without changing data
- Editing: Full access to price changes
- Protected ranges: Certain columns are only accessible to the owner
Change history
Google Sheets automatically tracks all changes:
- View history via File → Version History
- Restoring previous versions
- Tracking who made changes and when
Change notifications
// Apps Script: Notify the team about changes function notifyTeamOnPriceChange(e) { var sheet = e.source.getActiveSheet(); var range = e.range; // Track only the price column if (sheet.getName()!== 'Price' || range.getColumn()!== 3) return; var row = range.getRow(); var sku = sheet.getRange(row, 1).getValue(); var productName = sheet.getRange(row, 2).getValue(); var oldPrice = e.oldValue; var newPrice = e.value; var user = e.user.getEmail(); var message = ` Price change in the price list Product: ${productName} (${sku}) Old price: ${oldPrice} rubles New price: ${newPrice} rubles Changed by: ${user} Time: ${new Date().toLocaleString('ru-RU')} `; // Sending to Telegram sendToTelegram(message); // Sending to email var recipients = 'sales@example.com, manager@example.com'; MailApp.sendEmail(recipients, 'Price change in price list', message); } function sendToTelegram(message) { var token = 'YOUR_BOT_TOKEN'; var chatId = 'YOUR_CHAT_ID'; var url = `https://api.telegram.org/bot${token}/sendMessage`; var payload ={ chat_id: chatId, text: message }; UrlFetchApp.fetch(url,{ method: 'post', contentType: 'application/json', payload: JSON.stringify(payload) } ); }Comments and discussions
Use the built-in comment system to discuss controversial positions:
- @mentioning colleagues to attract attention
- Resolving comments after the issue is resolved
- Assigning tasks via comments
Limitations and alternatives
Despite its many advantages, Google Sheets has certain limitations:
Technical limitations
| Parameter | Limit | Solution |
|---|---|---|
| Maximum cells | 10 million cells | Split into multiple files |
| Maximum lines | There is no fixed limit | Limited by the total number of cells |
| API requests | 300/minute per project | Caching, batch requests |
| Apps Script time | 6 minutes (free) | Code optimization, breaking into parts |
| File size | There is no hard limit | Performance drops after 100k lines |
When to consider alternatives
- More than 50,000 products: Consider databases (PostgreSQL, MySQL) or specialized systems
- High update rate: If the price list is updated more than once a minute, it is better to use a database
- Complex business logic: For multi-level markups and complex calculations, an ERP system is suitable
- Critical speed: Google Sheets is not suitable for real-time systems.
Recommended alternatives
Airtable
More powerful database capabilities with an intuitive interface. Better suited for complex table relationships.
Microsoft Excel Online
An alternative with integration into the Microsoft 365 ecosystem. Power Query for advanced data processing.
Specialized PIM systems
For large businesses with thousands of SKUs, Product Information Management systems are suitable.
Elbuz
A ready-made solution for automating price list management, supporting import from Google Sheets and automatic synchronization with your website. Learn more about automatic price list processing.
Conclusion
Google Sheets with API and Apps Script is a powerful and accessible tool for managing price lists. Key benefits:
- Free: Most features are available free of charge.
- Ease of implementation: No complex infrastructure required
- Flexibility: Can be adapted to any business processes
- Integrations: Easy to connect to your website, CRM, 1C
- Teamwork: Convenient collaboration with access control
For small and medium-sized businesses with catalogs of up to 10,000-20,000 products, Google Sheets is the optimal solution. As data volumes grow or business logic becomes more complex, you can gradually migrate to more advanced platforms.
Related materials
Data management and price synchronization
A Complete Guide to Importing, Exporting, and Syncing Price Lists
Popular price list formats
Overview of CSV, XML, JSON, and Excel data exchange formats
Automatic synchronization of prices and balances
Setting up automatic data updates on the website from price lists
ElbuzAutomatic price list processing
A ready-made solution for automating work with price lists
Automate your price list management
Use the Google Sheets API to automatically sync price lists with your website, or try the ready-made Elbuz solution for full automation.
Save a link to this article
Galina Ostrachinyna
Copywriter ElbuzThe secrets of online store automation are revealed here, like the pages of a magic book of a successful business. Welcome to my world, where every idea is the key to online effectiveness!
Discussion of the topic – Working with price lists in Google Sheets: automation via API
Working with price lists in Google Sheets: automation via API
There are no reviews for this product.


Write a comment
Your email address will not be published. Required fields are checked *