Downloading a Draft via the API

The API can download a whole Draft as an Architect Loader Spreadsheet (ALS) or an Excel workbook, the same file the Download button on the Draft home page produces. You ask for the download, poll until the file is ready, and then fetch it from a time-limited URL.

What you get

Every download includes everything in the Draft. It is the file you get from the Download button with every object type ticked, including TrialGrid Extensions. You choose the file format:

  • als gives an ALS (.xls) ready to upload into Rave Architect. It is only available for a Draft on a Medidata Rave URL, and is what a Medidata Rave Draft gets if you do not choose.

  • xlsx gives an Excel workbook (.xlsx). It is available for every Draft, and is what a Draft on any other URL gets if you do not choose.

  • An ALS comes inside a zip archive. An Excel workbook is already compressed, so it comes as the .xlsx itself.

  • The extra worksheets whose names start TG_ hold your Test Cases and Custom Properties. Rave ignores them when you upload the ALS.

To choose which object types to include, use the Download button instead.

Behavior and constraints

  • Requests run as you. You can download any Draft you can open in TrialGrid. If you lose access to the Draft's Project, or the Draft is deleted, the status endpoint stops giving out download URLs for it. A URL it has already given out keeps working until it expires. Each download is recorded once in the Draft's activity, when its first download URL is given out.

  • Downloads take a little time. Asking for a download starts it in the background and returns a task_id straight away. Poll the status endpoint until it reports the download is complete. Most Drafts take a few seconds; a very large one can take tens of minutes.

  • Downloads are rate limited. Each user can ask for 20 downloads per hour, on top of the limit that applies to the whole API. Over that, the API answers 429 Too Many Requests with a Retry-After header giving the number of seconds to wait. Polling for status and fetching the file do not count towards the 20.

  • The download URL expires. It is typically valid for one hour. If it expires, poll the status endpoint again for a fresh URL to the same file. Old files are eventually removed, and a completed download whose file has gone has a download of null. Ask for a new download instead.

Authentication

These endpoints accept the same credentials as the rest of the API. See Authentication.

Important

Do not send your TrialGrid credentials with the final request for the file. The URL itself authorizes that request, and an extra Authorization header can make it fail.

Endpoint summary

Every endpoint is versioned with v1 or v2; the examples use v2 and there is no difference.

Method

Path

Purpose

POST

/api/v2/drafts/{draft_id}/export/

Start a download of the Draft, returns a task_id

GET

/api/v2/draft_export_tasks/{task_id}/

Poll the download; once complete it includes the URL of the file

Find a Draft's id with the Drafts API, GET /api/v2/drafts/.

1. Ask for the download

Send a POST. The body is optional, and its only setting is file_format, either "als" or "xlsx":

POST /api/v2/drafts/456/export/
Authorization: Token fa2ae7f1c766ddea1c8b4ff14773de33569d399b
Content-Type: application/json

{
    "file_format": "xlsx"
}

With no body, a Medidata Rave Draft is downloaded as an ALS and any other Draft as an Excel workbook.

Response (HTTP 202 Accepted):

{
    "task_id": 9876,
    "status_url": "/api/v2/draft_export_tasks/9876/",
    "export_warnings": [
        {
            "section": "Draft",
            "message": "Primary Form not set",
            "url": "https://www.trialgrid.io/drafts/456/edit"
        }
    ]
}

export_warnings lists the warnings the Download button shows before a download, such as a missing Primary Form or open Diagnostic findings. They do not stop the download, but the file might not upload into Rave until they are fixed. The list is empty when there is nothing to warn about.

2. Poll until it is ready

GET /api/v2/draft_export_tasks/9876/
Authorization: Token fa2ae7f1c766ddea1c8b4ff14773de33569d399b

While the download is being prepared, download is null:

{
    "task_id": 9876,
    "name": "Export Draft Draft 1",
    "state": "R",
    "state_display": "Running",
    "progress_pct": 40,
    "state_message": "Writing Fields",
    "created": "2026-11-10T10:00:00+00:00",
    "updated": "2026-11-10T10:00:03+00:00",
    "download": null
}

Once it is complete, download tells you where to fetch the file:

{
    "task_id": 9876,
    "name": "Export Draft Draft 1",
    "state": "C",
    "state_display": "Complete",
    "progress_pct": 100,
    "state_message": "Export complete.",
    "created": "2026-11-10T10:00:00+00:00",
    "updated": "2026-11-10T10:00:06+00:00",
    "download": {
        "url": "https://s3.amazonaws.com/...?X-Amz-Signature=...",
        "filename": "Study_123_Draft_1.zip",
        "content_type": "application/zip",
        "size_in_bytes": 482113,
        "expires_in_seconds": 3600
    }
}

The states are P Pending, R Running, C Complete and F Failed. Polling every few seconds is reasonable. progress_pct does not always move between polls, so an unchanged value does not mean the download has stalled.

3. Fetch the file

Send a GET to download.url without an Authorization header and save the response: the zip archive for an ALS, or the .xlsx for an Excel workbook. If the URL has expired, poll the status endpoint again for a new one.

Worked example in Python

This example uses requests (pip install requests). Edit the constants at the top, or set the matching EXAMPLE_* environment variables.

 1# Copyright TrialGrid Limited
 2
 3"""Download a Draft as an Architect Loader Spreadsheet or an Excel workbook through the TrialGrid API.
 4
 5This script:
 6
 71. Asks for an export of the Draft and prints any warnings about it.
 82. Polls the export until it is complete (or has failed).
 93. Downloads the file from the URL in the completed status: a zip archive for an ALS, or the
10   .xlsx itself for an Excel workbook.
11
12Edit the ``Configuration`` constants below for your environment, or set the matching
13``EXAMPLE_*`` environment variables.
14"""
15
16import base64
17import os
18import time
19from pathlib import Path
20
21import requests
22
23# ---- Configuration ----------------------------------------------------------------------
24BASE_URL = os.environ.get("EXAMPLE_BASE_URL", "https://www.trialgrid.io/api/v2")
25DRAFT_ID = int(os.environ.get("EXAMPLE_DRAFT_ID", "456"))
26# "als" for an Architect Loader Spreadsheet (Medidata Rave Drafts only), or "xlsx" for an Excel workbook
27FILE_FORMAT = os.environ.get("EXAMPLE_FILE_FORMAT", "als")
28OUTPUT_DIR = Path(os.environ.get("EXAMPLE_OUTPUT_DIR", ""))
29
30# ---- Authentication: pick ONE of the two styles below -----------------------------------
31# (a) HTTP Basic Authentication - username + password.
32USERNAME = os.environ.get("EXAMPLE_USERNAME", "alice@example.com")
33PASSWORD = os.environ.get("EXAMPLE_PASSWORD", "<your password>")
34AUTH_HEADERS = {
35    "Authorization": "Basic " + base64.b64encode(f"{USERNAME}:{PASSWORD}".encode()).decode(),
36}
37# (b) Token Authentication - see https://www.trialgrid.io/docs/api.html#token-authentication
38#     for how to generate or revoke tokens.
39# AUTH_HEADERS = {"Authorization": "Token fa2ae7f1c766ddea1c8b4ff14773de33569d399b"}
40# -----------------------------------------------------------------------------------------
41
42POLL_SECONDS = float(os.environ.get("EXAMPLE_POLL_SECONDS", "3"))
43TIMEOUT_SECONDS = int(os.environ.get("EXAMPLE_TIMEOUT_SECONDS", "3600"))
44
45
46def start_export(draft_id: int, file_format: str) -> int:
47    """Ask for an export of the whole Draft. Returns the task_id."""
48    resp = requests.post(
49        f"{BASE_URL}/drafts/{draft_id}/export/",
50        json={"file_format": file_format},
51        headers=AUTH_HEADERS,
52        timeout=30,
53    )
54    if resp.status_code == 429:
55        raise RuntimeError(f"Too many exports, retry in {resp.headers['Retry-After']} seconds")
56    resp.raise_for_status()
57    body = resp.json()
58    for warning in body["export_warnings"]:
59        print(f"  Warning ({warning['section']}): {warning['message']} {warning['url']}")
60    return body["task_id"]
61
62
63def wait_for_completion(task_id: int) -> dict:
64    """Poll until the export is Complete or Failed. Returns the final status."""
65    deadline = time.monotonic() + TIMEOUT_SECONDS
66    while True:
67        resp = requests.get(f"{BASE_URL}/draft_export_tasks/{task_id}/", headers=AUTH_HEADERS, timeout=30)
68        resp.raise_for_status()
69        status = resp.json()
70        if status["state"] == "C":
71            if status["download"] is None:
72                raise RuntimeError(f"Export {task_id} is complete but its file is no longer available; start a new one")
73            return status
74        if status["state"] == "F":
75            raise RuntimeError(f"Export failed: {status['state_message']}")
76        if time.monotonic() > deadline:
77            raise TimeoutError(f"Export {task_id} did not complete in {TIMEOUT_SECONDS}s")
78        print(f"  {status['progress_pct']}% - {status['state_message']}")
79        time.sleep(POLL_SECONDS)
80
81
82def download(status: dict, save_to: Path) -> None:
83    """Save the file. Send no Authorization header: the signed URL authorizes the request."""
84    with requests.get(status["download"]["url"], stream=True, timeout=60) as resp:
85        resp.raise_for_status()
86        with save_to.open("wb") as fh:
87            for chunk in resp.iter_content(chunk_size=64 * 1024):
88                fh.write(chunk)
89    print(f"Saved {status['download']['size_in_bytes']} bytes to {save_to}")
90
91
92if __name__ == "__main__":
93    task_id = start_export(DRAFT_ID, FILE_FORMAT)
94    print(f"Started export {task_id}")
95
96    final = wait_for_completion(task_id)
97    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
98    download(final, OUTPUT_DIR / final["download"]["filename"])

Error responses

Status

Meaning

400

file_format is not als or xlsx, or is als for a Draft that is not on a Medidata Rave URL.

401

Missing or invalid credentials.

403

You cannot view the Draft's Project, or your Organization is not licensed for the Draft's URL. For the status endpoint: the download is ready, but you can no longer view the Draft's Project.

404

The Draft does not exist, or the task does not exist, is not a Draft download, or is not yours.

429

You have asked for too many downloads. Wait for the number of seconds in the Retry-After header.