Guides
BigQuery and Dataform
Dataform transforms data that is already in BigQuery. It does not call REST APIs itself, so you need two steps:
- Load: A small script fetches the datasets every night and writes them unchanged to raw tables (dataset
gastrotodo_raw). - Transform: Dataform builds your reporting tables from the raw tables and replaces the rows in the time window.
1. Run the loader as a Cloud Run job
The script loads all datasets for the last 7 days. It gets the table schemas from the API, so BigQuery does not have to infer them. Each run replaces all raw tables. The history is kept in the Dataform tables.
# main.py
from __future__ import annotations
import datetime as dt
import os
import time
import requests
from google.cloud import bigquery
BASE = "https://www.gastrotodo.de/api/v1/reporting"
KEY = os.environ["GASTROTODO_API_KEY"]
PROJECT = os.environ["GCP_PROJECT"]
DATASET = os.environ.get("BQ_DATASET", "gastrotodo_raw")
DATASETS = [
"task-reports", "haccp-measurements", "haccp-incidents", "defects",
"instruction-acknowledgments", "training-completions", "daily-reports", "task-outcomes",
]
session = requests.Session()
def get(path: str, params: dict | None = None) -> dict:
for attempt in range(5):
try:
res = session.get(
f"{BASE}/{path}", params=params, timeout=120,
headers={"Authorization": f"Bearer {KEY}"},
)
except requests.RequestException:
time.sleep(2 ** (attempt + 1))
continue
if res.status_code == 429 or res.status_code >= 500:
time.sleep(int(res.headers.get("Retry-After") or 2 ** (attempt + 1)))
continue
if not res.ok:
raise RuntimeError(f"{path}: {res.status_code} {res.text}")
return res.json()
raise RuntimeError(f"{path}: giving up after retries")
def fetch_all(dataset: str, window: dict) -> list[dict]:
body = get(dataset, {"limit": 1000, **window})
rows = body["data"]
while body["nextCursor"]:
body = get(dataset, {"limit": 1000, "cursor": body["nextCursor"]})
rows += body["data"]
return rows
def replace_table(bq: bigquery.Client, name: str, schema: list, rows: list[dict]) -> None:
table_id = f"{PROJECT}.{DATASET}.{name}"
bq.create_table(bigquery.Table(table_id, schema=schema), exists_ok=True)
if not rows:
bq.query(f"TRUNCATE TABLE `{table_id}`").result()
return
bq.load_table_from_json(
rows, table_id,
job_config=bigquery.LoadJobConfig(schema=schema, write_disposition="WRITE_TRUNCATE"),
).result()
def main() -> None:
bq = bigquery.Client(project=PROJECT)
today = dt.date.today()
days = int(os.environ.get("DAYS", "7"))
window = {
"from": os.environ.get("FROM") or (today - dt.timedelta(days=days)).isoformat(),
"to": os.environ.get("TO") or today.isoformat(),
}
schemas = get("bigquery-schema")
for name in DATASETS:
rows = fetch_all(name, window)
schema = [bigquery.SchemaField.from_api_repr(f) for f in schemas[name]]
replace_table(bq, name.replace("-", "_"), schema, rows)
print(f"{name}: {len(rows)} rows")
# The window of this run. Dataform reads it from this table, so it works even
# if a dataset returned no rows.
replace_table(
bq, "load_window",
[bigquery.SchemaField("date_from", "DATE"), bigquery.SchemaField("date_to", "DATE")],
[{"date_from": window["from"], "date_to": window["to"]}],
)
if __name__ == "__main__":
main()Put these two files next to main.py:
# requirements.txt
requests
google-cloud-bigquery# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
CMD ["python", "main.py"]Set up the project
Create the dataset, a service account, and the secret. Replace my-project with your project ID.
PROJECT=my-project
REGION=europe-west3
SA=gastrotodo-loader@$PROJECT.iam.gserviceaccount.com
bq mk --project_id=$PROJECT --location=$REGION --dataset $PROJECT:gastrotodo_raw
gcloud iam service-accounts create gastrotodo-loader --project $PROJECT
printf '%s' "$GASTROTODO_API_KEY" | gcloud secrets create gastrotodo-api-key \
--project $PROJECT --data-file=-
gcloud secrets add-iam-policy-binding gastrotodo-api-key --project $PROJECT \
--member "serviceAccount:$SA" --role roles/secretmanager.secretAccessor
gcloud projects add-iam-policy-binding $PROJECT \
--member "serviceAccount:$SA" --role roles/bigquery.jobUser
gcloud projects add-iam-policy-binding $PROJECT \
--member "serviceAccount:$SA" --role roles/bigquery.dataEditorTo keep the permissions narrow, grant roles/bigquery.dataEditor on the dataset gastrotodo_raw only.
Deploy and schedule
gcloud run jobs deploy gastrotodo-loader --source . --project $PROJECT --region $REGION \
--service-account $SA \
--set-secrets GASTROTODO_API_KEY=gastrotodo-api-key:latest \
--set-env-vars GCP_PROJECT=$PROJECT
gcloud run jobs add-iam-policy-binding gastrotodo-loader --project $PROJECT --region $REGION \
--member "serviceAccount:$SA" --role roles/run.invoker
gcloud scheduler jobs create http gastrotodo-loader --project $PROJECT --location $REGION \
--schedule "0 6 * * *" --time-zone Europe/Berlin --http-method POST \
--uri "https://run.googleapis.com/v2/projects/$PROJECT/locations/$REGION/jobs/gastrotodo-loader:run" \
--oauth-service-account-email $SAAt 6 a.m., the previous business day is complete.
2. Transform with Dataform
Declare sources
-- definitions/sources/task_reports.sqlx
config { type: "declaration", schema: "gastrotodo_raw", name: "task_reports" }Create one declaration for each raw table, including load_window. To run Dataform after the loader, create a workflow configuration with a schedule, e.g. at 7 a.m.
Replace the window
The raw table contains the window of the last run, and load_window contains its start and end. The incremental table deletes the rows in that window and inserts the new ones, so it reflects both corrections and deletions. List the columns you need explicitly, so that new API fields do not change your table.
-- definitions/reporting/fct_task_reports.sqlx
config {
type: "incremental",
schema: "reporting",
bigquery: { partitionBy: "DATE(reportedAt)" }
}
pre_operations {
${when(incremental(), `
DELETE FROM ${self()}
WHERE DATE(reportedAt) BETWEEN (SELECT date_from FROM ${ref("load_window")})
AND (SELECT date_to FROM ${ref("load_window")})
`)}
}
SELECT
id, areaId, areaName, locationId, locationName, taskId, taskTitle, departmentId, departmentName,
status, reportedAt, plannedDate, reportedByEmployeeId, reportedByName, isHaccp,
measuredValue, measurementUnit, comment, reason, correctiveAction
FROM ${ref("task_reports")}Use the same pattern for haccp_measurements (column measuredAt), instruction_acknowledgments (acknowledgedAt), and training_completions (completedAt). For task_outcomes, daily_reports, and haccp_incidents, compare the date column directly:
-- definitions/reporting/fct_task_outcomes.sqlx
config {
type: "incremental",
schema: "reporting",
bigquery: { partitionBy: "date" }
}
pre_operations {
${when(incremental(), `
DELETE FROM ${self()}
WHERE date BETWEEN (SELECT date_from FROM ${ref("load_window")})
AND (SELECT date_to FROM ${ref("load_window")})
`)}
}
SELECT id, date, areaId, areaName, locationId, locationName, taskId, taskTitle,
departmentId, departmentName, status, plannedDate, isLate, isHaccp,
reportedByEmployeeId, reportedByName, reportedAt, reason, correctiveAction
FROM ${ref("task_outcomes")}Defects: merge by id
-- definitions/reporting/fct_defects.sqlx
config { type: "incremental", schema: "reporting", uniqueKey: ["id"] }
SELECT id, areaId, areaName, locationId, locationName, deviceName, productName, manufacturerName, description,
hasPhoto, reportedAt, resolvedAt, reportedByEmployeeId, reportedByName
FROM ${ref("defects")}Daily reports and the latest names
Create fct_daily_reports with the same pattern as fct_task_outcomes:
SELECT id, date, areaId, areaName, locationId, locationName, isFinal, dueCount,
completedCount, lateCount, canceledCount, missedCount, skippedCount, openCount,
fulfillmentRate, haccpIncidentCount, employeeCount
FROM ${ref("daily_reports")}When an area or a location is renamed, rows that are already in your warehouse keep the old name. This view returns the latest name for each ID:
-- definitions/reporting/dim_locations.sqlx
config { type: "view", schema: "reporting" }
SELECT
areaId,
locationId,
ARRAY_AGG(areaName ORDER BY date DESC LIMIT 1)[OFFSET(0)] AS area,
COALESCE(ARRAY_AGG(locationName ORDER BY date DESC LIMIT 1)[OFFSET(0)], 'whole area') AS location
FROM ${ref("fct_daily_reports")}
GROUP BY areaId, locationIdExample: fulfillment rate per area, location, and day
Use only rows with isFinal = TRUE. On the current business day, completed tasks already count but open tasks do not, so the rate would be too high.
-- definitions/reporting/fulfillment_daily.sqlx
config { type: "view", schema: "reporting" }
SELECT
r.date,
r.areaId,
n.area,
r.locationId,
n.location,
r.completedCount AS completed,
r.dueCount AS due,
r.fulfillmentRate AS fulfillment_rate
FROM ${ref("fct_daily_reports")} r
JOIN ${ref("dim_locations")} n
ON n.areaId = r.areaId AND COALESCE(n.locationId, 0) = COALESCE(r.locationId, 0)
WHERE r.isFinalInitial load
Load your historical data in windows of at most 92 days, starting with the oldest. Run Dataform after each window, because the next load replaces the raw tables:
gcloud run jobs execute gastrotodo-loader --region europe-west3 --wait \
--update-env-vars FROM=2026-07-01,TO=2026-09-30Then run Dataform, load the next window, and repeat. When you are done, the nightly run continues without FROM and TO.
Monthly reload
Once a month, reload the last 92 days to pick up older corrections and deleted tasks, then run Dataform:
gcloud run jobs execute gastrotodo-loader --region europe-west3 --wait \
--update-env-vars DAYS=91