Sub topic 14
Validating a feed before you submit it
A feed that fails inside the merchant account is slow to fix. You upload, wait for processing, read diagnostics, edit, and upload again. A local validation step catches most of those problems in seconds and keeps bad data away from shopping systems.
This chapter assumes you have read the earlier chapters on the product data model, identifiers, and price and availability. You should be comfortable running a short Python script and reading RSS XML with the g: namespace.
What validation can and cannot prove
Validation checks that your feed is well formed and follows the rules you can test without Google's systems. It does not prove the feed will be approved. Approval also depends on policies, on the landing page matching the feed, and on account-level settings. Treat local validation as a gate that removes avoidable errors, not as a substitute for diagnostics after submission.
Checks fall into four layers, ordered from cheapest to most expensive:
- File checks: the file parses, the encoding is correct, and each item is found.
- Item checks: required attributes are present and their values have the right format.
- Feed checks: rules that involve more than one item, such as duplicate IDs.
- Page checks: the feed agrees with the live landing page.
Fix problems at the source (your catalog or the export job), not in the generated file. Otherwise the next export brings the same errors back.
Layer 1 and 2: file and item checks
The script below covers layers 1 and 2. It reads an RSS feed and reports missing required attributes, malformed prices, unknown availability values, and GTINs with invalid check digits.
import re
import sys
import xml.etree.ElementTree as ET
NS = {"g": "http://base.google.com/ns/1.0"}
REQUIRED = ["id", "title", "description", "link", "image_link", "price", "availability"]
AVAILABILITY = {"in_stock", "out_of_stock", "preorder", "backorder"}
PRICE = re.compile(r"^\d+(\.\d{2})? [A-Z]{3}$")
def gtin_valid(value):
if not value.isdigit() or len(value) not in (8, 12, 13, 14):
return False
body, check = value[:-1], int(value[-1])
total = sum(int(d) * (3 if i % 2 == 0 else 1) for i, d in enumerate(reversed(body)))
return (10 - total % 10) % 10 == check
def check_item(item):
problems = []
values = {}
for tag in REQUIRED + ["gtin"]:
node = item.find("g:" + tag, NS)
values[tag] = node.text.strip() if node is not None and node.text else ""
for tag in REQUIRED:
if not values[tag]:
problems.append("missing " + tag)
if values["price"] and not PRICE.match(values["price"]):
problems.append("price should look like '89.00 USD'")
if values["availability"] and values["availability"] not in AVAILABILITY:
problems.append("unknown availability '" + values["availability"] + "'")
if values["gtin"] and not gtin_valid(values["gtin"]):
problems.append("GTIN check digit or length is invalid")
return problems
def main(path):
failed = 0
for item in ET.parse(path).getroot().iter("item"):
node = item.find("g:id", NS)
item_id = node.text.strip() if node is not None and node.text else "(no id)"
for problem in check_item(item):
failed += 1
print(item_id + ": " + problem)
print("problems found: " + str(failed))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))Run it with python check_feed.py feed.xml. It exits with status 1 when it finds problems, so a build or export job can stop on failure.
How the GTIN check works
A GTIN (Global Trade Item Number) ends in a check digit. To verify it, drop the last digit and read the rest from right to left. Multiply the digits alternately by 3 and 1, starting with 3. Sum the products. The check digit is whatever brings the sum up to the next multiple of 10. For 00012345678905 the sum is 85, so the check digit is 5, which matches.
A GTIN that fails this test is almost always a typo, a truncated value, or a leading zero lost in a spreadsheet. Spreadsheets are the most common cause. A 14-digit code saved as a number loses its leading zeros, and 12 or 13 digit codes can turn into scientific notation. If you export from a spreadsheet, store identifier columns as text.
What the item checks miss
The script is deliberately small. Know its limits:
- It confirms a GTIN is well formed, not that it belongs to your product. A valid number copied from another product still passes.
- The price pattern rejects thousands separators such as
1,299.00 USD. That is intentional: write1299.00 USD. - It does not check that
image_linkreturns an image, or thatlinkresolves. Those are layer 4 checks. - A malformed XML file makes
ET.parseraisexml.etree.ElementTree.ParseError. That is a useful failure, but you may want to catch it and print a clear message in a production pipeline. The usual cause is an unescaped&in a URL, which must be written&in XML.
Layer 3: checks across items
Some rules cannot be seen by looking at one item. The following script checks three of them: duplicate id values, a sale_price that is not lower than price, and variant attributes without an item_group_id.
import sys
import xml.etree.ElementTree as ET
from collections import Counter
NS = {"g": "http://base.google.com/ns/1.0"}
def text(item, tag):
node = item.find("g:" + tag, NS)
return node.text.strip() if node is not None and node.text else ""
def amount(value):
try:
return float(value.split()[0])
except (IndexError, ValueError):
return None
def main(path):
items = list(ET.parse(path).getroot().iter("item"))
problems = 0
counts = Counter(text(item, "id") for item in items)
for item_id, count in counts.items():
if count > 1:
problems += 1
print(item_id + ": id appears " + str(count) + " times")
for item in items:
item_id = text(item, "id") or "(no id)"
price = amount(text(item, "price"))
sale = amount(text(item, "sale_price"))
if price is not None and sale is not None and sale >= price:
problems += 1
print(item_id + ": sale_price is not lower than price")
has_variant_field = text(item, "color") or text(item, "size")
if has_variant_field and not text(item, "item_group_id"):
problems += 1
print(item_id + ": color or size set but item_group_id is missing")
print("problems found: " + str(problems))
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))Duplicate IDs matter because the ID is how a system recognizes the same item across updates. Two rows with one ID mean one of them is silently lost or overwritten. Many duplicates come from joining a product table to a variants table without grouping.
Layer 4: compare the feed with the page
The most damaging mismatches are between the feed and the landing page, where price, currency, and availability must agree. A script can fetch the link of each sampled item and compare it with the feed. Two approaches work:
- Read the JSON-LD block on the page and compare its
price,priceCurrency, andavailabilitywith the feed values. Remember to maphttps://schema.org/InStocktoin_stock. - Compare the visible price text, which also catches pages where the markup and the displayed price disagree.
Sample rather than fetch everything. A few hundred items per run, plus every item whose price changed since the last run, gives good coverage without hammering your own site. Respect your site's rate limits and caching, because a validation run that slows the store is a bad trade.
Making validation part of the workflow
- Run validation automatically after each feed export, before upload.
- Fail the job on layers 1 to 3. For layer 4, fail only above a threshold, for example more than 1% of sampled items mismatching, since a single page may be mid-update.
- Keep the last good feed. If validation fails, leave the previous file in place instead of uploading a broken one.
- Log counts per problem type over time. A sudden rise in "missing image_link" points to a change in the export, not 400 separate product errors.
- Add a test case for each problem you meet in diagnostics later. The validator should grow with your own failure history.
| Layer | Example problem | Cost to run | Typical cause |
|---|---|---|---|
| File | Unescaped `&` breaks parsing | Very low | Export template |
| Item | GTIN check digit invalid | Low | Spreadsheet formatting, typos |
| Feed | Duplicate `id` | Low | Bad join of variants |
| Page | Feed price differs from page | High | Stale feed, caching |
Exercise
A feed passes the item checks, but a product is later disapproved because its price differs from the landing page. Which validation layer would have caught this, and why did the item checks not?
Show answer
Layer 4, the comparison with the landing page. The item checks look only at the feed file, so they can confirm the price is well formed (for example 89.00 USD) but cannot know what the page shows. Catching the mismatch requires fetching the page and comparing its JSON-LD or visible price with the feed value.
Exercise
The GTIN 0012345678905 (13 digits) appears in the feed. Using the check-digit method from this chapter, is it valid? Show the sum.
Show answer
Drop the last digit to get 001234567890 and read it right to left: 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0. Apply weights 3, 1, 3, 1, and so on: 0, 9, 24, 7, 18, 5, 12, 3, 6, 1, 0, 0. The sum is 85. The check digit should be (10 - 5) % 10 = 5, which matches the last digit, so the GTIN is valid.