From 872ed40ed0a0ad68a5a619b86d5de08279231ea3 Mon Sep 17 00:00:00 2001 From: fderuiter <127706008+fderuiter@users.noreply.github.com> Date: Thu, 26 Feb 2026 22:14:21 +0000 Subject: [PATCH] docs: Standardize example scripts configuration Refactors the example scripts in `examples/basic/` and `examples/async/` to use `imednet.load_config()` instead of hardcoded placeholder credentials. This encourages secure practices by loading credentials from environment variables (e.g., via a `.env` file). - Added `examples/README.md` with setup instructions. - Updated all basic examples to use `load_config` and `configure_json_logging`. - Updated async example to use `load_config` and `configure_json_logging`. - Fixed linting errors in modified files. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> --- examples/README.md | 34 +++++ examples/async/get_records_async.py | 29 ++--- examples/basic/get_codings.py | 66 ++++++---- examples/basic/get_record_revisions.py | 61 +++++---- examples/basic/get_records.py | 60 +++++---- examples/basic/get_sites.py | 62 +++++---- examples/basic/get_studies.py | 51 +++++--- examples/basic/get_subjects.py | 63 +++++---- examples/basic/get_users.py | 63 +++++---- examples/basic/get_variables.py | 174 ++++++++++++++----------- examples/basic/get_visits.py | 57 +++++--- 11 files changed, 444 insertions(+), 276 deletions(-) create mode 100644 examples/README.md diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..f83ec6e5 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,34 @@ +# Examples + +This directory contains examples demonstrating how to use the iMednet Python SDK. + +## Prerequisites + +Before running the examples, you need to set up your environment with your iMednet API credentials. + +1. Copy `.env.example` to `.env` in the root of the project: + ```bash + cp .env.example .env + ``` + +2. Fill in your API credentials in `.env`: + ```ini + IMEDNET_API_KEY=your_api_key_here + IMEDNET_SECURITY_KEY=your_security_key_here + # Optional: Set base URL if using a custom instance + # IMEDNET_BASE_URL=https://edc.prod.imednetapi.com + ``` + +## Running Examples + +You can run any example directly using Python: + +```bash +python examples/basic/get_studies.py +``` + +## Structure + +- `basic/`: Simple synchronous examples for common endpoints (studies, sites, subjects, records, etc.). +- `async/`: Asynchronous examples using `asyncio`. +- `workflows/`: Examples of higher-level workflows. diff --git a/examples/async/get_records_async.py b/examples/async/get_records_async.py index a0ad70a8..797e60cc 100644 --- a/examples/async/get_records_async.py +++ b/examples/async/get_records_async.py @@ -1,34 +1,33 @@ import asyncio -from imednet import AsyncImednetSDK +from imednet import AsyncImednetSDK, load_config +from imednet.utils import configure_json_logging """Example script demonstrating basic usage of the AsyncImednetSDK. -This script initializes the asynchronous client with API credentials, retrieves a list of -studies, selects the first study, and then fetches and prints a few records associated with -that study. +This script initializes the asynchronous client with API credentials loaded +from environment variables, retrieves a list of studies, selects the first study, +and then fetches and prints a few records associated with that study. -Replace the "XXXXXXXXXX" placeholders with your API key, security key and optionally a -specific study key. ``base_url`` can be left ``None`` to use the default iMednet endpoint or -set to a custom URL if needed. +Ensure your environment variables (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY) are set correctly. """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - async def main() -> None: + configure_json_logging() + try: + cfg = load_config() async with AsyncImednetSDK( - api_key=api_key, - security_key=security_key, - base_url=base_url, + api_key=cfg.api_key, + security_key=cfg.security_key, + base_url=cfg.base_url, ) as sdk: studies = await sdk.studies.async_list() if not studies: print("No studies returned from API.") + return + for study in studies[:1]: study_key = study.study_key records = await sdk.records.async_list(study_key=study_key) diff --git a/examples/basic/get_codings.py b/examples/basic/get_codings.py index 39c63f00..2203814f 100644 --- a/examples/basic/get_codings.py +++ b/examples/basic/get_codings.py @@ -1,39 +1,55 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ This script demonstrates how to retrieve coding information from the iMednet API using the imednet package. -It initializes the ImednetClient with API credentials, lists the available studies, -retrieves the codings for the first study found, and prints the total count -of codings along with details for the first five codings. + +It initializes the ImednetClient with API credentials loaded from environment variables, +lists the available studies, retrieves the codings for the first study found, +and prints the total count of codings along with details for the first five codings. + Requires: - imednet installed (`pip install imednet`) -- Valid API key and security key (replace placeholders). +- Valid API key and security key set in environment variables + (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY). + Usage: -1. Replace the placeholder values for `api_key` and `security_key`. -2. Optionally set `base_url` if using a custom iMednet instance. -3. Run the script. +1. Ensure your .env file is configured correctly. +2. Run the script. + The script will output: - The total number of codings found for the first study accessed via the API key. - The Coding ID and Variable name for the first 5 codings (if available). - An error message if any issues occur during the API interaction. """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - codings = client.codings.list(study_key=study_key) - print(f"Codings for study '{study_key}': {len(codings)}") - for coding in codings[:5]: - print(f"- Coding ID: {coding.coding_id}, Variable: {coding.variable}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + codings = client.codings.list(study_key=study_key) + print(f"Codings for study '{study_key}': {len(codings)}") + for coding in codings[:5]: + print(f"- Coding ID: {coding.coding_id}, Variable: {coding.variable}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_record_revisions.py b/examples/basic/get_record_revisions.py index e4aed041..93c14889 100644 --- a/examples/basic/get_record_revisions.py +++ b/examples/basic/get_record_revisions.py @@ -1,31 +1,44 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ This script demonstrates how to retrieve record revisions for a specific study using the iMednet Python SDK. -It initializes the iMednet client with API credentials, lists available studies, -selects the first study found, and then retrieves and prints the record revisions -associated with that study. It prints the total count of revisions and details -for the first five revisions found. Basic error handling is included. -Note: Replace placeholder API keys, security keys, and potentially the base URL -with actual values before running. + +It initializes the iMednet client with API credentials loaded from environment variables, +lists available studies, selects the first study found, and then retrieves and prints +the record revisions associated with that study. It prints the total count of revisions +and details for the first five revisions found. Basic error handling is included. + +Note: Ensure your environment variables (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY) are set correctly. """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - record_revisions = client.record_revisions.list(study_key=study_key) - print(f"Record Revisions for study '{study_key}': {len(record_revisions)}") - for rev in record_revisions[:5]: - print(f"- Revision ID: {rev.record_revision_id}, Record ID: {rev.record_id}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + record_revisions = client.record_revisions.list(study_key=study_key) + print(f"Record Revisions for study '{study_key}': {len(record_revisions)}") + for rev in record_revisions[:5]: + print(f"- Revision ID: {rev.record_revision_id}, Record ID: {rev.record_id}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_records.py b/examples/basic/get_records.py index 5bfb773c..a12fb769 100644 --- a/examples/basic/get_records.py +++ b/examples/basic/get_records.py @@ -1,39 +1,51 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ Example script demonstrating basic usage of the imednet package. -This script initializes the ImednetClient with API credentials, + +This script initializes the ImednetClient with API credentials loaded from environment variables, retrieves a list of studies associated with the account, selects the first study, and then fetches and prints the first few records associated with that study. + It showcases: -- Initializing the ImednetSDK client. +- Initializing the ImednetSDK client using configuration loading. - Listing studies using `client.studies.list()`. - Listing records for a specific study using `client.records.list()`. - Basic iteration and printing of retrieved data. - Simple error handling for API calls. + Note: -Replace "XXXXXXXXXX" placeholders with your actual API key, -security key, and optionally a specific study key if you want to -target a particular study directly. The `base_url` can be left as None -to use the default iMednet API endpoint or set to a custom URL if required. +Ensure your environment variables (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY) are set correctly. """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - records = client.records.list(study_key=study_key) - print(f"Records for study '{study_key}': {len(records)}") - for record in records[:5]: - print(f"- Record ID: {record.record_id}, Subject Key: {record.subject_key}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + records = client.records.list(study_key=study_key) + print(f"Records for study '{study_key}': {len(records)}") + for record in records[:5]: + print(f"- Record ID: {record.record_id}, Subject Key: {record.subject_key}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_sites.py b/examples/basic/get_sites.py index 9147d277..b9f26d38 100644 --- a/examples/basic/get_sites.py +++ b/examples/basic/get_sites.py @@ -1,37 +1,53 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ This script demonstrates how to use the Imednet Python SDK to retrieve a list of studies and then list the sites associated with the first study found. -It initializes the ImednetClient with API credentials, fetches the list of studies -accessible with those credentials, selects the first study, and then retrieves -and prints the details (name and ID) of the first few sites belonging to that study. + +It initializes the ImednetClient with API credentials loaded from environment variables, +fetches the list of studies accessible with those credentials, selects the first study, +and then retrieves and prints the details (name and ID) of the first few sites belonging +to that study. + Requires: - An active Imednet account with API access. -- API Key and Security Key for authentication. +- API Key and Security Key set in environment variables (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY). - The `imednet` package installed (`pip install imednet`). + Usage: -1. Replace the placeholder values for `api_key`, `security_key`, and optionally `base_url`. +1. Ensure your .env file is configured correctly. 2. Run the script. It will print the total number of sites for the first study found and the details of up to the first five sites. 3. If an error occurs during the API interaction, an error message will be printed. """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - sites = client.sites.list(study_key=study_key) - print(f"Sites for study '{study_key}': {len(sites)}") - for site in sites[:5]: - print(f"- Site Name: {site.site_name}, ID: {site.site_id}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + sites = client.sites.list(study_key=study_key) + print(f"Sites for study '{study_key}': {len(sites)}") + for site in sites[:5]: + print(f"- Site Name: {site.site_name}, ID: {site.site_id}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_studies.py b/examples/basic/get_studies.py index a8cc3b00..d441628d 100644 --- a/examples/basic/get_studies.py +++ b/examples/basic/get_studies.py @@ -1,31 +1,44 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ Example script demonstrating how to list available studies using the iMednet SDK. -This script initializes the ImednetClient with the necessary API credentials -(API key and security key). It then calls the `studies.list()` method to retrieve + +This script initializes the ImednetClient with credentials loaded from environment variables +(e.g., .env file). It then calls the `studies.list()` method to retrieve a list of studies accessible with the provided credentials. Finally, it prints the name and key of the first 5 studies found. If any error occurs during the process, it prints an error message. + Prerequisites: - An active iMednet account with API access. -- Your API key and security key. +- Your API key and security key set in environment variables + (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY). + Usage: -1. Replace the placeholder values for `api_key`, `security_key`, and optionally - `base_url` with your actual credentials and environment URL. -2. Run the script. +1. Ensure your .env file is configured correctly. +2. Run the script: `python examples/basic/get_studies.py` """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - print("Studies found:") - for study in studies[:5]: - print(f"- Name: {study.study_name}, Key: {study.study_key}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + print("Studies found:") + for study in studies[:5]: + print(f"- Name: {study.study_name}, Key: {study.study_key}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_subjects.py b/examples/basic/get_subjects.py index 130f80bd..d42d5a69 100644 --- a/examples/basic/get_subjects.py +++ b/examples/basic/get_subjects.py @@ -1,38 +1,53 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ Example script demonstrating how to retrieve subjects from iMednet studies using the iMednet SDK. + This script: -1. Initializes the iMednet client with API credentials +1. Initializes the iMednet client with API credentials loaded from environment variables 2. Retrieves a list of available studies 3. For the first study, retrieves and displays information about its subjects 4. Prints the subject key and status for up to 5 subjects -Required environment variables or configurations: - - api_key (str): Your iMednet API key - - security_key (str): Your iMednet security key - - base_url (str, optional): Custom base URL for the API endpoint - - study_key (str): The study identifier + +Required environment variables: + - IMEDNET_API_KEY: Your iMednet API key + - IMEDNET_SECURITY_KEY: Your iMednet security key + - IMEDNET_BASE_URL (optional): Custom base URL for the API endpoint + Returns: None. Prints subject information to standard output. + Raises: Exception: Any errors that occur during API communication """ -api_key = "XXX" -security_key = "XXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - subjects = client.subjects.list(study_key=study_key) - print(f"Subjects for study '{study_key}': {len(subjects)}") - for subject in subjects[:5]: - print(f"- Subject Key: {subject.subject_key}, Status: {subject.subject_status}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + subjects = client.subjects.list(study_key=study_key) + print(f"Subjects for study '{study_key}': {len(subjects)}") + for subject in subjects[:5]: + print(f"- Subject Key: {subject.subject_key}, Status: {subject.subject_status}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_users.py b/examples/basic/get_users.py index 00981f65..2f7c927e 100644 --- a/examples/basic/get_users.py +++ b/examples/basic/get_users.py @@ -1,40 +1,55 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ Example script demonstrating how to retrieve users from an iMednet study using the iMednet SDK. + This script shows how to: -1. Initialize the iMednet SDK client with authentication credentials +1. Initialize the iMednet SDK client with authentication credentials from environment variables 2. List available studies 3. Get users for the first study 4. Print basic user information for up to 5 users -Required Parameters: - api_key (str): API key for authentication - security_key (str): Security key for authentication - base_url (str, optional): Custom base URL if needed, defaults to None - study_key (str): Study identifier key + +Required Environment Variables: + IMEDNET_API_KEY: API key for authentication + IMEDNET_SECURITY_KEY: Security key for authentication + IMEDNET_BASE_URL (optional): Custom base URL if needed + Returns: Prints user information to console including: - Number of users in the study - Login and name details for up to 5 users + Raises: Exception: Any errors during API communication or data retrieval """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - users = client.users.list(study_key=study_key) - print(f"Users for study '{study_key}': {len(users)}") - for user in users[:5]: - print(f"- User Login: {user.login}, Name: {user.name}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + users = client.users.list(study_key=study_key) + print(f"Users for study '{study_key}': {len(users)}") + for user in users[:5]: + print(f"- User Login: {user.login}, Name: {user.name}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_variables.py b/examples/basic/get_variables.py index d653094d..b257465f 100644 --- a/examples/basic/get_variables.py +++ b/examples/basic/get_variables.py @@ -3,27 +3,34 @@ import os from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ A script to retrieve and save study variables from the iMednet API. -This script connects to the iMednet API, retrieves a list of studies and their variables, -and saves the variable information in both JSON and CSV formats. + +This script connects to the iMednet API using credentials from environment variables, +retrieves a list of studies and their variables, and saves the variable information +in both JSON and CSV formats. + The script performs the following operations: -1. Connects to iMednet API using provided credentials +1. Connects to iMednet API using loaded credentials 2. Retrieves list of available studies 3. For the first study found: - Gets all variables for that study - Saves variables data to JSON file with full details - Saves variables data to CSV file with flattened structure - Prints first 5 variables basic information -Required Environment Variables or Constants: - api_key (str): iMednet API key - security_key (str): iMednet security key - base_url (str, optional): Custom base URL for the API - study_key (str): Study identifier key + +Required Environment Variables: + IMEDNET_API_KEY: iMednet API key + IMEDNET_SECURITY_KEY: iMednet security key + IMEDNET_BASE_URL (optional): Custom base URL for the API + Output Files: - {output_dir}/variables_{study_key}.json: JSON file containing full variable details - {output_dir}/variables_{study_key}.csv: CSV file containing flattened variable information + CSV Fields: - variableId: Unique identifier for the variable - variableName: Name of the variable @@ -38,81 +45,92 @@ - deleted: Deletion status - dateCreated: Creation timestamp - dateModified: Last modification timestamp + Raises: Exception: Any error that occurs during API communication or file operations """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - print(f"Studies found: {len(studies)}") - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - print(f"- Name: {study.study_name}, Key: {study.study_key}") - variables = client.variables.list(study_key=study.study_key) - print(f"Variables for study '{study.study_key}': {len(variables)}") - if not variables: - print("No variables returned for this study.") - else: - # Save all variables to JSON (with datetime serialization) - output_dir = os.path.join(os.path.dirname(__file__), "variables_output") - os.makedirs(output_dir, exist_ok=True) - json_path = os.path.join(output_dir, f"variables_{study.study_key}.json") - with open(json_path, "w", encoding="utf-8") as f: - json.dump( - [v.model_dump(by_alias=True) for v in variables], - f, - indent=2, - ensure_ascii=False, - default=str, - ) - # Save as CSV (flattened) - csv_path = os.path.join(output_dir, f"variables_{study.study_key}.csv") - with open(csv_path, "w", newline="", encoding="utf-8") as csvfile: - writer = csv.writer(csvfile) - writer.writerow( - [ - "variableId", - "variableName", - "formId", - "formKey", - "formName", - "label", - "variableType", - "sequence", - "revision", - "disabled", - "deleted", - "dateCreated", - "dateModified", - ] - ) - for v in variables: + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + print(f"Studies found: {len(studies)}") + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + print(f"- Name: {study.study_name}, Key: {study.study_key}") + variables = client.variables.list(study_key=study.study_key) + print(f"Variables for study '{study.study_key}': {len(variables)}") + if not variables: + print("No variables returned for this study.") + else: + # Save all variables to JSON (with datetime serialization) + output_dir = os.path.join(os.path.dirname(__file__), "variables_output") + os.makedirs(output_dir, exist_ok=True) + json_path = os.path.join(output_dir, f"variables_{study.study_key}.json") + with open(json_path, "w", encoding="utf-8") as f: + json.dump( + [v.model_dump(by_alias=True) for v in variables], + f, + indent=2, + ensure_ascii=False, + default=str, + ) + # Save as CSV (flattened) + csv_path = os.path.join(output_dir, f"variables_{study.study_key}.csv") + with open(csv_path, "w", newline="", encoding="utf-8") as csvfile: + writer = csv.writer(csvfile) writer.writerow( [ - v.variable_id, - v.variable_name, - v.form_id, - v.form_key, - v.form_name, - v.label, - v.variable_type, - v.sequence, - v.revision, - v.disabled, - v.deleted, - v.date_created, - v.date_modified, + "variableId", + "variableName", + "formId", + "formKey", + "formName", + "label", + "variableType", + "sequence", + "revision", + "disabled", + "deleted", + "dateCreated", + "dateModified", ] ) - print(f"Saved variables to: {json_path} and {csv_path}") - for variable in variables[:5]: - print(f"- Variable Name: {variable.variable_name}, ID: {variable.variable_id}") -except Exception as e: - print(f"Error: {e}") + for v in variables: + writer.writerow( + [ + v.variable_id, + v.variable_name, + v.form_id, + v.form_key, + v.form_name, + v.label, + v.variable_type, + v.sequence, + v.revision, + v.disabled, + v.deleted, + v.date_created, + v.date_modified, + ] + ) + print(f"Saved variables to: {json_path} and {csv_path}") + for variable in variables[:5]: + print(f"- Variable Name: {variable.variable_name}, ID: {variable.variable_id}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main() diff --git a/examples/basic/get_visits.py b/examples/basic/get_visits.py index 094f9aa3..1faccd82 100644 --- a/examples/basic/get_visits.py +++ b/examples/basic/get_visits.py @@ -1,37 +1,54 @@ from imednet import ImednetSDK as ImednetClient +from imednet import load_config +from imednet.utils import configure_json_logging """ Example script demonstrating how to retrieve visits from the iMednet API. + This script showcases: -1. Connecting to the iMednet API using the SDK client +1. Connecting to the iMednet API using the SDK client with credentials from environment variables. 2. Listing available studies 3. Retrieving visits for the first study 4. Displaying basic visit information + Requirements: - imednet - - Valid iMednet API credentials (api_key and security_key) + - Valid iMednet API credentials set in environment variables + (IMEDNET_API_KEY, IMEDNET_SECURITY_KEY) + Returns: Prints the number of visits for the first study and displays details of up to 5 visits including their visit IDs and subject keys. + Raises: Exception: Any error that occurs during API communication """ -api_key = "XXXXXXXXXX" -security_key = "XXXXXXXXXX" -base_url = None # Or set to your custom base URL if needed -study_key = "XXXXXXXXXX" - -try: - client = ImednetClient(api_key=api_key, security_key=security_key, base_url=base_url) - studies = client.studies.list() - if not studies: - print("No studies returned from API.") - for study in studies[:1]: - study_key = study.study_key - visits = client.visits.list(study_key=study_key) - print(f"Visits for study '{study_key}': {len(visits)}") - for visit in visits[:5]: - print(f"- Visit ID: {visit.visit_id}, Subject Key: {visit.subject_key}") -except Exception as e: - print(f"Error: {e}") + +def main(): + configure_json_logging() + + try: + cfg = load_config() + client = ImednetClient( + api_key=cfg.api_key, security_key=cfg.security_key, base_url=cfg.base_url + ) + + studies = client.studies.list() + if not studies: + print("No studies returned from API.") + return + + for study in studies[:1]: + study_key = study.study_key + visits = client.visits.list(study_key=study_key) + print(f"Visits for study '{study_key}': {len(visits)}") + for visit in visits[:5]: + print(f"- Visit ID: {visit.visit_id}, Subject Key: {visit.subject_key}") + + except Exception as e: + print(f"Error: {e}") + + +if __name__ == "__main__": + main()