Quick Start

This page walks through a minimal example of using the SDK.

Installation

# PyPI release
pip install imednet
# Install all tabular export dependencies
pip install "imednet[export]"

# Or install destination-specific extras
pip install "imednet[duckdb]"
pip install "imednet[mongodb]"
pip install "imednet[neo4j]"
pip install "imednet[snowflake]"
# Workflow plugin package
pip install imednet-workflows

# Airflow provider package (core hook/operator/sensor support)
pip install "apache-airflow>=3.2.0,<4.0.0" apache-airflow-providers-imednet

Basic Usage

Set your credentials by copying the environment template or exporting them directly:

cp .env.example .env
export IMEDNET_API_KEY="your_api_key"
export IMEDNET_SECURITY_KEY="your_security_key"

Synchronous Example

from __future__ import annotations

import sys

from dotenv import load_dotenv

from imednet import ImednetSDK, load_config
from imednet.utils import configure_json_logging

"""Quick start example using environment variables for authentication.

Set ``IMEDNET_API_KEY`` and ``IMEDNET_SECURITY_KEY`` before running this
script. Optionally set ``IMEDNET_BASE_URL`` for non-default instances.

Example:

    cp .env.example .env
    # Or export directly:
    export IMEDNET_API_KEY="your_api_key"
    export IMEDNET_SECURITY_KEY="your_security_key"
    # Optional: Custom base URL for the API endpoint
    # export IMEDNET_BASE_URL="https://edc.prod.imednetapi.com"
    uv run --with "imednet[cli]" python examples/quick_start.py
"""


def main() -> None:
    """Run a minimal SDK example using environment variables."""
    configure_json_logging()
    # Load environment variables from .env file if it exists
    # Note: Ensure you've run `cp .env.example .env` or exported keys to your shell.
    load_dotenv()

    try:
        cfg = load_config()
    except ValueError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

    with ImednetSDK(
        api_key=cfg.api_key,
        security_key=cfg.security_key,
        base_url=cfg.base_url,
    ) as sdk:
        print(list(sdk.studies.list()))


if __name__ == "__main__":
    main()

Asynchronous Example

from __future__ import annotations

import asyncio
import os
import sys

from dotenv import load_dotenv

from imednet import AsyncImednetSDK, load_config
from imednet.utils import configure_json_logging

"""Async quick start example using environment variables for authentication.

Set ``IMEDNET_API_KEY`` and ``IMEDNET_SECURITY_KEY`` before running this
script. Optionally set ``IMEDNET_BASE_URL`` for non-default instances.
Provide ``IMEDNET_JOB_STUDY_KEY`` and ``IMEDNET_BATCH_ID`` to poll a job.

Example::

    cp .env.example .env
    # Or export directly:
    export IMEDNET_API_KEY="your_api_key"
    export IMEDNET_SECURITY_KEY="your_security_key"
    # Optional: Custom base URL for the API endpoint
    # export IMEDNET_BASE_URL="https://edc.prod.imednetapi.com"
    uv run --with "imednet[cli]" python examples/async_quick_start.py
"""


async def main() -> None:
    """Run a minimal async SDK example using environment variables."""
    configure_json_logging()
    # Load environment variables from .env file if it exists
    # Note: Ensure you've run `cp .env.example .env` or exported keys to your shell.
    load_dotenv()

    try:
        cfg = load_config()
    except ValueError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

    async with AsyncImednetSDK(
        api_key=cfg.api_key,
        security_key=cfg.security_key,
        base_url=cfg.base_url,
    ) as sdk:
        studies = [s async for s in sdk.studies.list()]
        print(studies)

        job_study = os.getenv("IMEDNET_JOB_STUDY_KEY")
        batch_id = os.getenv("IMEDNET_BATCH_ID")
        if job_study and batch_id:
            status = await sdk.poll_job(job_study, batch_id, interval=2, timeout=60)
            print(status)


if __name__ == "__main__":
    asyncio.run(main())

Custom retry logic can be provided via a RetryPolicy:

from collections.abc import Iterator
import httpx
from imednet import ImednetSDK
from imednet.core.retry import RetryConfig, RetryPolicy, RetryState
from imednet.errors import RateLimitError, ServerError

class ServerRetry(RetryPolicy):
    def should_retry(self, state: RetryState) -> bool:
        if isinstance(state.exception, (RateLimitError, ServerError, httpx.RequestError)):
            return True
        if isinstance(state.result, httpx.Response):
            status = state.result.status_code
            return status == 429 or 500 <= status < 600
        return False

attempts: list[int] = []
responses: Iterator[httpx.Response] = iter(
    [
        httpx.Response(429, json={"metadata": {"status": "TOO_MANY_REQUESTS"}}),
        httpx.Response(500, json={"metadata": {"status": "SERVER_ERROR"}}),
        httpx.Response(
            200,
            json={
                "metadata": {"status": "OK"},
                "pagination": {
                    "currentPage": 0,
                    "size": 25,
                    "totalPages": 1,
                    "totalElements": 1,
                },
                "data": [{"studyKey": "STUDY", "studyName": "Quick Start Study"}],
            },
        ),
    ]
)

def responder(_request: httpx.Request) -> httpx.Response:
    resp = next(responses)
    attempts.append(resp.status_code)
    return resp

retry_sdk = ImednetSDK(
    api_key="mock",  # pragma: allowlist secret
    security_key="mock",  # pragma: allowlist secret
    retry_config=RetryConfig(retries=3, backoff_factor=0.01, retry_policy=ServerRetry()),
    transport=httpx.MockTransport(responder),
)
retried_studies = list(retry_sdk.studies.list())
assert attempts == [429, 500, 200]
assert len(retried_studies) == 1

sdk = ImednetSDK(
    api_key="mock",  # pragma: allowlist secret
    security_key="mock",  # pragma: allowlist secret
    retry_config=RetryConfig(retries=3, backoff_factor=0.01, retry_policy=ServerRetry()),
)

See Retry Policy and Error Handling for more guidance on error handling and exponential backoff.