Basic Python Code to Download Documents as .Grist Files

Here is just some simple Python code to download your entire Grist document as a .grist (.sqlite) file. To use it, just call “download_grist_document” with the following parameters:

Team Name (pass an empty string (“”) if your document isn’t under a Teams site)
Document ID (you can find this under the “Settings” option on the document)
API Key (you can find this under your user Profile Settings)
Save Directory (directory to save the file to - it will be created if it doesn’t exist)
Filename (the name to give to the downloaded Grist document like “mydocument.grist”)

import requests
import os

# Pass in the team name (leave empty if no team), document ID, Grist API Key, directory and file name
def download_grist_document(team, doc_id, api_key, save_directory, filename):
    headers = {"Authorization": f"Bearer {api_key}"}

    if len(team) == 0:
        url = f"{doc_id}/download"           # url for non team documents
        url = f"https://{team}{doc_id}/download"         # url for teams documents

    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        if not os.path.exists(save_directory):              # Check to make sure the directory exists
            os.makedirs(save_directory)                     # If not, create it
        file_path = os.path.join(save_directory, filename)  # Combine the path and file name
        with open(file_path, "wb") as file:                 # Save the Grist file
        print("Error downloading the document.")            # Report if document can't be downloaded

# Team Example:
#                           TEAM           DOCUMENT ID           GRIST API KEY        PATH       DOCUMENT NAME
# download_grist_document('myteamname','documentidgoeshere','mygristapikeygoeshere',"C:/Temp/","document1.grist")

# Non Team Example
# download_grist_document('','documentidgoeshere','mygristapikeygoeshere',"C:/Temp/","document2.grist")