accounts.py•3.06 kB
"""Account management tools for YNAB API."""
from typing import Annotated, Any
import ynab
from auth import get_api_client, get_api_configuration
def get_accounts(
budget_id: Annotated[
str,
"The ID of the budget to query. Use 'last-used' for the most recently "
"accessed budget, or provide a specific budget ID.",
] = "last-used",
) -> dict[str, Any]:
"""Get all accounts for a budget.
Retrieves all account information including checking, savings, credit cards,
and other account types. Use this tool to discover account IDs needed for
transaction queries and other account-specific operations.
Args:
budget_id: The ID of the budget to query. Use 'last-used' for the most
recently accessed budget, or provide a specific budget ID.
Returns:
dict[str, Any]: List of accounts with their IDs, names, types, balances,
and other account metadata.
Raises:
Exception: If the API call fails.
"""
configuration = get_api_configuration()
with get_api_client(configuration) as api_client:
api_instance = ynab.AccountsApi(api_client)
try:
api_response = api_instance.get_accounts(budget_id)
return api_response.data.model_dump() # type: ignore[attr-defined]
except Exception as e:
msg = f"Error fetching accounts: {e!s}"
raise Exception(msg) from e
def get_account_by_id(
account_id: Annotated[
str,
"The ID of the account to retrieve. Use get_accounts to discover "
"available account IDs.",
],
budget_id: Annotated[
str,
"The ID of the budget to query. Use 'last-used' for the most recently "
"accessed budget, or provide a specific budget ID.",
] = "last-used",
) -> dict[str, Any]:
"""Get a single account by its ID.
Retrieves detailed information for a specific account. If you don't know the
account ID, use get_accounts first to list all accounts and find the ID you need.
Args:
account_id: The ID of the account to retrieve. Use get_accounts to discover
available account IDs.
budget_id: The ID of the budget to query. Use 'last-used' for the most
recently accessed budget, or provide a specific budget ID.
Returns:
dict[str, Any]: Account data including ID, name, type, balance, and other
account details.
Raises:
Exception: If the API call fails or account not found.
"""
configuration = get_api_configuration()
with get_api_client(configuration) as api_client:
api_instance = ynab.AccountsApi(api_client)
try:
api_response = api_instance.get_account_by_id(budget_id, account_id)
account = api_response.data.account # type: ignore[attr-defined]
return account.model_dump() # type: ignore[attr-defined]
except Exception as e:
msg = f"Error fetching account: {e!s}"
raise Exception(msg) from e