Skip to main content

Google Sheets Product Catalog API

gsheets is not available in flAPI v26.11.25

The gsheets community extension, which this recipe used to rely on, is not published for DuckDB 2.0.1, the DuckDB version flAPI has embedded since v26.11.23. INSTALL gsheets FROM community fails with HTTP 404, and because a failing init stops startup, a config that installs it does not start.

This recipe therefore reads the sheet's CSV export over HTTPS, which works today for sheets that may be read by anyone with the link. The Google Sheets guide has the details and the gsheets setup for when the extension is published again.

Build a product catalog API backed by Google Sheets, for teams where non-technical staff manage product data without touching code or databases.

Use Case​

Scenario: A growing e-commerce company needs a product catalog API, but:

  • Marketing team updates product descriptions daily
  • Pricing changes multiple times per week
  • Developers are focused on core features
  • No time to build an admin panel

Solution: Use Google Sheets as the "database" that marketing edits directly, with flAPI providing the REST API layer on a local cache of the sheet.

Architecture​

Benefits:

  • ✅ Marketing updates products without a developer
  • ✅ No admin panel to build or maintain
  • ✅ Version history built in (Google Sheets)
  • ✅ Requests are served from a local cache, not from Google

Trade-off: a change in the sheet shows up in the API after the next cache refresh (here every 10 minutes).

Step 1: Create the Spreadsheet​

Products tab​

skunamedescriptionpricecategoryin_stockimage_urlcreated_date
SKU-001Wireless MouseErgonomic wireless mouse with 3 buttons29.99ElectronicsTRUEhttps://...2024-01-15
SKU-002Laptop StandAdjustable aluminum laptop stand49.99AccessoriesTRUEhttps://...2024-01-16
SKU-003USB-C Cable6ft USB-C to USB-C cable12.99CablesFALSEhttps://...2024-01-17
SKU-004Desk LampLED desk lamp with touch control39.99FurnitureTRUEhttps://...2024-01-18
SKU-005KeyboardMechanical keyboard with RGB89.99ElectronicsTRUEhttps://...2024-01-19

Categories tab​

category_idcategory_namedescription
CAT-001ElectronicsElectronic devices and gadgets
CAT-002AccessoriesComputer and desk accessories
CAT-003CablesCharging and data cables
CAT-004FurnitureOffice furniture and ergonomics

Share settings and export URLs​

  1. Click Share → General access → "Anyone with the link" → Viewer. The export URL works only for a sheet shared this way, so put nothing in it that may not be public.
  2. Copy the spreadsheet ID from the address bar: https://docs.google.com/spreadsheets/d/<SPREADSHEET_ID>/edit.
  3. Open each tab and note the number after gid= in the address bar.

Each tab is then available as CSV at:

https://docs.google.com/spreadsheets/d/<SPREADSHEET_ID>/export?format=csv&gid=<SHEET_GID>

Check both with curl -L '<url>' before you go on. The URL and its behaviour are Google's, and this recipe has not been tested against a live sheet.

Step 2: Configure flAPI​

httpfs, which reads files over HTTPS, is in flAPI's default extension set, so no init: is needed. The cache lives in DuckLake:

flapi.yaml
project-name: sheets-product-catalog
project-description: Product catalog API backed by Google Sheets

template:
path: './sqls'

connections:
product-sheets:
properties:
products_url: 'https://docs.google.com/spreadsheets/d/1A2B3C4D5E6F7G8H9I0J/export?format=csv&gid=0'
categories_url: 'https://docs.google.com/spreadsheets/d/1A2B3C4D5E6F7G8H9I0J/export?format=csv&gid=123456789'

ducklake:
enabled: true
alias: cache
metadata-path: ./cache.ducklake
data-path: ./cache_data

In templates, {{{ conn.products_url }}} uses triple braces: double braces would HTML-escape the & in the URL.

Step 3: Create API Endpoints​

Every endpoint serves from its own cache table. A cache refresh downloads the tab once per schedule; requests read the local copy and never trigger a download.

Endpoint 1: List all products​

The populate template rebuilds the table from the whole sheet on each refresh. That is the right mode for a sheet: the export has no reliable "changed since" column, and a few thousand rows rebuild in a moment. A populate template must write the table itself; a bare SELECT is refused.

sqls/products_cache.sql
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
SELECT
sku,
name,
description,
CAST(price AS DOUBLE) AS price,
category,
CAST(in_stock AS BOOLEAN) AS in_stock,
image_url,
CAST(created_date AS DATE) AS created_date
FROM read_csv('{{{ conn.products_url }}}', header = true, all_varchar = true)

all_varchar = true reads every cell as text, so one stray text cell in the price column does not break the import; the casts then say what each column is.

sqls/products.sql
SELECT sku, name, description, price, category, in_stock, image_url, created_date
FROM {{cache.catalog}}.{{cache.schema}}.{{cache.table}}
WHERE 1=1
{{#params.category}}
AND lower(category) = lower('{{{ params.category }}}')
{{/params.category}}
{{#params.in_stock}}
AND in_stock = {{{ params.in_stock }}}
{{/params.in_stock}}
{{#params.min_price}}
AND price >= {{{ params.min_price }}}
{{/params.min_price}}
{{#params.max_price}}
AND price <= {{{ params.max_price }}}
{{/params.max_price}}
{{#params.search}}
AND (lower(name) LIKE lower('%{{{ params.search }}}%')
OR lower(description) LIKE lower('%{{{ params.search }}}%'))
{{/params.search}}
ORDER BY
{{#params.sort_by}}
CASE WHEN '{{{ params.sort_by }}}' = 'price_asc' THEN price END ASC,
CASE WHEN '{{{ params.sort_by }}}' = 'price_desc' THEN price END DESC,
CASE WHEN '{{{ params.sort_by }}}' = 'name' THEN name END ASC,
{{/params.sort_by}}
created_date DESC

No LIMIT: GET endpoints are paginated by default, and ?limit=/?offset= are reserved for the pagination. Clients page with ?limit=20&offset=40.

sqls/products.yaml
url-path: /products/
template-source: products.sql
connection:
- product-sheets

cache:
enabled: true
table: products_cache
schedule: 10m # download the sheet every 10 minutes
template-file: products_cache.sql

request:
- field-name: category
field-in: query
description: Filter by category name
required: false
validators:
- type: string
max-length: 50
regex: '^[A-Za-z &-]+$'

- field-name: in_stock
field-in: query
description: Filter by stock status ("true" or "false")
required: false
validators:
- type: enum
allowedValues: ["true", "false"]

- field-name: min_price
field-in: query
description: Minimum price
required: false
validators:
- type: number
min: 0

- field-name: max_price
field-in: query
description: Maximum price
required: false
validators:
- type: number
min: 0

- field-name: search
field-in: query
description: Search in name and description
required: false
validators:
- type: string
max-length: 100
regex: '^[A-Za-z0-9 -]+$'

- field-name: sort_by
field-in: query
description: Sort order
required: false
validators:
- type: enum
allowedValues: [price_asc, price_desc, name, date]

The validators are what keep request values in shape: an enum for the fixed choices, numbers for prices, and a strict pattern for free text.

Endpoint 2: Single product​

sqls/product_detail.sql
SELECT sku, name, description, price, category, in_stock, image_url, created_date
FROM {{cache.catalog}}.{{cache.schema}}.{{cache.table}}
WHERE sku = '{{{ params.sku }}}'
sqls/product_detail.yaml
url-path: /products/:sku/
template-source: product_detail.sql
connection:
- product-sheets

cache:
enabled: true
table: product_detail_cache
schedule: 10m
template-file: products_cache.sql # same populate SQL, its own table

request:
- field-name: sku
field-in: path
description: Product SKU
required: true
validators:
- type: string
regex: '^SKU-[0-9]{3}$'

Endpoint 3: Categories with product counts​

One populate template reads both tabs and stores the summary, so a request is a plain read:

sqls/categories_cache.sql
CREATE OR REPLACE TABLE {{cache.catalog}}.{{cache.schema}}.{{cache.table}} AS
WITH products AS (
SELECT category,
CAST(price AS DOUBLE) AS price,
CAST(in_stock AS BOOLEAN) AS in_stock
FROM read_csv('{{{ conn.products_url }}}', header = true, all_varchar = true)
),
category_products AS (
SELECT category,
count(*) AS product_count,
count(*) FILTER (WHERE in_stock) AS in_stock_count,
round(avg(price), 2) AS avg_price,
min(price) AS min_price,
max(price) AS max_price
FROM products
GROUP BY category
)
SELECT c.category_id,
c.category_name,
c.description,
coalesce(cp.product_count, 0) AS product_count,
coalesce(cp.in_stock_count, 0) AS in_stock_count,
cp.avg_price,
cp.min_price,
cp.max_price
FROM read_csv('{{{ conn.categories_url }}}', header = true, all_varchar = true) c
LEFT JOIN category_products cp ON c.category_name = cp.category
sqls/categories.sql
SELECT *
FROM {{cache.catalog}}.{{cache.schema}}.{{cache.table}}
ORDER BY category_name
sqls/categories.yaml
url-path: /categories/
template-source: categories.sql
connection:
- product-sheets

cache:
enabled: true
table: categories_cache
schedule: 30m
template-file: categories_cache.sql
Pick the right refresh mode

flAPI infers the refresh mode from the cache block: full refresh (no cursor, no primary key: rebuild the whole table, as here), incremental append (cursor only) and incremental merge (cursor and primary key). A sheet export has no trustworthy change column, so full refresh fits. See Caching Strategy for the others.

Step 4: Deploy & Test​

Start flAPI​

The flapii commands below talk to flAPI's config service, which is off unless you start it with a token:

export FLAPI_CONFIG_SERVICE_TOKEN=$(openssl rand -hex 16)
flapi -c flapi.yaml --host 127.0.0.1 --config-service

flapi reads the token from FLAPI_CONFIG_SERVICE_TOKEN (or --config-service-token), and so does flapii: export the same value in the terminal where you run it. The config service is an admin interface, so keep it on loopback.

Or with Docker, mounting the project directory (no config service here; refresh with flapi cache refresh instead, see below):

docker run --rm -p 8080:8080 -v "$(pwd)":/config \
ghcr.io/datazoode/flapi:latest -c /config/flapi.yaml

The caches are built when the server starts. An endpoint whose first build failed (for example, a sheet that is not shared) answers 503 {"error":"cache_build_failed"}; the server log names the cause.

Test the APIs​

# All products, first page
curl 'http://localhost:8080/products/?limit=20'

# Filter by category
curl 'http://localhost:8080/products/?category=Electronics'

# Search products
curl 'http://localhost:8080/products/?search=wireless'

# Price range + in stock
curl 'http://localhost:8080/products/?min_price=20&max_price=50&in_stock=true'

# Single product
curl http://localhost:8080/products/SKU-001/

# Categories with counts
curl http://localhost:8080/categories/

# Pull the sheet now instead of waiting for the schedule
# (needs the config service and FLAPI_CONFIG_SERVICE_TOKEN, as started above)
flapii cache refresh /products/

Without the config service, flapi cache refresh -c flapi.yaml --all refreshes every cache once and exits. It is meant for a writer job; run it where it can reach the same DuckLake files.

Sample Response​

{
"data": [
{
"sku": "SKU-001",
"name": "Wireless Mouse",
"description": "Ergonomic wireless mouse with 3 buttons",
"price": 29.99,
"category": "Electronics",
"in_stock": true,
"image_url": "https://example.com/images/mouse.jpg",
"created_date": "2024-01-15"
}
],
"next": "",
"total_count": 1
}

Step 5: Integration with Website​

JavaScript Example​

// Fetch products for a product listing page
async function loadProducts(category = null, inStock = true) {
const params = new URLSearchParams();
if (category) params.append('category', category);
if (inStock) params.append('in_stock', 'true');
params.append('limit', '20'); // page size

const response = await fetch(
`https://api.yoursite.com/products/?${params}`
);
const body = await response.json();

return body.data; // body.next is the URL of the next page, "" on the last
}

loadProducts('Electronics', true).then(products => {
products.forEach(product => {
console.log(`${product.name} - $${product.price}`);
});
});

React Hook Example​

import { useState, useEffect } from 'react';

function useProducts(category, inStock) {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
const params = new URLSearchParams();
if (category) params.append('category', category);
params.append('in_stock', inStock.toString());

fetch(`https://api.yoursite.com/products/?${params}`)
.then(res => res.json())
.then(body => {
setProducts(body.data);
setLoading(false);
});
}, [category, inStock]);

return { products, loading };
}

function ProductList() {
const { products, loading } = useProducts('Electronics', true);

if (loading) return <div>Loading...</div>;

return (
<ul>
{products.map(p => (
<li key={p.sku}>{p.name} - ${p.price}</li>
))}
</ul>
);
}

A browser on another origin needs that origin in cors.allow-origins in flapi.yaml.

Scaling Considerations​

  • Sheet size: a spreadsheet holds up to 10 million cells; long before that, the export gets slow. Thousands of rows are comfortable.
  • Google's limits: the export URL is fetched once per refresh per endpoint, not per request, so API traffic does not reach Google.
  • Freshness: edits appear after the next refresh. Shorten schedule, or refresh on demand (flapii cache refresh with the config service, flapi cache refresh -c flapi.yaml --all without it).

When to Migrate​

Consider moving to PostgreSQL or BigQuery when:

  • ❌ Products > 50,000
  • ❌ You need transactions or concurrent writers
  • ❌ Stock must be correct to the second
  • ❌ The data may not be public

Because requests read only the cache table, migrating changes only the populate template (see the migration path); the endpoints, validators and serving templates stay.

Troubleshooting​

503 cache_build_failed, or an HTML page instead of CSV​

The sheet is not shared as "anyone with the link can view", or the gid is wrong. curl -L '<export url>' must print CSV, not a Google sign-in page.

A column is missing or a cast fails​

Header names in the sheet must match the column names in the populate template exactly, and every price must be a number. Fix the cell, then refresh: flapii cache refresh /products/ (config service on), or flapi cache refresh -c flapi.yaml --all.

Edits do not show up​

Requests read the cache; it refreshes every schedule. With the config service on (see Step 4), run flapii cache refresh /products/ to pull now, or flapii cache audit /products/ -o table to see when it last ran. Without it, flapi cache refresh -c flapi.yaml --all pulls now.

Next Steps​


Marketing Loves This

Non-technical staff update product descriptions, pricing and availability without waiting for developers, and developers get a clean, cached API in front of it.

🍪 Cookie Settings