> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usedatabrain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Query Guidelines

> Best practices for writing clean, maintainable, and production-ready Python queries in Databrain.

Before writing your Python query, note the following runtime assumptions:

1. The `requests` module is already available in scope.
2. The following variables are available:
   * `client_id` → string
   * `metric_filters` → filter configuration object
3. Secrets are available through:
   * `secrets["SECRET_NAME"]`
4. The final output must be assigned to a variable named `result`.
5. The output must be:
   * an array of objects
   * or a list of dictionaries

## Metric Filters Structure

Use the following structure when working with metric filters in your query:

```python theme={"dark"}
from typing import Dict, Union
import datetime


class DateDict:
    startDate: datetime.date
    endDate: datetime.date


MetricFilters = Dict[str, Union[DateDict, str, int]]
```

## Formatting Instructions

1. Use consistent indentation (4 spaces).
2. Follow PEP8 naming conventions.
3. Use descriptive variable names.
4. Avoid hardcoded values; use variables and secrets instead.
5. Add whitespace between logical blocks.
6. Use helper variables to improve readability.
7. Handle filters dynamically instead of hardcoding them.
8. Avoid unnecessary global variables.
9. Use exception handling for API calls when possible.
10. Always assign output to the `result` variable.

## Core Usage Guidelines

### Guideline 1: Import `requests`

The `requests` module is already available and does not need installation, but you should still import it for clarity:

```python theme={"dark"}
import requests
```

### Guideline 2: Use Runtime Variables

Use the available runtime variables instead of hardcoding values:

```python theme={"dark"}
payload = {
    "clientId": client_id,
}
```

### Guideline 3: Use Metric Filters Dynamically

Handle `metric_filters` generically based on type to support both date ranges and simple values:

```python theme={"dark"}
query_filters = {}

for key, value in metric_filters.items():
    if isinstance(value, dict):
        query_filters[key] = {
            "startDate": value["startDate"].isoformat(),
            "endDate": value["endDate"].isoformat(),
        }
    else:
        query_filters[key] = value
```

### Guideline 4: Use Secrets Securely

Always retrieve sensitive information using `secrets`:

```python theme={"dark"}
base_url = secrets["BASE_URL"]
api_key = secrets["API_KEY"]
```

### Guideline 5: Structure API Calls Clearly

Build headers and API calls in a clear, readable way:

```python theme={"dark"}
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

response = requests.get(base_url, headers=headers, params=query_filters)
data = response.json()
```

### Guideline 6: Transform Data Before Returning

Ensure your output matches the required format before assigning it to `result`:

```python theme={"dark"}
result = [
    {
        "key": item["name"],
        "value": item["value"],
    }
    for item in data
]
```

## Output Requirements

Your script **must** end by assigning to `result` using one of the following patterns:

```python theme={"dark"}
result = [{"key": "value"}, ...]
```

or:

```python theme={"dark"}
result = requests.get("SOME_URL").json()
```
