Dataform repositories do not all live in git. If you connected yours to GitHub or GitLab when you set it up, this post is not for you: git clone and you are done. But when the GA4Dataform installer creates the repository for you, which is the default, it has no remote. There is nothing to clone. The files exist only inside the Dataform interface in the Google Cloud console.
That becomes a problem the moment you want the workspace on your laptop, which is where most people end up: to read the code in an editor, to diff two installations, or to point an AI assistant at it for onboarding. The Dataform API will hand you every file. Here is a small script that walks a workspace and mirrors it to a local folder.
What you need on your machine
Four things, and you probably have three of them already.
- Python 3. The script imports nothing outside the standard library, so there is no
pip installstep and no virtual environment to set up. - The gcloud CLI, authenticated. The script shells out to
gcloud auth print-access-tokenfor its credentials. If you have never logged in, rungcloud auth loginfirst. If your default gcloud account is not the one with access to the Dataform project, setGCLOUD_ACCOUNT=you@company.comand the script will use that one instead. - The Dataform Viewer role (or higher) on the project. Reading files is all the script does, so Viewer is enough. If you also plan to push your edits back later, you need Dataform Editor for that part. A 403 from the API means this role is missing, and the script says so rather than failing silently.
- The bq command-line tool, if you want to run BigQuery checks against your tables once the copy is local. Not needed for the download itself.
The GCP console URL
Open the workspace in the Cloud console and look at the address bar. Say it reads:
https://console.cloud.google.com/bigquery/dataform/locations/europe-west4/repositories/my-custom-datamodel/workspaces/jules-dev/files/?project=acme-analytics
The five values the script wants are all in there:
projectis the?project=query parameter:acme-analyticslocationcomes after/locations/:europe-west4repositorycomes after/repositories/:my-custom-datamodelworkspacecomes after/workspaces/:jules-devdest_diris yours to pick: wherever you want the local copy to land
Note that the project is at the end of the URL but goes first on the command line.
The script
Save this as fetch_dataform_workspace.py.
#!/usr/bin/env python3
"""Mirror a hosted Dataform workspace to a local folder via the Dataform API.
Usage: fetch_dataform_workspace.py <project> <location> <repository> <workspace> <dest_dir>
Writes a .ga4df-sync.json manifest into <dest_dir> recording the connection
details and a hash per file - push_dataform_workspace.py uses it to detect
local changes and remote conflicts.
Auth: uses your active gcloud account (set GCLOUD_ACCOUNT to pick another
credentialed one). The account needs the Dataform Viewer role or higher on
the project.
"""
import base64
import hashlib
import json
import os
import subprocess
import sys
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
if len(sys.argv) != 6:
sys.exit(__doc__.strip())
project, location, repo, workspace, dest = sys.argv[1:6]
account = os.environ.get("GCLOUD_ACCOUNT")
cmd = ["gcloud", "auth", "print-access-token"] + (
[f"--account={account}"] if account else []
)
try:
token = subprocess.check_output(cmd, text=True).strip().splitlines()[-1]
except subprocess.CalledProcessError:
sys.exit(
"Could not get a gcloud access token. Run 'gcloud auth login' first, "
"or set GCLOUD_ACCOUNT to a credentialed account."
)
WS = (
f"https://dataform.googleapis.com/v1beta1/projects/{project}"
f"/locations/{location}/repositories/{repo}/workspaces/{workspace}"
)
def get(url):
req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
try:
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as e:
if e.code == 403:
sys.exit(
f"Permission denied on {project}. Your account needs the "
"Dataform Viewer role (or higher) on this project - or set "
"GCLOUD_ACCOUNT to one that has it."
)
raise
def list_all_files():
files, page_token = [], None
while True:
url = f"{WS}:searchFiles?pageSize=1000"
if page_token:
url += f"&pageToken={urllib.parse.quote(page_token)}"
data = get(url)
for entry in data.get("searchResults", []):
if "file" in entry:
files.append(entry["file"]["path"])
page_token = data.get("nextPageToken")
if not page_token:
return files
def fetch_file(path):
data = get(f"{WS}:readFile?path={urllib.parse.quote(path, safe='')}")
content = base64.b64decode(data.get("fileContents", ""))
local = os.path.join(dest, path)
os.makedirs(os.path.dirname(local), exist_ok=True)
with open(local, "wb") as f:
f.write(content)
return path, hashlib.sha256(content).hexdigest()
start = time.time()
files = list_all_files()
print(f"listed {len(files)} files")
with ThreadPoolExecutor(max_workers=8) as pool:
hashes = dict(pool.map(fetch_file, sorted(files)))
manifest = {
"project": project,
"location": location,
"repository": repo,
"workspace": workspace,
"fetched_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"files": hashes,
}
with open(os.path.join(dest, ".ga4df-sync.json"), "w") as f:
json.dump(manifest, f, indent=2, sort_keys=True)
print(
f"done: {len(files)} files in {time.time() - start:.1f}s -> {dest}\n"
"Push local edits back later with: push_dataform_workspace.py "
f"{dest} --message 'your commit message'"
)
Running it
For the workspace in the URL above, dropping the copy into ~/dataform/my-custom-datamodel:
python3 fetch_dataform_workspace.py acme-analytics europe-west4 my-custom-datamodel jules-dev ~/dataform/my-custom-datamodel
It lists the files first, then fetches them eight at a time, so a typical GA4Dataform installation of around 170 files takes a few seconds:
listed 171 files done: 171 files in 3.8s -> /Users/jules/dataform/my-custom-datamodel Push local edits back later with: push_dataform_workspace.py /Users/jules/dataform/my-custom-datamodel --message 'your commit message'
If you get a permission error instead, the account gcloud is currently using does not have Dataform Viewer on that project. Check which one that is with gcloud auth list, then either switch it or pass the right one through GCLOUD_ACCOUNT.
Do not delete the .ga4df-sync.json file
Alongside your files the script writes a manifest called .ga4df-sync.json. It records the project, location, repository and workspace it copied from, plus a SHA-256 hash of every file as it was at the time of the download.
That manifest is what makes the trip back possible. The companion script that ships inside your workspace, push_dataform_workspace.py, reads it to work out which files you changed locally and which ones somebody else changed in the Dataform interface while you were working. Without it, a push has no way to tell your edits apart from everyone’s, and no way to refuse an overwrite it should refuse. Keep the file where it is, and keep it out of any cleanup you run on the folder.



