How to Use the Taobao API to Build a Product Price Tracker and Alert System
Introduction
In the world of e-commerce, price tracking and change notifications are highly valuable features. Whether you're helping users compare prices, determine the best time to buy, or build promotional alert systems, the Taobao API provides a reliable source of product data to support these use cases.
This article will guide you through:
Using
taobao.item.get
to fetch real-time product pricesDesigning a basic price tracking system
Storing and comparing historical prices
Implementing a notification mechanism (Email, LINE Notify, Webhook, etc.)
Demonstrating implementations in Python and Node.js
1. What Is Price Tracking?
Price tracking refers to the automatic and periodic monitoring of a product's price, followed by a notification if it changes. This functionality is widely used in:
Price comparison websites and apps
Affiliate marketing platforms
Smart shopping tools
Sales alert systems
Here’s a typical process flow:
[ Scheduler / Cron Job ]↓
[ Price Fetching API (taobao.item.get) ]
↓
[ Compare with Last Known Price ]
↓
[ If Changed → Send Notification ]
↓
[ Update Local Price Record ]
2. Using taobao.item.get
to Fetch Product Prices
The taobao.item.get
API provides real-time data for a given product ID, including price, title, image URL, and seller info.
Common Parameters
Parameter | Description |
---|---|
| Always |
| Product ID (numeric) |
| Comma-separated list of fields to return (e.g., |
Example API Response
{"item_get_response": {
"item": {
"title": "Wireless Sports Earbuds",
"price": "89.00",
"pic_url": "https://image.taobao.com/img/abc.jpg",
"num_iid": 321654987123,
"seller_id": "seller_abc"
}
}
}
This response includes the product's title, price, and image URL, among other information.
3. Python Example: Price Tracker Script
Here’s a basic Python script that tracks product prices and sends an alert if a change is detected.
Step 1: Basic Setup and Signature Generation
import requestsimport hashlib
import time
import json
import os
API_URL = 'https://api.taobao.com/endpoint'
API_KEY = 'YOUR_API_KEY'
API_SECRET = 'YOUR_API_SECRET'
DATA_FILE = 'price_log.json'
This sets up the API key, secret, and the local file path used to store price history.
def generate_signature(params):sorted_keys = sorted(params.keys())
base = API_SECRET + ''.join(f"{k}{params[k]}" for k in sorted_keys) + API_SECRET
return hashlib.md5(base.encode()).hexdigest().upper()
This function generates the MD5 signature required by the API using a sorted list of parameters.
Step 2: Fetch the Current Price from the API
def get_price(num_iid):params = {
'method': 'taobao.item.get',
'api_key': API_KEY,
'num_iid': num_iid,
'fields': 'title,price',
'timestamp': int(time.time())
}
params['signature'] = generate_signature(params)
response = requests.get(API_URL, params=params)
return response.json()['item_get_response']['item']
This function calls the API to get the product's title and price based on the provided ID.
Step 3: Load and Save Price History
def load_price_history():if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f:
return json.load(f)
return {}
def save_price_history(data):
with open(DATA_FILE, 'w') as f:
json.dump(data, f)
These functions handle loading and saving price history in a local JSON file for comparison.
Step 4: Compare Prices and Send Notification
def notify(title, old_price, new_price):print(f"[Alert] '{title}' price changed: NT${old_price} → NT${new_price}")
This function simulates a notification; in production, it can be replaced with email, LINE Notify, etc.
def track_price(num_iid):data = load_price_history()
item = get_price(num_iid)
title = item['title']
current_price = float(item['price'])
prev_price = float(data.get(str(num_iid), {}).get('price', current_price))
if current_price != prev_price:
notify(title, prev_price, current_price)
data[str(num_iid)] = {'title': title, 'price': current_price}
save_price_history(data)
This is the core logic: fetch the current price, compare it to the previous value, notify if it changed, and update the record.
4. Node.js Example: Cron Job + Webhook Notification
Here’s how to implement the same concept using Node.js with node-cron
to run checks every 10 minutes.
Setup and Signature Generator
const axios = require('axios');const crypto = require('crypto');
const fs = require('fs');
const cron = require('node-cron');
const API_KEY = 'YOUR_API_KEY';
const API_SECRET = 'YOUR_API_SECRET';
const API_URL = 'https://api.taobao.com/endpoint';
const ITEM_ID = '321654987123';
const PRICE_FILE = './price_record.json';
function generateSignature(params) {
const sortedKeys = Object.keys(params).sort();
let base = API_SECRET;
sortedKeys.forEach(k => { base += k + params[k]; });
base += API_SECRET;
return crypto.createHash('md5').update(base).digest('hex').toUpperCase();
}
Fetching Price and Reading Record
async function getPrice(numIid) {const params = {
method: 'taobao.item.get',
api_key: API_KEY,
num_iid: numIid,
fields: 'title,price',
timestamp: Math.floor(Date.now() / 1000)
};
params.signature = generateSignature(params);
const { data } = await axios.get(API_URL, { params });
return data.item_get_response.item;
}
function loadHistory() {
if (fs.existsSync(PRICE_FILE)) {
return JSON.parse(fs.readFileSync(PRICE_FILE));
}
return {};
}
function saveHistory(record) {
fs.writeFileSync(PRICE_FILE, JSON.stringify(record));
}
Webhook Notification + Scheduler
function sendWebhook(title, oldPrice, newPrice) {axios.post('https://your-webhook-url.com', {
text: `[Price Alert] "${title}" dropped from NT$${oldPrice} to NT$${newPrice}!`
});
}
cron.schedule('*/10 * * * *', async () => {
const record = loadHistory();
const item = await getPrice(ITEM_ID);
const current = parseFloat(item.price);
const previous = parseFloat(record.price || current);
if (current !== previous) {
sendWebhook(item.title, previous, current);
saveHistory({ title: item.title, price: current });
console.log(`Price change detected: ${previous} → ${current}`);
} else {
console.log('No change.');
}
});
Runs every 10 minutes
Sends a webhook notification if the price has changed
Updates the stored price record
5. Suggestions for Improvement and Expansion
Feature | Description |
---|---|
Track multiple products | Use a list or array and loop through each item ID |
Modular notification system | Support email, SMS, push notifications, etc. |
Web dashboard | Let users add products and set target prices |
Price drop-only alerts | Notify only when price drops (not increases) |
Use a database | Replace JSON with MongoDB or SQLite for scalability |
Conclusion
This article demonstrated how to build a simple yet powerful product price tracker using the Taobao API. From fetching product prices to notifying users of price changes, we covered the full stack of features needed for such a system.
Articles related to APIs :
Introduction to Taobao API: Basic Concepts and Application Scenarios
Taobao API: Authentication & Request Flow Explained with Code Examples
Using the Taobao API to Retrieve Product Information and Implement Keyword Search
If you need the Taobao API, feel free to contact us : support@luckdata.com