<a id="downloading-a-draft-via-the-api"></a>
<a id="api-draft-export"></a>
# 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](../exporting_draft.html.md#download-draft) 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.

<a id="what-you-get"></a>
## 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.

<a id="behavior-and-constraints"></a>
## 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.

<a id="authentication"></a>
## Authentication

These endpoints accept the same credentials as the rest of the API. See [Authentication](authentication.html.md#api-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.

<a id="endpoint-summary"></a>
## 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](api_drafts.html.md#api-drafts), `GET /api/v2/drafts/`.

<a id="ask-for-the-download"></a>
## 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):

```json
{
    "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.

<a id="poll-until-it-is-ready"></a>
## 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`:

```json
{
    "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:

```json
{
    "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.

<a id="fetch-the-file"></a>
## 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.

<a id="worked-example-in-python"></a>
## Worked example in Python

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

```python
# Copyright TrialGrid Limited

"""Download a Draft as an Architect Loader Spreadsheet or an Excel workbook through the TrialGrid API.

This script:

1. Asks for an export of the Draft and prints any warnings about it.
2. Polls the export until it is complete (or has failed).
3. Downloads the file from the URL in the completed status: a zip archive for an ALS, or the
   .xlsx itself for an Excel workbook.

Edit the ``Configuration`` constants below for your environment, or set the matching
``EXAMPLE_*`` environment variables.
"""

import base64
import os
import time
from pathlib import Path

import requests

# ---- Configuration ----------------------------------------------------------------------
BASE_URL = os.environ.get("EXAMPLE_BASE_URL", "https://www.trialgrid.io/api/v2")
DRAFT_ID = int(os.environ.get("EXAMPLE_DRAFT_ID", "456"))
# "als" for an Architect Loader Spreadsheet (Medidata Rave Drafts only), or "xlsx" for an Excel workbook
FILE_FORMAT = os.environ.get("EXAMPLE_FILE_FORMAT", "als")
OUTPUT_DIR = Path(os.environ.get("EXAMPLE_OUTPUT_DIR", ""))

# ---- Authentication: pick ONE of the two styles below -----------------------------------
# (a) HTTP Basic Authentication - username + password.
USERNAME = os.environ.get("EXAMPLE_USERNAME", "alice@example.com")
PASSWORD = os.environ.get("EXAMPLE_PASSWORD", "<your password>")
AUTH_HEADERS = {
    "Authorization": "Basic " + base64.b64encode(f"{USERNAME}:{PASSWORD}".encode()).decode(),
}
# (b) Token Authentication - see https://www.trialgrid.io/docs/api.html#token-authentication
#     for how to generate or revoke tokens.
# AUTH_HEADERS = {"Authorization": "Token fa2ae7f1c766ddea1c8b4ff14773de33569d399b"}
# -----------------------------------------------------------------------------------------

POLL_SECONDS = float(os.environ.get("EXAMPLE_POLL_SECONDS", "3"))
TIMEOUT_SECONDS = int(os.environ.get("EXAMPLE_TIMEOUT_SECONDS", "3600"))

def start_export(draft_id: int, file_format: str) -> int:
    """Ask for an export of the whole Draft. Returns the task_id."""
    resp = requests.post(
        f"{BASE_URL}/drafts/{draft_id}/export/",
        json={"file_format": file_format},
        headers=AUTH_HEADERS,
        timeout=30,
    )
    if resp.status_code == 429:
        raise RuntimeError(f"Too many exports, retry in {resp.headers['Retry-After']} seconds")
    resp.raise_for_status()
    body = resp.json()
    for warning in body["export_warnings"]:
        print(f"  Warning ({warning['section']}): {warning['message']} {warning['url']}")
    return body["task_id"]

def wait_for_completion(task_id: int) -> dict:
    """Poll until the export is Complete or Failed. Returns the final status."""
    deadline = time.monotonic() + TIMEOUT_SECONDS
    while True:
        resp = requests.get(f"{BASE_URL}/draft_export_tasks/{task_id}/", headers=AUTH_HEADERS, timeout=30)
        resp.raise_for_status()
        status = resp.json()
        if status["state"] == "C":
            if status["download"] is None:
                raise RuntimeError(f"Export {task_id} is complete but its file is no longer available; start a new one")
            return status
        if status["state"] == "F":
            raise RuntimeError(f"Export failed: {status['state_message']}")
        if time.monotonic() > deadline:
            raise TimeoutError(f"Export {task_id} did not complete in {TIMEOUT_SECONDS}s")
        print(f"  {status['progress_pct']}% - {status['state_message']}")
        time.sleep(POLL_SECONDS)

def download(status: dict, save_to: Path) -> None:
    """Save the file. Send no Authorization header: the signed URL authorizes the request."""
    with requests.get(status["download"]["url"], stream=True, timeout=60) as resp:
        resp.raise_for_status()
        with save_to.open("wb") as fh:
            for chunk in resp.iter_content(chunk_size=64 * 1024):
                fh.write(chunk)
    print(f"Saved {status['download']['size_in_bytes']} bytes to {save_to}")

if __name__ == "__main__":
    task_id = start_export(DRAFT_ID, FILE_FORMAT)
    print(f"Started export {task_id}")

    final = wait_for_completion(task_id)
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    download(final, OUTPUT_DIR / final["download"]["filename"])
```

<a id="error-responses"></a>
## 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. |
