Skip to content

Project Documentation

Micro YNAB - a small SDK for YNAB API

__main__

account()

Account-related commands.

Source code in src/uynab/__main__.py
@cli.group()
def account():
    """Account-related commands."""
    pass

budget()

Budget-related commands.

Source code in src/uynab/__main__.py
@cli.group()
def budget():
    """Budget-related commands."""
    pass

category()

Category-related commands.

Source code in src/uynab/__main__.py
@cli.group()
def category():
    """Category-related commands."""
    pass

cli()

YNAB CLI tool for managing budgets, accounts, and categories.

Source code in src/uynab/__main__.py
@click.group()
def cli():
    """YNAB CLI tool for managing budgets, accounts, and categories."""
    pass

format_table(data, headers=None)

Format a table from sequences of strings with optional headers, properly handling Unicode characters.

Parameters:

Name Type Description Default
data Sequence[Sequence[str]]

Sequence of sequences where each inner sequence represents a row

required
headers Sequence[str] | None

Optional sequence of column headers

None

Returns:

Type Description
str

Formatted table as string with aligned columns

Source code in src/uynab/__main__.py
def format_table(
    data: Sequence[Sequence[str]], headers: Sequence[str] | None = None
) -> str:
    """
    Format a table from sequences of strings with optional headers, properly handling Unicode characters.

    Args:
        data: Sequence of sequences where each inner sequence represents a row
        headers: Optional sequence of column headers

    Returns:
        Formatted table as string with aligned columns
    """
    if not data:
        return ""

    # Add headers to data if provided
    all_rows = [headers] + list(data) if headers else list(data)

    # Calculate column widths using display width
    num_cols = len(all_rows[0])
    col_widths = [0] * num_cols
    for row in all_rows:
        for i, cell in enumerate(row):
            col_widths[i] = max(col_widths[i], get_string_display_width(str(cell)))

    # Create the separator line
    separator = "+" + "+".join("-" * (width + 2) for width in col_widths) + "+"

    # Format each row
    def format_row(row: Sequence[str]) -> str:
        parts = []
        for cell, max_width in zip(row, col_widths):
            cell_str = str(cell)
            display_width = get_string_display_width(cell_str)
            padding = max_width - display_width
            parts.append(f" {cell_str}{' ' * padding} ")
        return "|" + "|".join(parts) + "|"

    # Build the table
    lines = [separator]

    if headers:
        lines.append(format_row(headers))
        lines.append(separator)

    # Add data rows
    for row in data:
        lines.append(format_row(row))

    lines.append(separator)

    return "\n".join(lines)

get_string_display_width(s)

Calculate the display width of a string, handling emoji and other Unicode characters.

Parameters:

Name Type Description Default
s str

Input string

required

Returns:

Type Description
int

Display width of the string

Source code in src/uynab/__main__.py
def get_string_display_width(s: str) -> int:
    """
    Calculate the display width of a string, handling emoji and other Unicode characters.

    Args:
        s: Input string

    Returns:
        Display width of the string
    """
    width = 0
    for char in s:
        east_asian_width = unicodedata.east_asian_width(char)
        width += 2 if east_asian_width in ("F", "W") else 1
    return width

get_ynab_client()

Get a YNABClient instance, prompting for an API token if not already set.

Source code in src/uynab/__main__.py
def get_ynab_client() -> YNABClient:
    """Get a YNABClient instance, prompting for an API token if not already set."""
    client = YNABClient()

    if client.api_token is None:
        token = click.prompt("Please provide a token", type=str)
        client.set_token(token)

    return client

list_accounts(budget_id)

List accounts for a specific budget.

Source code in src/uynab/__main__.py
@account.command(name="list")
@click.option(
    "--budget_id",
    required=True,
    type=UUID,
    help="ID of the budget to list accounts from",
)
def list_accounts(budget_id):
    """List accounts for a specific budget."""
    client = get_ynab_client()

    all_accounts = client.account.get_all_accounts(budget_id)
    to_print = parse_all_account_list(all_accounts)
    result = format_table(to_print, ["Account Name", "Account Balance", "Account ID"])

    click.echo(result)

list_budgets()

List all available budgets.

Source code in src/uynab/__main__.py
@budget.command(name="list")
def list_budgets():
    """List all available budgets."""
    client = get_ynab_client()

    all_budgets = client.budget.get_all_budgets()
    to_print = parse_all_budget_list(all_budgets)
    result = format_table(to_print, ["Budget Name", "Budget ID"])

    click.echo(result)

list_categories(budget_id)

List categories for a specific budget.

Source code in src/uynab/__main__.py
@category.command(name="list")
@click.option(
    "--budget_id",
    required=True,
    type=UUID,
    help="ID of the budget to list categories from.",
)
def list_categories(budget_id):
    """List categories for a specific budget."""
    client = get_ynab_client()

    all_categories = client.category.get_all_categories(budget_id)
    to_print = parse_all_category_list(all_categories)
    result = format_table(to_print, ["Category Name", "Category ID"])

    click.echo(result)

list_payees(budget_id, json_output)

List payees for a specific budget.

Source code in src/uynab/__main__.py
@payee.command(name="list")
@click.option(
    "--budget_id", required=True, type=UUID, help="ID of a budget to list payees from."
)
@click.option(
    "--json",
    "json_output",
    required=False,
    is_flag=True,
    help="Print output in JSON format",
)
def list_payees(budget_id, json_output):
    """List payees for a specific budget."""
    client = get_ynab_client()

    all_payees = client.payee.get_all_payees(budget_id)

    if json_output:
        result = json.dumps([payee.model_dump(mode="json") for payee in all_payees])
    else:
        to_print = parse_all_payee_list(all_payees)
        result = format_table(to_print, ["Payee Name", "ID", "Transfer Account ID"])

    click.echo(result)

parse_all_account_list(accounts)

Parse a list of Account objects into a list of tuples with basic account information.

Parameters:

Name Type Description Default
accounts list[Account]

A list of Account objects to be parsed.

required

Returns:

Type Description
list[tuple]

list[tuple[str, float, UUID]]: A list of tuples where each tuple contains: - account name (str) - account balance (float) - account ID (UUID)

Source code in src/uynab/__main__.py
def parse_all_account_list(accounts: list[Account]) -> list[tuple]:
    """
    Parse a list of Account objects into a list of tuples with basic account information.

    Args:
        accounts (list[Account]): A list of Account objects to be parsed.

    Returns:
        list[tuple[str, float, UUID]]: A list of tuples where each tuple contains:
            - account name (str)
            - account balance (float)
            - account ID (UUID)
    """
    return [(account.name, account.balance / 1000, account.id) for account in accounts]

parse_all_budget_list(budgets)

Convert a list of BudgetSummary objects into a list of tuples containing budget names and IDs.

Parameters:

Name Type Description Default
budgets list[BudgetSummary]

List of BudgetSummary objects to process

required

Returns:

Type Description
list[tuple]

list[tuple[str, UUID]]: List of tuples where each tuple contains (budget_name, budget_id)

Source code in src/uynab/__main__.py
def parse_all_budget_list(budgets: list[BudgetSummary]) -> list[tuple]:
    """
    Convert a list of BudgetSummary objects into a list of tuples containing budget names and IDs.

    Args:
        budgets (list[BudgetSummary]): List of BudgetSummary objects to process

    Returns:
        list[tuple[str, UUID]]: List of tuples where each tuple contains (budget_name, budget_id)
    """
    return [(budget.name, budget.id) for budget in budgets]

parse_all_category_list(categories)

Transforms a list of CategoryGroup objects into a list of tuples for display purposes.

Each tuple in the resulting list contains either: - A category group header: ("--- Category Group ---", "--- {group_name} ---") - A category entry: (category_name, category_id)

Parameters:

Name Type Description Default
categories list[CategoryGroup]

List of CategoryGroup objects to be parsed

required

Returns:

Type Description
list[tuple]

list[tuple[str, UUID]]: List of tuples containing category group headers and category entries

Source code in src/uynab/__main__.py
def parse_all_category_list(categories: list[CategoryGroup]) -> list[tuple]:
    """
    Transforms a list of CategoryGroup objects into a list of tuples for display purposes.

    Each tuple in the resulting list contains either:
    - A category group header: ("--- Category Group ---", "--- {group_name} ---")
    - A category entry: (category_name, category_id)

    Args:
        categories (list[CategoryGroup]): List of CategoryGroup objects to be parsed

    Returns:
        list[tuple[str, UUID]]: List of tuples containing category group headers and category entries
    """
    result: list[tuple[Any, Any]] = []  # just for mypy to not throw errors
    for category_group in categories:
        result.append((f"{category_group.name}:", ""))
        for category in category_group.categories:
            result.append((f" - {category.name}", category.id))
    return result

payee()

Payees-related commands.

Source code in src/uynab/__main__.py
@cli.group()
def payee():
    """Payees-related commands."""
    pass

client

YNABClient

Bases: Client

A client for interacting with the YNAB (You Need A Budget) API.

Attributes:

Name Type Description
api_token str

The API token for authenticating requests.

base_url str

The base URL for the YNAB API.

session Session

The session object for making HTTP requests.

Methods:

Name Description
request

Makes an HTTP request to the YNAB API.

Properties

account (AccountService): Returns the account service. budget (BudgetService): Returns the budget service. category (CategoryService): Returns the category service. payee (PayeeService): Returns the payee service. transaction (TransactionService): Returns the transaction service.

Source code in src/uynab/client.py
class YNABClient(Client):
    """
    A client for interacting with the YNAB (You Need A Budget) API.

    Attributes:
        api_token (str): The API token for authenticating requests.
        base_url (str): The base URL for the YNAB API.
        session (requests.Session): The session object for making HTTP requests.

    Methods:
        request(method, endpoint, params=None, data=None):
            Makes an HTTP request to the YNAB API.

    Properties:
        account (AccountService): Returns the account service.
        budget (BudgetService): Returns the budget service.
        category (CategoryService): Returns the category service.
        payee (PayeeService): Returns the payee service.
        transaction (TransactionService): Returns the transaction service.
    """

    def __init__(
        self, api_token: None | str = None, base_url: None | str = None
    ) -> None:
        self.api_token = api_token or os.getenv(Config.API_TOKEN_NAME)
        if self.api_token is None:
            load_dotenv()
            self.api_token = os.getenv(Config.API_TOKEN_NAME)
        self.base_url = base_url or Config.BASE_URL
        self.session = requests.Session()
        self.session.headers.update({"Authorization": f"Bearer {self.api_token}"})
        self._account = AccountService(self)
        self._budget = BudgetService(self)
        self._category = CategoryService(self)
        self._payee = PayeeService(self)
        self._transaction = TransactionService(self)
        self._verbose = Config.VERBOSE
        self._timeout = Config.TIMEOUT

    def request(
        self,
        method: str,
        endpoint: str,
        params: dict | None = None,
        data: Any | None = None,
    ) -> dict:
        url = f"{self.base_url}/{endpoint}"
        response = self.session.request(
            method, url, params=params, json=data, timeout=self._timeout
        )
        self._handle_response(response)
        return response.json()

    def _handle_response(self, response: requests.Response) -> None:
        if not response.ok:
            raise APIClientException(
                response.status_code, response.json().get("error", {})
            )

    def set_token(self, new_token: str) -> None:
        """Safely update the API token after the client instance is created.

        Args:
            new_token: New API token.
        """
        self.api_token = new_token
        self.session.headers.update({"Authorization": f"Bearer {self.api_token}"})

    @property
    def account(self) -> AccountService:
        return self._account

    @property
    def budget(self) -> BudgetService:
        return self._budget

    @property
    def category(self) -> CategoryService:
        return self._category

    @property
    def payee(self) -> PayeeService:
        return self._payee

    @property
    def transaction(self) -> TransactionService:
        return self._transaction

set_token(new_token)

Safely update the API token after the client instance is created.

Parameters:

Name Type Description Default
new_token str

New API token.

required
Source code in src/uynab/client.py
def set_token(self, new_token: str) -> None:
    """Safely update the API token after the client instance is created.

    Args:
        new_token: New API token.
    """
    self.api_token = new_token
    self.session.headers.update({"Authorization": f"Bearer {self.api_token}"})

model

account

Model account module

This module defines the data models for representing financial accounts and their related responses and requests.

Classes:

Name Description
Account

Represents a financial account with various attributes such as id, name, type, balance, etc.

ResponseDataAccount

Represents the response data for a single account.

ResponseAccount

Represents the response for a single account.

ResponseDataAccounts

Represents the response data for a list of accounts.

ResponseAccounts

Represents the response for a list of accounts.

RequestAccount

Represents the request data for creating or updating an account.

RequestDataAccount

Represents the request data wrapper for an account.

Account

Bases: BaseModel

Account model representing a financial account.

Attributes:

Name Type Description
id UUID

Unique identifier for the account.

name str

Name of the account.

type str

Type of the account (e.g., checking, savings).

on_budget bool

Indicates if the account is on budget.

closed bool

Indicates if the account is closed.

note Optional[str]

Additional notes about the account.

balance int

Current balance of the account.

cleared_balance int

Cleared balance of the account.

uncleared_balance int

Uncleared balance of the account.

transfer_payee_id UUID

Identifier for the transfer payee.

direct_import_linked bool

Indicates if the account is linked for direct import.

direct_import_in_error bool

Indicates if there is an error with direct import.

last_reconciled_at Optional[str]

Timestamp of the last reconciliation.

debt_original_balance Optional[int]

Original balance of the debt.

debt_interest_rates dict[datetime, int]

Interest rates of the debt over time.

debt_minimum_payments dict[datetime, int]

Minimum payments of the debt over time.

debt_escrow_amounts dict[datetime, int]

Escrow amounts of the debt over time.

deleted bool

Indicates if the account is deleted.

Source code in src/uynab/model/account.py
class Account(BaseModel):
    """
    Account model representing a financial account.

    Attributes:
        id (UUID): Unique identifier for the account.
        name (str): Name of the account.
        type (str): Type of the account (e.g., checking, savings).
        on_budget (bool): Indicates if the account is on budget.
        closed (bool): Indicates if the account is closed.
        note (Optional[str]): Additional notes about the account.
        balance (int): Current balance of the account.
        cleared_balance (int): Cleared balance of the account.
        uncleared_balance (int): Uncleared balance of the account.
        transfer_payee_id (UUID): Identifier for the transfer payee.
        direct_import_linked (bool): Indicates if the account is linked for direct import.
        direct_import_in_error (bool): Indicates if there is an error with direct import.
        last_reconciled_at (Optional[str]): Timestamp of the last reconciliation.
        debt_original_balance (Optional[int]): Original balance of the debt.
        debt_interest_rates (dict[datetime, int]): Interest rates of the debt over time.
        debt_minimum_payments (dict[datetime, int]): Minimum payments of the debt over time.
        debt_escrow_amounts (dict[datetime, int]): Escrow amounts of the debt over time.
        deleted (bool): Indicates if the account is deleted.
    """

    id: UUID
    name: str
    type: str
    on_budget: bool
    closed: bool
    note: Optional[str] = None
    balance: int
    cleared_balance: int
    uncleared_balance: int
    transfer_payee_id: UUID
    direct_import_linked: bool
    direct_import_in_error: bool
    last_reconciled_at: Optional[str] = None
    debt_original_balance: Optional[int] = None
    debt_interest_rates: dict[datetime, int]
    debt_minimum_payments: dict[datetime, int]
    debt_escrow_amounts: dict[datetime, int]
    deleted: bool

RequestAccount

Bases: BaseModel

RequestAccount model representing an account request. Attributes: name (str): The name of the account. type (str): The type of the account. balance (int): The balance of the account.

Source code in src/uynab/model/account.py
class RequestAccount(BaseModel):
    """
    RequestAccount model representing an account request.
    Attributes:
        name (str): The name of the account.
        type (str): The type of the account.
        balance (int): The balance of the account.
    """

    name: str
    type: str
    balance: int

RequestDataAccount

Bases: BaseModel

RequestDataAccount is a data model that represents the request data for an account.

Attributes:

Name Type Description
account RequestAccount

An instance of RequestAccount containing the account details.

Source code in src/uynab/model/account.py
class RequestDataAccount(BaseModel):
    """
    RequestDataAccount is a data model that represents the request data for an account.

    Attributes:
        account (RequestAccount): An instance of RequestAccount containing the account details.
    """

    account: RequestAccount

ResponseAccount

Bases: BaseModel

ResponseAccount is a model representing the response for an account.

Source code in src/uynab/model/account.py
class ResponseAccount(BaseModel):
    """ResponseAccount is a model representing the response for an account."""

    data: ResponseDataAccount

ResponseAccounts

Bases: BaseModel

ResponseAccounts is a model representing the response for a list of accounts.

Source code in src/uynab/model/account.py
class ResponseAccounts(BaseModel):
    """ResponseAccounts is a model representing the response for a list of accounts."""

    data: ResponseDataAccounts

ResponseDataAccount

Bases: BaseModel

ResponseDataAccount is a model representing the response data for an account.

Source code in src/uynab/model/account.py
class ResponseDataAccount(BaseModel):
    """ResponseDataAccount is a model representing the response data for an account."""

    account: Account

ResponseDataAccounts

Bases: BaseModel

ResponseDataAccounts is a model representing the response data for a list of accounts.

Source code in src/uynab/model/account.py
class ResponseDataAccounts(BaseModel):
    """ResponseDataAccounts is a model representing the response data for a list of accounts."""

    accounts: list[Account]
    server_knowledge: int

budget

Model budget module.

This module defines the models related to budgets in the application using Pydantic BaseModel.

Classes:

Name Description
Budget

Represents a budget with various attributes such as accounts, payees, categories, and transactions.

ResponseDataBudget

Represents the response data for a single budget.

ResponseBudget

Represents the response structure for a single budget.

ResponseDataBudgets

Represents the response data for multiple budgets.

ResponseBudgets

Represents the response structure for multiple budgets.

BudgetSettings

Represents the settings for a budget, including date and currency formats.

ResponseDataBudgetSettings

Represents the response data for budget settings.

ResponseBudgetSettings

Represents the response structure for budget settings.

Budget

Bases: BaseModel

A class representing a budget in the application.

Attributes:

Name Type Description
id UUID

The unique identifier of the budget.

name str

The name of the budget.

last_modified_on datetime

The date and time when the budget was last modified.

first_month datetime

The first month of the budget.

last_month datetime

The last month of the budget.

date_format DateFormat

The date format used in the budget.

currency_format CurrencyFormat

The currency format used in the budget.

accounts list[Account]

A list of accounts associated with the budget.

payees list[Payee]

A list of payees associated with the budget.

payee_locations list[dict]

A list of payee locations associated with the budget.

category_groups list[CategoryGroup]

A list of category groups in the budget.

categories list[Category]

A list of categories in the budget.

months list[Month]

A list of months in the budget.

transactions list[TransactionSummary]

A list of transactions in the budget.

subtransactions list[Subtransaction]

A list of subtransactions in the budget.

scheduled_transactions list[dict]

A list of scheduled transactions in the budget.

scheduled_subtransactions list[dict]

A list of scheduled subtransactions in the budget.

Source code in src/uynab/model/budget.py
class Budget(BaseModel):
    """
    A class representing a budget in the application.

    Attributes:
        id (UUID): The unique identifier of the budget.
        name (str): The name of the budget.
        last_modified_on (datetime): The date and time when the budget was last modified.
        first_month (datetime): The first month of the budget.
        last_month (datetime): The last month of the budget.
        date_format (DateFormat): The date format used in the budget.
        currency_format (CurrencyFormat): The currency format used in the budget.
        accounts (list[Account]): A list of accounts associated with the budget.
        payees (list[Payee]): A list of payees associated with the budget.
        payee_locations (list[dict]): A list of payee locations associated with the budget.
        category_groups (list[CategoryGroup]): A list of category groups in the budget.
        categories (list[Category]): A list of categories in the budget.
        months (list[Month]): A list of months in the budget.
        transactions (list[TransactionSummary]): A list of transactions in the budget.
        subtransactions (list[Subtransaction]): A list of subtransactions in the budget.
        scheduled_transactions (list[dict]): A list of scheduled transactions in the budget.
        scheduled_subtransactions (list[dict]): A list of scheduled subtransactions in the budget.
    """

    id: UUID
    name: str
    last_modified_on: datetime
    first_month: datetime
    last_month: datetime
    date_format: DateFormat
    currency_format: CurrencyFormat
    accounts: list[Account]
    payees: list[Payee]
    payee_locations: list[dict]
    category_groups: list[CategoryGroup]
    categories: list[Category]
    months: list[Month]
    transactions: list[TransactionSummary]
    subtransactions: list[Subtransaction]
    scheduled_transactions: list[dict]
    scheduled_subtransactions: list[dict]

BudgetSettings

Bases: BaseModel

A class used to represent the settings for a budget.

Attributes:

Name Type Description
date_format dict

A dictionary representing the format for dates.

currency_format dict

A dictionary representing the format for currency.

Source code in src/uynab/model/budget.py
class BudgetSettings(BaseModel):
    """A class used to represent the settings for a budget.

    Attributes:
        date_format (dict): A dictionary representing the format for dates.
        currency_format (dict): A dictionary representing the format for currency.
    """

    date_format: DateFormat
    currency_format: CurrencyFormat

BudgetSummary

Bases: BaseModel

BudgetSummary model representing a summary of a budget. Attributes: id (UUID): Unique identifier for the budget. name (str): Name of the budget. last_modified_on (datetime): Timestamp of the last modification. first_month (datetime): The first month of the budget. last_month (datetime): The last month of the budget. date_format (Optional[DateFormat]): The date format used in the budget. currency_format (Optional[CurrencyFormat]): The currency format used in the budget.

Source code in src/uynab/model/budget.py
class BudgetSummary(BaseModel):
    """
    BudgetSummary model representing a summary of a budget.
    Attributes:
        id (UUID): Unique identifier for the budget.
        name (str): Name of the budget.
        last_modified_on (datetime): Timestamp of the last modification.
        first_month (datetime): The first month of the budget.
        last_month (datetime): The last month of the budget.
        date_format (Optional[DateFormat]): The date format used in the budget.
        currency_format (Optional[CurrencyFormat]): The currency format used in the budget.
    """

    id: UUID
    name: str
    last_modified_on: datetime
    first_month: datetime
    last_month: datetime
    date_format: Optional[DateFormat] = None
    currency_format: Optional[CurrencyFormat] = None

ResponseBudget

Bases: BaseModel

ResponseBudget is a model representing the response structure for a budget.

Attributes:

Name Type Description
data ResponseDataBudget

The data attribute containing the budget details.

Source code in src/uynab/model/budget.py
class ResponseBudget(BaseModel):
    """
    ResponseBudget is a model representing the response structure for a budget.

    Attributes:
        data (ResponseDataBudget): The data attribute containing the budget details.
    """

    data: ResponseDataBudget

ResponseBudgetSettings

Bases: BaseModel

ResponseBudgetSettings is a model representing the settings of a budget response.

Attributes:

Name Type Description
data ResponseDataBudgetSettings

The data containing the budget settings.

Source code in src/uynab/model/budget.py
class ResponseBudgetSettings(BaseModel):
    """
    ResponseBudgetSettings is a model representing the settings of a budget response.

    Attributes:
        data (ResponseDataBudgetSettings): The data containing the budget settings.
    """

    data: ResponseDataBudgetSettings

ResponseBudgets

Bases: BaseModel

ResponseBudgets is a model representing the response structure for budget-related data.

Attributes:

Name Type Description
data ResponseDataBudgets

The data attribute containing budget-related information.

Source code in src/uynab/model/budget.py
class ResponseBudgets(BaseModel):
    """
    ResponseBudgets is a model representing the response structure for budget-related data.

    Attributes:
        data (ResponseDataBudgets): The data attribute containing budget-related information.
    """

    data: ResponseDataBudgets

ResponseDataBudget

Bases: BaseModel

ResponseDataBudget is a model representing the response data for a budget.

Attributes:

Name Type Description
budget Budget

The budget data.

server_knowledge int

The server knowledge value.

Source code in src/uynab/model/budget.py
class ResponseDataBudget(BaseModel):
    """
    ResponseDataBudget is a model representing the response data for a budget.

    Attributes:
        budget (Budget): The budget data.
        server_knowledge (int): The server knowledge value.
    """

    budget: Budget
    server_knowledge: int

ResponseDataBudgetSettings

Bases: BaseModel

ResponseDataBudgetSettings is a model representing the settings of a budget response.

Attributes:

Name Type Description
settings BudgetSettings

The settings of the budget.

Source code in src/uynab/model/budget.py
class ResponseDataBudgetSettings(BaseModel):
    """
    ResponseDataBudgetSettings is a model representing the settings of a budget response.

    Attributes:
        settings (BudgetSettings): The settings of the budget.
    """

    settings: BudgetSettings

ResponseDataBudgets

Bases: BaseModel

ResponseDataBudgets is a model representing the response data for budgets.

Attributes:

Name Type Description
budgets list[BudgetSummary]

A list of Budget objects.

default_budget Optional[BudgetSummary]

The default Budget object.

Source code in src/uynab/model/budget.py
class ResponseDataBudgets(BaseModel):
    """
    ResponseDataBudgets is a model representing the response data for budgets.

    Attributes:
        budgets (list[BudgetSummary]): A list of Budget objects.
        default_budget (Optional[BudgetSummary]): The default Budget object.
    """

    budgets: list[BudgetSummary]
    default_budget: Optional[BudgetSummary] = None

category

Model category module.

This module defines models for representing financial categories and category groups within a budgeting application.

Classes:

Name Description
Category

Represents a financial category with various attributes such as id, name, budgeted amount, and goal details.

ResponseDataCategory

Represents the response data for a single category.

ResponseCategory

Represents the response structure for a category.

CategoryGroup

Represents a group of categories with attributes such as id, name, and a list of categories.

ResponseDataCategoryGroup

Represents the response data for a category group, including server knowledge.

ResponseCategoryGroup

Represents the response structure for a category group.

Each class uses Pydantic's BaseModel to enforce type validation and provide serialization/deserialization capabilities.

Category

Bases: BaseModel

Category model representing a financial category.

Attributes:

Name Type Description
id UUID

Unique identifier for the category.

category_group_id UUID

Identifier for the category group.

category_group_name str

Name of the category group.

name str

Name of the category.

hidden bool

Indicates if the category is hidden.

original_category_group_id Optional[UUID]

Original identifier for the category group, if any.

note Optional[str]

Additional notes for the category.

budgeted int

Budgeted amount for the category.

activity int

Activity amount for the category.

balance int

Balance amount for the category.

goal_type Optional[Literal['TB', 'TBD', 'MF', 'NEED', 'DEBT']]

Type of goal associated with the category.

goal_needs_whole_amount Optional[bool]

Indicates if the goal needs the whole amount.

goal_day Optional[int]

Day associated with the goal.

goal_cadence Optional[int]

Cadence of the goal.

goal_cadence_frequency Optional[int]

Frequency of the goal cadence.

goal_creation_month Optional[str]

Month when the goal was created.

goal_target Optional[int]

Target amount for the goal.

goal_target_month Optional[str]

Target month for the goal.

goal_percentage_complete Optional[int]

Percentage of goal completion.

goal_months_to_budget Optional[int]

Number of months to budget for the goal.

goal_under_funded Optional[int]

Amount underfunded for the goal.

goal_overall_funded Optional[int]

Overall funded amount for the goal.

goal_overall_left Optional[int]

Overall amount left for the goal.

deleted bool

Indicates if the category is deleted.

Source code in src/uynab/model/category.py
class Category(BaseModel):
    """
    Category model representing a financial category.

    Attributes:
        id (UUID): Unique identifier for the category.
        category_group_id (UUID): Identifier for the category group.
        category_group_name (str): Name of the category group.
        name (str): Name of the category.
        hidden (bool): Indicates if the category is hidden.
        original_category_group_id (Optional[UUID]): Original identifier for the category group, if any.
        note (Optional[str]): Additional notes for the category.
        budgeted (int): Budgeted amount for the category.
        activity (int): Activity amount for the category.
        balance (int): Balance amount for the category.
        goal_type (Optional[Literal["TB", "TBD", "MF", "NEED", "DEBT"]]): Type of goal associated with the category.
        goal_needs_whole_amount (Optional[bool]): Indicates if the goal needs the whole amount.
        goal_day (Optional[int]): Day associated with the goal.
        goal_cadence (Optional[int]): Cadence of the goal.
        goal_cadence_frequency (Optional[int]): Frequency of the goal cadence.
        goal_creation_month (Optional[str]): Month when the goal was created.
        goal_target (Optional[int]): Target amount for the goal.
        goal_target_month (Optional[str]): Target month for the goal.
        goal_percentage_complete (Optional[int]): Percentage of goal completion.
        goal_months_to_budget (Optional[int]): Number of months to budget for the goal.
        goal_under_funded (Optional[int]): Amount underfunded for the goal.
        goal_overall_funded (Optional[int]): Overall funded amount for the goal.
        goal_overall_left (Optional[int]): Overall amount left for the goal.
        deleted (bool): Indicates if the category is deleted.
    """

    id: UUID
    category_group_id: UUID
    category_group_name: str
    name: str
    hidden: bool
    original_category_group_id: Optional[UUID] = None
    note: Optional[str] = None
    budgeted: int
    activity: int
    balance: int
    goal_type: Optional[Literal["TB", "TBD", "MF", "NEED", "DEBT"]] = None
    goal_needs_whole_amount: Optional[bool] = None
    goal_day: Optional[int] = None
    goal_cadence: Optional[int] = None
    goal_cadence_frequency: Optional[int] = None
    goal_creation_month: Optional[str] = None
    goal_target: Optional[int] = None
    goal_target_month: Optional[str] = None
    goal_percentage_complete: Optional[int] = None
    goal_months_to_budget: Optional[int] = None
    goal_under_funded: Optional[int] = None
    goal_overall_funded: Optional[int] = None
    goal_overall_left: Optional[int] = None
    deleted: bool

CategoryGroup

Bases: BaseModel

Represents a group of categories in the budgeting application.

Attributes:

Name Type Description
id UUID

The unique identifier of the category group.

name str

The name of the category group.

hidden bool

Indicates whether the category group is hidden.

deleted bool

Indicates whether the category group is deleted.

categories list[Category]

A list of categories that belong to this group.

Source code in src/uynab/model/category.py
class CategoryGroup(BaseModel):
    """
    Represents a group of categories in the budgeting application.

    Attributes:
        id (UUID): The unique identifier of the category group.
        name (str): The name of the category group.
        hidden (bool): Indicates whether the category group is hidden.
        deleted (bool): Indicates whether the category group is deleted.
        categories (list[Category]): A list of categories that belong to this group.
    """

    id: UUID
    name: str
    hidden: bool
    deleted: bool
    categories: list[Category]

ResponseCategory

Bases: BaseModel

ResponseCategory is a model representing the response structure for a category.

Attributes:

Name Type Description
data ResponseDataCategory

The data attribute containing the category details.

Source code in src/uynab/model/category.py
class ResponseCategory(BaseModel):
    """
    ResponseCategory is a model representing the response structure for a category.

    Attributes:
        data (ResponseDataCategory): The data attribute containing the category details.
    """

    data: ResponseDataCategory

ResponseCategoryGroup

Bases: BaseModel

ResponseCategoryGroup represents a category group in the response model.

Attributes:

Name Type Description
data ResponseDataCategoryGroup

The data associated with the category group.

Source code in src/uynab/model/category.py
class ResponseCategoryGroup(BaseModel):
    """
    ResponseCategoryGroup represents a category group in the response model.

    Attributes:
        data (ResponseDataCategoryGroup): The data associated with the category group.
    """

    data: ResponseDataCategoryGroup

ResponseDataCategory

Bases: BaseModel

ResponseDataCategory is a model that represents the response data for a category.

Attributes:

Name Type Description
category Category

The category object associated with the response.

Source code in src/uynab/model/category.py
class ResponseDataCategory(BaseModel):
    """
    ResponseDataCategory is a model that represents the response data for a category.

    Attributes:
        category (Category): The category object associated with the response.
    """

    category: Category

ResponseDataCategoryGroup

Bases: BaseModel

ResponseDataCategoryGroup represents the response data for a category group.

Attributes:

Name Type Description
category_groups list[CategoryGroup]

A list of category groups.

server_knowledge int

The server knowledge value.

Source code in src/uynab/model/category.py
class ResponseDataCategoryGroup(BaseModel):
    """
    ResponseDataCategoryGroup represents the response data for a category group.

    Attributes:
        category_groups (list[CategoryGroup]): A list of category groups.
        server_knowledge (int): The server knowledge value.
    """

    category_groups: list[CategoryGroup]
    server_knowledge: int

payee

Model payee module.

This module contains Pydantic models for validating and managing data structures related to payees in the YNAB API. These models ensure consistency when working with API request and response payloads.

Classes:

Name Description
- Payee

Represents a single payee object.

- ResponseDataPayee

Wraps a single payee in the response's data field.

- ResponsePayee

Represents the full API response for a single payee.

- ResponseDataPayees

Wraps a list of payees and server knowledge metadata.

- ResponsePayees

Represents the full API response for multiple payees.

- RequestPayee

Represents the structure of a single payee in request payloads.

- RequestDataPayee

Wraps the payee field in request payloads.

Example Usage
from uynab.model.payee import Payee, ResponsePayee

# Validating a single payee response
response_data = {
    "data": {
        "payee": {
            "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "name": "Test Payee",
            "transfer_account_id": None,
            "deleted": False
        }
    }
}
validated_response = ResponsePayee(**response_data)
print(validated_response.data.payee.name)  # Output: Test Payee

Payee

Bases: BaseModel

Represents a payee in the YNAB system.

Attributes:

Name Type Description
id UUID

The unique identifier of the payee.

name str

The name of the payee.

transfer_account_id Optional[str]

The ID of the associated transfer account, if applicable.

deleted bool

Indicates whether the payee has been deleted.

Source code in src/uynab/model/payee.py
class Payee(BaseModel):
    """
    Represents a payee in the YNAB system.

    Attributes:
        id (UUID): The unique identifier of the payee.
        name (str): The name of the payee.
        transfer_account_id (Optional[str]): The ID of the associated transfer account, if applicable.
        deleted (bool): Indicates whether the payee has been deleted.
    """

    id: UUID
    name: str
    transfer_account_id: Optional[UUID] = None
    deleted: bool

RequestDataPayee

Bases: BaseModel

Represents the structure of the payee field in a request payload.

Attributes:

Name Type Description
payee RequestPayee

The wrapper for the payee data in the request payload.

Source code in src/uynab/model/payee.py
class RequestDataPayee(BaseModel):
    """
    Represents the structure of the `payee` field in a request payload.

    Attributes:
        payee (RequestPayee): The wrapper for the payee data in the request payload.
    """

    payee: RequestPayee

RequestPayee

Bases: BaseModel

Represents the structure of a request payload to update a payee.

Attributes:

Name Type Description
name str

The new name of the payee.

Source code in src/uynab/model/payee.py
class RequestPayee(BaseModel):
    """
    Represents the structure of a request payload to update a payee.

    Attributes:
        name (str): The new name of the payee.
    """

    name: str

ResponseDataPayee

Bases: BaseModel

Represents the structure of the data field in a response containing a single payee.

Attributes:

Name Type Description
payee Payee

The payee object returned in the response.

Source code in src/uynab/model/payee.py
class ResponseDataPayee(BaseModel):
    """
    Represents the structure of the `data` field in a response containing a single payee.

    Attributes:
        payee (Payee): The payee object returned in the response.
    """

    payee: Payee

ResponseDataPayees

Bases: BaseModel

Represents the structure of the data field in a response containing multiple payees.

Attributes:

Name Type Description
payees list[Payee]

A list of payee objects.

server_knowledge int

A server-provided knowledge value for caching or synchronization.

Source code in src/uynab/model/payee.py
class ResponseDataPayees(BaseModel):
    """
    Represents the structure of the `data` field in a response containing multiple payees.

    Attributes:
        payees (list[Payee]): A list of payee objects.
        server_knowledge (int): A server-provided knowledge value for caching or synchronization.
    """

    payees: list[Payee]
    server_knowledge: int

ResponsePayee

Bases: BaseModel

Represents the full API response containing a single payee.

Attributes:

Name Type Description
data ResponseDataPayee

The wrapper for the payee data in the response.

Source code in src/uynab/model/payee.py
class ResponsePayee(BaseModel):
    """
    Represents the full API response containing a single payee.

    Attributes:
        data (ResponseDataPayee): The wrapper for the payee data in the response.
    """

    data: ResponseDataPayee

ResponsePayees

Bases: BaseModel

Represents the full API response containing multiple payees.

Attributes:

Name Type Description
data ResponseDataPayees

The wrapper for the list of payee data and metadata in the response.

Source code in src/uynab/model/payee.py
class ResponsePayees(BaseModel):
    """
    Represents the full API response containing multiple payees.

    Attributes:
        data (ResponseDataPayees): The wrapper for the list of payee data and metadata in the response.
    """

    data: ResponseDataPayees

transaction

Model transaction module

This module defines various Pydantic models for representing financial transactions and their related data.

Classes:

Name Description
Subtransaction

Represents a subtransaction within a transaction.

SaveSubTransaction

Represents a sub-transaction to be saved.

TransactionDetail

Represents the details of a financial transaction.

TransactionSummary

Represents a summary of a financial transaction.

NewTransaction

Represents a new financial transaction.

ResponseDataTransaction

Represents the response data for a transaction.

ResponseTransaction

Represents a transaction response.

ResponseDataTransactions

Represents the response data for multiple transactions.

ResponseTransactions

Represents the response containing transaction data.

ResponseDataSaveTransactions

Represents the response data for saving transactions.

ResponseSaveTransactions

Represents the response received after saving transactions.

NewTransaction

Bases: BaseModel

NewTransaction model representing a financial transaction.

Attributes:

Name Type Description
account_id UUID

The unique identifier for the account.

date date

The date of the transaction.

amount int

The amount of the transaction in the smallest currency unit (e.g., cents).

payee_id Optional[UUID]

The unique identifier for the payee (optional).

payee_name Optional[str]

The name of the payee (optional).

category_id Optional[UUID]

The unique identifier for the category (optional).

memo Optional[str]

A memo or note associated with the transaction (optional).

cleared Literal['cleared', 'uncleared', 'reconciled']

The cleared status of the transaction.

approved bool

Whether the transaction is approved.

flag_color Optional[str]

The color of the flag associated with the transaction (optional).

import_id Optional[str]

The import identifier for the transaction (optional).

subtransactions list[SaveSubTransaction]

A list of subtransactions associated with this transaction.

Source code in src/uynab/model/transaction.py
class NewTransaction(BaseModel):
    """
    NewTransaction model representing a financial transaction.

    Attributes:
        account_id (UUID): The unique identifier for the account.
        date (date): The date of the transaction.
        amount (int): The amount of the transaction in the smallest currency unit (e.g., cents).
        payee_id (Optional[UUID]): The unique identifier for the payee (optional).
        payee_name (Optional[str]): The name of the payee (optional).
        category_id (Optional[UUID]): The unique identifier for the category (optional).
        memo (Optional[str]): A memo or note associated with the transaction (optional).
        cleared (Literal["cleared", "uncleared", "reconciled"]): The cleared status of the transaction.
        approved (bool): Whether the transaction is approved.
        flag_color (Optional[str]): The color of the flag associated with the transaction (optional).
        import_id (Optional[str]): The import identifier for the transaction (optional).
        subtransactions (list[SaveSubTransaction]): A list of subtransactions associated with this transaction.
    """

    account_id: UUID
    date: date
    amount: int
    payee_id: Optional[UUID] = None
    payee_name: Optional[str] = None
    category_id: Optional[UUID] = None
    memo: Optional[str] = None
    cleared: Literal["cleared", "uncleared", "reconciled"]
    approved: bool
    flag_color: Optional[FlagColor] = None
    import_id: Optional[str] = None
    subtransactions: list[SaveSubTransaction]

ResponseDataSaveTransactions

Bases: BaseModel

ResponseDataSaveTransactions is a model representing the response data for saving transactions.

Attributes:

Name Type Description
transaction_ids list[str]

A list of transaction IDs.

transactions list[TransactionDetail]

A list of transaction details.

duplicate_import_ids list[str]

A list of duplicate import IDs.

server_knowledge int

The server knowledge value.

Source code in src/uynab/model/transaction.py
class ResponseDataSaveTransactions(BaseModel):
    """
    ResponseDataSaveTransactions is a model representing the response data for saving transactions.

    Attributes:
        transaction_ids (list[str]): A list of transaction IDs.
        transactions (list[TransactionDetail]): A list of transaction details.
        duplicate_import_ids (list[str]): A list of duplicate import IDs.
        server_knowledge (int): The server knowledge value.
    """

    transaction_ids: list[str]
    transactions: list[TransactionDetail]
    duplicate_import_ids: list[str]
    server_knowledge: int

ResponseDataTransaction

Bases: BaseModel

ResponseDataTransaction is a model that represents the response data for a transaction.

Attributes:

Name Type Description
transaction TransactionDetail

Detailed information about the transaction.

Source code in src/uynab/model/transaction.py
class ResponseDataTransaction(BaseModel):
    """
    ResponseDataTransaction is a model that represents the response data for a transaction.

    Attributes:
        transaction (TransactionDetail): Detailed information about the transaction.
    """

    transaction: TransactionDetail

ResponseDataTransactions

Bases: BaseModel

ResponseDataTransactions is a model representing the response data for transactions.

Attributes:

Name Type Description
transactions list[TransactionDetail]

A list of transaction details.

server_knowledge int

An integer representing the server's knowledge of the current state.

Source code in src/uynab/model/transaction.py
class ResponseDataTransactions(BaseModel):
    """
    ResponseDataTransactions is a model representing the response data for transactions.

    Attributes:
        transactions (list[TransactionDetail]): A list of transaction details.
        server_knowledge (int): An integer representing the server's knowledge of the current state.
    """

    transactions: list[TransactionDetail]
    server_knowledge: int

ResponseSaveTransactions

Bases: BaseModel

ResponseSaveTransactions is a model representing the response received after saving transactions.

Attributes:

Name Type Description
data ResponseDataSaveTransactions

The data related to the saved transactions.

Source code in src/uynab/model/transaction.py
class ResponseSaveTransactions(BaseModel):
    """
    ResponseSaveTransactions is a model representing the response received after saving transactions.

    Attributes:
        data (ResponseDataSaveTransactions): The data related to the saved transactions.
    """

    data: ResponseDataSaveTransactions

ResponseTransaction

Bases: BaseModel

ResponseTransaction is a model representing a transaction response.

Attributes:

Name Type Description
data ResponseDataTransaction

The data associated with the transaction response.

Source code in src/uynab/model/transaction.py
class ResponseTransaction(BaseModel):
    """
    ResponseTransaction is a model representing a transaction response.

    Attributes:
        data (ResponseDataTransaction): The data associated with the transaction response.
    """

    data: ResponseDataTransaction

ResponseTransactions

Bases: BaseModel

ResponseTransactions is a model that represents the response containing transaction data.

Attributes:

Name Type Description
data ResponseDataTransactions

The transaction data included in the response.

Source code in src/uynab/model/transaction.py
class ResponseTransactions(BaseModel):
    """
    ResponseTransactions is a model that represents the response containing transaction data.

    Attributes:
        data (ResponseDataTransactions): The transaction data included in the response.
    """

    data: ResponseDataTransactions

SaveSubTransaction

Bases: BaseModel

Represents a sub-transaction to be saved.

Attributes:

Name Type Description
amount int

The amount of the sub-transaction.

payee_id Optional[UUID]

The ID of the payee associated with the sub-transaction.

payee_name Optional[str]

The name of the payee associated with the sub-transaction.

category_id Optional[UUID]

The ID of the category associated with the sub-transaction.

memo Optional[str]

An optional memo for the sub-transaction.

Source code in src/uynab/model/transaction.py
class SaveSubTransaction(BaseModel):
    """
    Represents a sub-transaction to be saved.

    Attributes:
        amount (int): The amount of the sub-transaction.
        payee_id (Optional[UUID]): The ID of the payee associated with the sub-transaction.
        payee_name (Optional[str]): The name of the payee associated with the sub-transaction.
        category_id (Optional[UUID]): The ID of the category associated with the sub-transaction.
        memo (Optional[str]): An optional memo for the sub-transaction.
    """

    amount: int
    payee_id: Optional[UUID] = None
    payee_name: Optional[str] = None
    category_id: Optional[UUID] = None
    memo: Optional[str] = None

Subtransaction

Bases: BaseModel

Represents a subtransaction within a transaction.

Attributes:

Name Type Description
id UUID

Unique identifier for the subtransaction.

transaction_id UUID

Unique identifier for the parent transaction.

amount int

The amount of the subtransaction.

memo Optional[str]

An optional memo for the subtransaction.

payee_id Optional[UUID]

Optional unique identifier for the payee.

payee_name Optional[str]

Optional name of the payee.

category_id Optional[UUID]

Optional unique identifier for the category.

category_name Optional[str]

Optional name of the category.

transfer_account_id Optional[UUID]

Optional unique identifier for the transfer account.

transfer_transaction_id Optional[UUID]

Optional unique identifier for the transfer transaction.

deleted bool

Indicates whether the subtransaction is deleted.

Source code in src/uynab/model/transaction.py
class Subtransaction(BaseModel):
    """
    Represents a subtransaction within a transaction.

    Attributes:
        id (UUID): Unique identifier for the subtransaction.
        transaction_id (UUID): Unique identifier for the parent transaction.
        amount (int): The amount of the subtransaction.
        memo (Optional[str]): An optional memo for the subtransaction.
        payee_id (Optional[UUID]): Optional unique identifier for the payee.
        payee_name (Optional[str]): Optional name of the payee.
        category_id (Optional[UUID]): Optional unique identifier for the category.
        category_name (Optional[str]): Optional name of the category.
        transfer_account_id (Optional[UUID]): Optional unique identifier for the transfer account.
        transfer_transaction_id (Optional[UUID]): Optional unique identifier for the transfer transaction.
        deleted (bool): Indicates whether the subtransaction is deleted.
    """

    id: UUID
    transaction_id: UUID
    amount: int
    memo: Optional[str] = None
    payee_id: Optional[UUID] = None
    payee_name: Optional[str] = None
    category_id: Optional[UUID] = None
    category_name: Optional[str] = None
    transfer_account_id: Optional[UUID] = None
    transfer_transaction_id: Optional[UUID] = None
    deleted: bool

TransactionDetail

Bases: BaseModel

TransactionDetail represents the details of a financial transaction.

Attributes:

Name Type Description
id str

Unique identifier for the transaction.

date date

The date of the transaction.

amount int

The amount of the transaction in the smallest currency unit (e.g., cents).

memo Optional[str]

A memo or note associated with the transaction.

cleared Literal['cleared', 'uncleared', 'reconciled']

The cleared status of the transaction.

approved bool

Indicates whether the transaction is approved.

flag_color Optional[FlagColor]

The color of the flag associated with the transaction.

flag_name Optional[str]

The name of the flag associated with the transaction.

account_id UUID

The unique identifier of the account associated with the transaction.

payee_id Optional[UUID]

The unique identifier of the payee associated with the transaction.

category_id Optional[UUID]

The unique identifier of the category associated with the transaction.

transfer_account_id Optional[UUID]

The unique identifier of the transfer account associated with the transaction.

transfer_transaction_id Optional[str]

The unique identifier of the transfer transaction associated with the transaction.

matched_transaction_id Optional[str]

The unique identifier of the matched transaction associated with the transaction.

import_id Optional[UUID]

The unique identifier of the import associated with the transaction.

import_payee_name Optional[str]

The name of the payee as imported.

import_payee_name_original Optional[str]

The original name of the payee as imported.

debt_transaction_type Optional[str]

The type of debt transaction.

deleted bool

Indicates whether the transaction is deleted.

account_name str

The name of the account associated with the transaction.

payee_name Optional[str]

The name of the payee associated with the transaction.

category_name Optional[str]

The name of the category associated with the transaction.

subtransactions list[Subtransaction]

A list of subtransactions associated with the transaction.

Source code in src/uynab/model/transaction.py
class TransactionDetail(BaseModel):
    """
    TransactionDetail represents the details of a financial transaction.

    Attributes:
        id (str): Unique identifier for the transaction.
        date (date): The date of the transaction.
        amount (int): The amount of the transaction in the smallest currency unit (e.g., cents).
        memo (Optional[str]): A memo or note associated with the transaction.
        cleared (Literal["cleared", "uncleared", "reconciled"]): The cleared status of the transaction.
        approved (bool): Indicates whether the transaction is approved.
        flag_color (Optional[FlagColor]): The color of the flag associated with the transaction.
        flag_name (Optional[str]): The name of the flag associated with the transaction.
        account_id (UUID): The unique identifier of the account associated with the transaction.
        payee_id (Optional[UUID]): The unique identifier of the payee associated with the transaction.
        category_id (Optional[UUID]): The unique identifier of the category associated with the transaction.
        transfer_account_id (Optional[UUID]): The unique identifier of the transfer account associated with the transaction.
        transfer_transaction_id (Optional[str]): The unique identifier of the transfer transaction associated with the transaction.
        matched_transaction_id (Optional[str]): The unique identifier of the matched transaction associated with the transaction.
        import_id (Optional[UUID]): The unique identifier of the import associated with the transaction.
        import_payee_name (Optional[str]): The name of the payee as imported.
        import_payee_name_original (Optional[str]): The original name of the payee as imported.
        debt_transaction_type (Optional[str]): The type of debt transaction.
        deleted (bool): Indicates whether the transaction is deleted.
        account_name (str): The name of the account associated with the transaction.
        payee_name (Optional[str]): The name of the payee associated with the transaction.
        category_name (Optional[str]): The name of the category associated with the transaction.
        subtransactions (list[Subtransaction]): A list of subtransactions associated with the transaction.
    """

    id: str
    date: date
    amount: int
    memo: Optional[str] = None
    cleared: Literal["cleared", "uncleared", "reconciled"]
    approved: bool
    flag_color: Optional[FlagColor] = None
    flag_name: Optional[str] = None
    account_id: UUID
    payee_id: Optional[UUID] = None
    category_id: Optional[UUID] = None
    transfer_account_id: Optional[UUID] = None
    transfer_transaction_id: Optional[str] = None
    matched_transaction_id: Optional[str] = None
    import_id: Optional[UUID] = None
    import_payee_name: Optional[str] = None
    import_payee_name_original: Optional[str] = None
    debt_transaction_type: Optional[str] = None
    deleted: bool
    account_name: str
    payee_name: Optional[str] = None
    category_name: Optional[str] = None
    subtransactions: list[Subtransaction]

TransactionSummary

Bases: BaseModel

TransactionSummary represents a summary of a financial transaction.

Attributes:

Name Type Description
id str

Unique identifier for the transaction.

date date

The date of the transaction.

amount int

The amount of the transaction in the smallest currency unit (e.g., cents).

memo Optional[str]

A memo or note associated with the transaction.

cleared Literal['cleared', 'uncleared', 'reconciled']

The cleared status of the transaction.

approved bool

Indicates whether the transaction is approved.

flag_color Optional[FlagColor]

The color of the flag associated with the transaction.

flag_name Optional[str]

The name of the flag associated with the transaction.

account_id UUID

The unique identifier of the account associated with the transaction.

payee_id Optional[UUID]

The unique identifier of the payee associated with the transaction.

category_id Optional[UUID]

The unique identifier of the category associated with the transaction.

transfer_account_id Optional[UUID]

The unique identifier of the transfer account associated with the transaction.

transfer_transaction_id Optional[str]

The unique identifier of the transfer transaction associated with the transaction.

matched_transaction_id Optional[str]

The unique identifier of the matched transaction.

import_id Optional[UUID]

The unique identifier of the import associated with the transaction.

import_payee_name Optional[str]

The name of the payee as imported.

import_payee_name_original Optional[str]

The original name of the payee as imported.

debt_transaction_type Optional[str]

The type of debt transaction.

deleted bool

Indicates whether the transaction is deleted.

Source code in src/uynab/model/transaction.py
class TransactionSummary(BaseModel):
    """
    TransactionSummary represents a summary of a financial transaction.

    Attributes:
        id (str): Unique identifier for the transaction.
        date (date): The date of the transaction.
        amount (int): The amount of the transaction in the smallest currency unit (e.g., cents).
        memo (Optional[str]): A memo or note associated with the transaction.
        cleared (Literal["cleared", "uncleared", "reconciled"]): The cleared status of the transaction.
        approved (bool): Indicates whether the transaction is approved.
        flag_color (Optional[FlagColor]): The color of the flag associated with the transaction.
        flag_name (Optional[str]): The name of the flag associated with the transaction.
        account_id (UUID): The unique identifier of the account associated with the transaction.
        payee_id (Optional[UUID]): The unique identifier of the payee associated with the transaction.
        category_id (Optional[UUID]): The unique identifier of the category associated with the transaction.
        transfer_account_id (Optional[UUID]): The unique identifier of the transfer account associated with the transaction.
        transfer_transaction_id (Optional[str]): The unique identifier of the transfer transaction associated with the transaction.
        matched_transaction_id (Optional[str]): The unique identifier of the matched transaction.
        import_id (Optional[UUID]): The unique identifier of the import associated with the transaction.
        import_payee_name (Optional[str]): The name of the payee as imported.
        import_payee_name_original (Optional[str]): The original name of the payee as imported.
        debt_transaction_type (Optional[str]): The type of debt transaction.
        deleted (bool): Indicates whether the transaction is deleted.
    """

    id: str
    date: date
    amount: int
    memo: Optional[str] = None
    cleared: Literal["cleared", "uncleared", "reconciled"]
    approved: bool
    flag_color: Optional[FlagColor] = None
    flag_name: Optional[str] = None
    account_id: UUID
    payee_id: Optional[UUID] = None
    category_id: Optional[UUID] = None
    transfer_account_id: Optional[UUID] = None
    transfer_transaction_id: Optional[str] = None
    matched_transaction_id: Optional[str] = None
    import_id: Optional[UUID] = None
    import_payee_name: Optional[str] = None
    import_payee_name_original: Optional[str] = None
    debt_transaction_type: Optional[str] = None
    deleted: bool

utils

CurrencyFormat

Bases: BaseModel

CurrencyFormat is a model that represents the formatting details for a specific currency.

Attributes:

Name Type Description
iso_code str

The ISO 4217 code for the currency (e.g., 'USD' for US Dollar).

example_format str

An example of how the currency is formatted (e.g., '$1,234.56').

decimal_digits int

The number of decimal digits used in the currency (e.g., 2 for USD).

decimal_separator str

The character used to separate the integer part from the fractional part (e.g., '.' for USD).

symbol_first bool

Indicates whether the currency symbol appears before the amount (True) or after (False).

group_separator str

The character used to separate groups of thousands (e.g., ',' for USD).

currency_symbol str

The symbol used to represent the currency (e.g., '$' for USD).

display_symbol bool

Indicates whether the currency symbol should be displayed (True) or not (False).

Source code in src/uynab/model/utils.py
class CurrencyFormat(BaseModel):
    """
    CurrencyFormat is a model that represents the formatting details for a specific currency.

    Attributes:
        iso_code (str): The ISO 4217 code for the currency (e.g., 'USD' for US Dollar).
        example_format (str): An example of how the currency is formatted (e.g., '$1,234.56').
        decimal_digits (int): The number of decimal digits used in the currency (e.g., 2 for USD).
        decimal_separator (str): The character used to separate the integer part from the fractional part (e.g., '.' for USD).
        symbol_first (bool): Indicates whether the currency symbol appears before the amount (True) or after (False).
        group_separator (str): The character used to separate groups of thousands (e.g., ',' for USD).
        currency_symbol (str): The symbol used to represent the currency (e.g., '$' for USD).
        display_symbol (bool): Indicates whether the currency symbol should be displayed (True) or not (False).
    """

    iso_code: str
    example_format: str
    decimal_digits: int
    decimal_separator: str
    symbol_first: bool
    group_separator: str
    currency_symbol: str
    display_symbol: bool

DateFormat

Bases: BaseModel

A class used to represent a Date Format.

Attributes:

Name Type Description
format str

A string representing the date format. For example: "YYYY-MM-DD"

Source code in src/uynab/model/utils.py
class DateFormat(BaseModel):
    """A class used to represent a Date Format.

    Attributes:
        format (str): A string representing the date format.
            For example: "YYYY-MM-DD"
    """

    format: str

FlagColor

Bases: StrEnum

A class used to represent the color of a flag.

Attributes:

Name Type Description
RED

A red flag.

ORANGE

An orange flag.

YELLOW

A yellow flag.

GREEN

A green flag.

BLUE

A blue flag.

PURPLE

A purple flag.

Source code in src/uynab/model/utils.py
class FlagColor(StrEnum):
    """A class used to represent the color of a flag.

    Attributes:
        RED: A red flag.
        ORANGE: An orange flag.
        YELLOW: A yellow flag.
        GREEN: A green flag.
        BLUE: A blue flag.
        PURPLE: A purple flag.
    """

    RED = "red"
    ORANGE = "orange"
    YELLOW = "yellow"
    GREEN = "green"
    BLUE = "blue"
    PURPLE = "purple"

Month

Bases: BaseModel

Represents a financial month with various attributes.

Attributes:

Name Type Description
month datetime

The month this instance represents.

note Optional[str]

An optional note for the month.

income int

The total income for the month.

budgeted int

The total amount budgeted for the month.

activity int

The total financial activity for the month.

to_be_budgeted int

The amount left to be budgeted for the month.

age_of_money int

The age of money in days.

deleted bool

Indicates if the month record is deleted.

categories list[Category]

A list of categories associated with the month.

Source code in src/uynab/model/utils.py
class Month(BaseModel):
    """
    Represents a financial month with various attributes.

    Attributes:
        month (datetime): The month this instance represents.
        note (Optional[str]): An optional note for the month.
        income (int): The total income for the month.
        budgeted (int): The total amount budgeted for the month.
        activity (int): The total financial activity for the month.
        to_be_budgeted (int): The amount left to be budgeted for the month.
        age_of_money (int): The age of money in days.
        deleted (bool): Indicates if the month record is deleted.
        categories (list[Category]): A list of categories associated with the month.
    """

    month: datetime
    note: Optional[str] = None
    income: int
    budgeted: int
    activity: int
    to_be_budgeted: int
    age_of_money: int
    deleted: bool
    categories: list[Category]

service

account

Service account module

This module provides the AccountService class for interacting with accounts in the YNAB (You Need A Budget) API.

Classes:

Name Description
AccountService

A service class for performing operations related to accounts in a YNAB budget.

budget

Service budget module

This module provides the BudgetService class for interacting with budget-related endpoints of the YNAB API.

Classes:

Name Description
BudgetService

A service class for retrieving and managing budgets and their settings.

BudgetService

Bases: YNABService

Source code in src/uynab/service/budget.py
class BudgetService(YNABService):
    def get_all_budgets(self) -> list[BudgetSummary]:
        """
        Retrieve all budgets from the API.
        This method performs an API call to fetch all budgets and returns them as a list of Budget objects.
        Returns:
            list[Budget]: A list of Budget objects retrieved from the API.
        """

        response = self.perform_api_call(ResponseBudgets, "GET", "budgets")
        return response.data.budgets

    def get_budget(self, budget_id: UUID) -> Budget:
        """
        Retrieve a budget by its ID.
        Args:
            budget_id (UUID): The ID of the budget to retrieve.
        Returns:
            Budget: The budget object corresponding to the provided ID.
        """

        response = self.perform_api_call(ResponseBudget, "GET", f"budgets/{budget_id}")
        return response.data.budget

    def get_budget_settings(self, budget_id: UUID) -> BudgetSettings:
        """
        Retrieve the settings for a specific budget.

        Args:
            budget_id (UUID): The ID of the budget for which to retrieve settings.

        Returns:
            BudgetSettings: The settings of the specified budget.
        """

        response = self.perform_api_call(
            ResponseBudgetSettings, "GET", f"budgets/{budget_id}/settings"
        )
        return response.data.settings

    # Not standard methods

    def _get_budget_by_name(self, budget_name: str) -> BudgetSummary:
        """
        Retrieve a budget by its name.
        Args:
            budget_name (str): The name of the budget to retrieve.
        Returns:
            Budget: The budget object with the specified name.
        Raises:
            ValueError: If the budget with the given name does not exist.
        """

        all_budgets = self.get_all_budgets()
        for budget in all_budgets:
            if budget.name == budget_name:
                return budget
        raise ValueError(f"Budget '{budget_name}' not found")

    def _get_budget_id(self, budget_name: str) -> UUID:
        """
        Retrieve the budget ID for a given budget name.
        Args:
            budget_name (str): The name of the budget.
        Returns:
            str: The ID of the budget.
        Raises:
            ValueError: If the budget with the given name does not exist.
        """

        budget = self._get_budget_by_name(budget_name)
        return budget.id
get_all_budgets()

Retrieve all budgets from the API. This method performs an API call to fetch all budgets and returns them as a list of Budget objects. Returns: list[Budget]: A list of Budget objects retrieved from the API.

Source code in src/uynab/service/budget.py
def get_all_budgets(self) -> list[BudgetSummary]:
    """
    Retrieve all budgets from the API.
    This method performs an API call to fetch all budgets and returns them as a list of Budget objects.
    Returns:
        list[Budget]: A list of Budget objects retrieved from the API.
    """

    response = self.perform_api_call(ResponseBudgets, "GET", "budgets")
    return response.data.budgets
get_budget(budget_id)

Retrieve a budget by its ID. Args: budget_id (UUID): The ID of the budget to retrieve. Returns: Budget: The budget object corresponding to the provided ID.

Source code in src/uynab/service/budget.py
def get_budget(self, budget_id: UUID) -> Budget:
    """
    Retrieve a budget by its ID.
    Args:
        budget_id (UUID): The ID of the budget to retrieve.
    Returns:
        Budget: The budget object corresponding to the provided ID.
    """

    response = self.perform_api_call(ResponseBudget, "GET", f"budgets/{budget_id}")
    return response.data.budget
get_budget_settings(budget_id)

Retrieve the settings for a specific budget.

Parameters:

Name Type Description Default
budget_id UUID

The ID of the budget for which to retrieve settings.

required

Returns:

Name Type Description
BudgetSettings BudgetSettings

The settings of the specified budget.

Source code in src/uynab/service/budget.py
def get_budget_settings(self, budget_id: UUID) -> BudgetSettings:
    """
    Retrieve the settings for a specific budget.

    Args:
        budget_id (UUID): The ID of the budget for which to retrieve settings.

    Returns:
        BudgetSettings: The settings of the specified budget.
    """

    response = self.perform_api_call(
        ResponseBudgetSettings, "GET", f"budgets/{budget_id}/settings"
    )
    return response.data.settings

category

Service category module.

This module provides services for interacting with categories and category groups within a budget in the YNAB (You Need A Budget) application.

Classes:

Name Description
CategoryService

A service class for retrieving category groups and categories from a specified budget.

CategoryService

Bases: YNABService

Source code in src/uynab/service/category.py
class CategoryService(YNABService):
    def get_all_categories(self, budget_id: UUID) -> list[CategoryGroup]:
        """
        Retrieve all category groups for a given budget.
        Inside the category group there are categories.

        Args:
            budget_id (UUID): The unique identifier of the budget.

        Returns:
            list[CategoryGroup]: A list of category groups associated with the budget.
        """

        response = self.perform_api_call(
            ResponseCategoryGroup, "GET", f"budgets/{budget_id}/categories"
        )
        return response.data.category_groups

    def get_category(self, budget_id: UUID, category_id: UUID) -> Category:
        """
        Retrieve a specific category from a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            category_id (UUID): The unique identifier of the category.

        Returns:
            Category: The category object retrieved from the budget.
        """
        response = self.perform_api_call(
            ResponseCategory, "GET", f"budgets/{budget_id}/categories/{category_id}"
        )
        return response.data.category
get_all_categories(budget_id)

Retrieve all category groups for a given budget. Inside the category group there are categories.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required

Returns:

Type Description
list[CategoryGroup]

list[CategoryGroup]: A list of category groups associated with the budget.

Source code in src/uynab/service/category.py
def get_all_categories(self, budget_id: UUID) -> list[CategoryGroup]:
    """
    Retrieve all category groups for a given budget.
    Inside the category group there are categories.

    Args:
        budget_id (UUID): The unique identifier of the budget.

    Returns:
        list[CategoryGroup]: A list of category groups associated with the budget.
    """

    response = self.perform_api_call(
        ResponseCategoryGroup, "GET", f"budgets/{budget_id}/categories"
    )
    return response.data.category_groups
get_category(budget_id, category_id)

Retrieve a specific category from a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
category_id UUID

The unique identifier of the category.

required

Returns:

Name Type Description
Category Category

The category object retrieved from the budget.

Source code in src/uynab/service/category.py
def get_category(self, budget_id: UUID, category_id: UUID) -> Category:
    """
    Retrieve a specific category from a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        category_id (UUID): The unique identifier of the category.

    Returns:
        Category: The category object retrieved from the budget.
    """
    response = self.perform_api_call(
        ResponseCategory, "GET", f"budgets/{budget_id}/categories/{category_id}"
    )
    return response.data.category

payee

Service payee module.

This module provides the PayeeService class, which encapsulates operations related to payees in the YNAB API. It acts as an interface to manage payees for a given budget, including retrieving payee details, fetching all payees, and updating payee information.

Classes:

Name Description
- PayeeService

A service for managing YNAB payees, providing methods to interact with the API.

Example Usage
from uynab.client import YNABClient
from uynab.service.payee import PayeeService

# Initialize the API client
client = YNABClient(api_token="your-token")

# Initialize the PayeeService
payee_service = PayeeService(client)

# Fetch all payees for a specific budget
budget_id = "some-budget-id"
payees = payee_service.get_all_payees(budget_id)

# Fetch details of a specific payee
payee_id = "some-payee-id"
payee = payee_service.get_payee(budget_id, payee_id)

# Update a specific payee
updated_payee = payee_service.update_payee(
    budget_id, payee_id, {"payee": {"name": "New Payee Name"}}
)

PayeeService

Bases: YNABService

A service for managing payees in the YNAB API.

This class provides methods to interact with the payees associated with a specific budget, including fetching all payees, retrieving details for a single payee, and updating payee details.

Attributes:

Name Type Description
client Client

An instance of the YNAB API client used for making requests.

Methods:

Name Description
get_all_payees

UUID) -> list[Payee]: Fetch all payees associated with a specific budget.

get_payee

UUID, payee_id: UUID) -> Payee: Retrieve details for a single payee by ID.

update_payee

UUID, payee_id: UUID, data: dict) -> Payee: Update the details of a specific payee.

Source code in src/uynab/service/payee.py
class PayeeService(YNABService):
    """
    A service for managing payees in the YNAB API.

    This class provides methods to interact with the payees associated with a specific budget,
    including fetching all payees, retrieving details for a single payee, and updating payee details.

    Attributes:
        client (Client): An instance of the YNAB API client used for making requests.

    Methods:
        get_all_payees(budget_id: UUID) -> list[Payee]:
            Fetch all payees associated with a specific budget.

        get_payee(budget_id: UUID, payee_id: UUID) -> Payee:
            Retrieve details for a single payee by ID.

        update_payee(budget_id: UUID, payee_id: UUID, data: dict) -> Payee:
            Update the details of a specific payee.
    """

    def get_all_payees(self, budget_id: UUID) -> list[Payee]:
        """Fetch all payees for the specific budget

        Args:
            budget_id (UUID): An ID for a budget from which all payees will be fetched

        Returns:
            list[Payee]: List of all payees for specified budget
        """
        response = self.perform_api_call(
            ResponsePayees, "GET", f"budgets/{budget_id}/payees"
        )
        return response.data.payees

    def get_payee(self, budget_id: UUID, payee_id: UUID) -> Payee:
        """Fetch a single payee

        Args:
            budget_id (UUID): An ID for the budget from which payee will be fetched
            payee_id (UUID): An ID of a payee to fetch

        Returns:
            Payee: Fetched payee
        """
        response = self.perform_api_call(
            ResponsePayee, "GET", f"budgets/{budget_id}/payees/{payee_id}"
        )
        return response.data.payee

    def update_payee(self, budget_id: UUID, payee_id: UUID, data: dict) -> Payee:
        """Update a single payee

        Args:
            budget_id (UUID): An ID for the budget from which payee will be updated
            payee_id (UUID): An ID of a payee to update
            data (dict): Data of payee to update in the following format:
                ```py
                {
                    "payee": {
                            "name": "string"
                        }
                }
                ```

        Returns:
            Payee: Updated payee
        """
        response = self.perform_api_call(
            ResponsePayee,
            "PATCH",
            f"budgets/{budget_id}/payees/{payee_id}",
            data=RequestDataPayee(**data).model_dump_json(),
        )
        return response.data.payee
get_all_payees(budget_id)

Fetch all payees for the specific budget

Parameters:

Name Type Description Default
budget_id UUID

An ID for a budget from which all payees will be fetched

required

Returns:

Type Description
list[Payee]

list[Payee]: List of all payees for specified budget

Source code in src/uynab/service/payee.py
def get_all_payees(self, budget_id: UUID) -> list[Payee]:
    """Fetch all payees for the specific budget

    Args:
        budget_id (UUID): An ID for a budget from which all payees will be fetched

    Returns:
        list[Payee]: List of all payees for specified budget
    """
    response = self.perform_api_call(
        ResponsePayees, "GET", f"budgets/{budget_id}/payees"
    )
    return response.data.payees
get_payee(budget_id, payee_id)

Fetch a single payee

Parameters:

Name Type Description Default
budget_id UUID

An ID for the budget from which payee will be fetched

required
payee_id UUID

An ID of a payee to fetch

required

Returns:

Name Type Description
Payee Payee

Fetched payee

Source code in src/uynab/service/payee.py
def get_payee(self, budget_id: UUID, payee_id: UUID) -> Payee:
    """Fetch a single payee

    Args:
        budget_id (UUID): An ID for the budget from which payee will be fetched
        payee_id (UUID): An ID of a payee to fetch

    Returns:
        Payee: Fetched payee
    """
    response = self.perform_api_call(
        ResponsePayee, "GET", f"budgets/{budget_id}/payees/{payee_id}"
    )
    return response.data.payee
update_payee(budget_id, payee_id, data)

Update a single payee

Parameters:

Name Type Description Default
budget_id UUID

An ID for the budget from which payee will be updated

required
payee_id UUID

An ID of a payee to update

required
data dict

Data of payee to update in the following format:

{
    "payee": {
            "name": "string"
        }
}

required

Returns:

Name Type Description
Payee Payee

Updated payee

Source code in src/uynab/service/payee.py
def update_payee(self, budget_id: UUID, payee_id: UUID, data: dict) -> Payee:
    """Update a single payee

    Args:
        budget_id (UUID): An ID for the budget from which payee will be updated
        payee_id (UUID): An ID of a payee to update
        data (dict): Data of payee to update in the following format:
            ```py
            {
                "payee": {
                        "name": "string"
                    }
            }
            ```

    Returns:
        Payee: Updated payee
    """
    response = self.perform_api_call(
        ResponsePayee,
        "PATCH",
        f"budgets/{budget_id}/payees/{payee_id}",
        data=RequestDataPayee(**data).model_dump_json(),
    )
    return response.data.payee

service

Service module

This module provides the YNABService class, which handles communication with the YNAB API.

Classes:

Name Description
YNABService

A service class to handle communication with YNAB.

YNABService

A service class to handle communication with YNAB.

Attributes:

Name Type Description
client Client

The client used for communication with YNAB.

Methods:

Name Description
perform_api_call

Model, method: str, endpoint: str, data: dict | None = None) -> dict: Sends a request to the specified endpoint using the given method and data.

Source code in src/uynab/service/service.py
class YNABService:
    """
    A service class to handle communication with YNAB.

    Attributes:
        client (Client): The client used for communication with YNAB.

    Methods:
        perform_api_call(model: Model, method: str, endpoint: str, data: dict | None = None) -> dict:
            Sends a request to the specified endpoint using the given method and data.
    """

    def __init__(self, client: Client) -> None:
        """Initialize service class

        Args:
            client (Client): client for communication with YNAB
        """
        self.client = client

    def perform_api_call(
        self,
        model: Model,
        method: str,
        endpoint: str,
        params: dict | None = None,
        data: Any | None = None,
    ) -> Model:
        """
        Perform an API call using the specified method and endpoint, and return the response as a model instance.

        Args:
            model (Model): The model class to instantiate with the response data.
            method (str): The HTTP method to use for the API call (e.g., 'GET', 'POST').
            endpoint (str): The API endpoint to call.
            params (dict, optional): The query parameters to send with the API call. Defaults to None.
            data (Any, optional): The data to send with the API call. Defaults to None.

        Returns:
            Model: An instance of the model class populated with the response data.

        Raises:
            ResponseError: If the response data cannot be validated against the model.
        """

        response = self.client.request(method, endpoint, params=params, data=data)
        try:
            return model(**response)
        except ValidationError as e:
            raise ResponseError(response=response, verbose=self.client._verbose) from e
__init__(client)

Initialize service class

Parameters:

Name Type Description Default
client Client

client for communication with YNAB

required
Source code in src/uynab/service/service.py
def __init__(self, client: Client) -> None:
    """Initialize service class

    Args:
        client (Client): client for communication with YNAB
    """
    self.client = client
perform_api_call(model, method, endpoint, params=None, data=None)

Perform an API call using the specified method and endpoint, and return the response as a model instance.

Parameters:

Name Type Description Default
model Model

The model class to instantiate with the response data.

required
method str

The HTTP method to use for the API call (e.g., 'GET', 'POST').

required
endpoint str

The API endpoint to call.

required
params dict

The query parameters to send with the API call. Defaults to None.

None
data Any

The data to send with the API call. Defaults to None.

None

Returns:

Name Type Description
Model Model

An instance of the model class populated with the response data.

Raises:

Type Description
ResponseError

If the response data cannot be validated against the model.

Source code in src/uynab/service/service.py
def perform_api_call(
    self,
    model: Model,
    method: str,
    endpoint: str,
    params: dict | None = None,
    data: Any | None = None,
) -> Model:
    """
    Perform an API call using the specified method and endpoint, and return the response as a model instance.

    Args:
        model (Model): The model class to instantiate with the response data.
        method (str): The HTTP method to use for the API call (e.g., 'GET', 'POST').
        endpoint (str): The API endpoint to call.
        params (dict, optional): The query parameters to send with the API call. Defaults to None.
        data (Any, optional): The data to send with the API call. Defaults to None.

    Returns:
        Model: An instance of the model class populated with the response data.

    Raises:
        ResponseError: If the response data cannot be validated against the model.
    """

    response = self.client.request(method, endpoint, params=params, data=data)
    try:
        return model(**response)
    except ValidationError as e:
        raise ResponseError(response=response, verbose=self.client._verbose) from e

transaction

Service transaction module

This module provides the TransactionService class, which is responsible for managing transactions within a budget in the YNAB (You Need A Budget) system. The service includes methods to retrieve, create, update, and delete transactions, as well as to retrieve transactions by account, category, payee, and month.

Classes:

Name Description
TransactionService

A service class for managing transactions in a YNAB budget.

TransactionService

Bases: YNABService

Source code in src/uynab/service/transaction.py
class TransactionService(YNABService):
    def get_all_transactions(
        self,
        budget_id: UUID,
        since_date: date | None = None,
        last_knowledge_of_server: int | None = None,
    ) -> list[TransactionDetail]:
        """
        Retrieve all transactions for a given budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            since_date (date, optional): The date from which to retrieve transactions.
                ISO formatted (e.g. 2024-01-01). Defaults to None.
            last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

        Returns:
            list[TransactionDetail]: A list of transactions associated with the budget.
        """
        params = self._prepare_params(since_date, last_knowledge_of_server)
        response = self.perform_api_call(
            ResponseTransactions,
            "GET",
            f"budgets/{budget_id}/transactions",
            params=params or None,
        )
        return response.data.transactions

    def get_transaction(
        self, budget_id: UUID, transaction_id: UUID
    ) -> TransactionDetail:
        """
        Retrieve a specific transaction from a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            transaction_id (UUID): The unique identifier of the transaction.

        Returns:
            TransactionDetail: The transaction object retrieved from the budget.
        """
        response = self.perform_api_call(
            ResponseTransaction,
            "GET",
            f"budgets/{budget_id}/transactions/{transaction_id}",
        )
        return response.data.transaction

    def create_transactions(
        self, budget_id: UUID, transactions: list[NewTransaction]
    ) -> list[TransactionDetail]:
        """
        Create new transactions in a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            transactions (NewTransaction): The transaction object to be created.

        Returns:
            TransactionDetail: The created transaction object.
        """
        data: dict[str, list[str]] = {"transactions": []}
        for transaction in transactions:
            data["transactions"].append(transaction.model_dump_json())

        response = self.perform_api_call(
            ResponseTransactions,
            "POST",
            f"budgets/{budget_id}/transactions",
            data=data,
        )
        return response.data.transactions

    def update_transactions(
        self, budget_id: UUID, transactions: list[SaveTransactionWithIdOrImportId]
    ) -> list[TransactionDetail]:
        """
        Updates a list of transactions for a given budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            transactions (list[SaveTransactionWithIdOrImportId]): A list of transactions to be updated.

        Returns:
            list[TransactionDetail]: A list of updated transaction details.
        """
        data: dict[str, list[str]] = {"transactions": []}
        for transaction in transactions:
            data["transactions"].append(transaction.model_dump_json())

        response = self.perform_api_call(
            ResponseSaveTransactions,
            "PUT",
            f"budgets/{budget_id}/transactions",
            data=data,
        )
        return response.data.transactions

    def update_transaction(
        self, budget_id: UUID, transaction_id: str, transaction: NewTransaction
    ) -> TransactionDetail:
        """
        Update existing transactions in a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            transaction_id (str): The unique identifier of the transaction.
            transaction (NewTransaction): The transaction object with updated data.

        Returns:
            Transaction: The updated transaction object.
        """
        data: dict[str, str] = {"transaction": transaction.model_dump_json()}

        response = self.perform_api_call(
            ResponseTransaction,
            "PATCH",
            f"budgets/{budget_id}/transactions/{transaction_id}",
            data=data,
        )
        return response.data.transaction

    def delete_transaction(
        self, budget_id: UUID, transaction_id: UUID
    ) -> TransactionDetail:
        """
        Delete a specific transaction from a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            transaction_id (UUID): The unique identifier of the transaction.
        """
        response = self.perform_api_call(
            ResponseTransaction,
            "DELETE",
            f"budgets/{budget_id}/transactions/{transaction_id}",
        )

        return response.data.transaction

    def get_transactions_by_account(
        self,
        budget_id: UUID,
        account_id: UUID,
        since_date: date | None = None,
        last_knowledge_of_server: int | None = None,
    ) -> list[TransactionDetail]:
        """
        Retrieve all transactions for a specific account in a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            account_id (UUID): The unique identifier of the account.
            since_date (date, optional): The date from which to retrieve transactions.
                ISO formatted (e.g. 2024-01-01). Defaults to None.
            last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

        Returns:
            list[TransactionDetail]: A list of transactions associated with the account.
        """
        params = self._prepare_params(since_date, last_knowledge_of_server)
        response = self.perform_api_call(
            ResponseTransactions,
            "GET",
            f"budgets/{budget_id}/accounts/{account_id}/transactions",
            params=params or None,
        )
        return response.data.transactions

    def get_transactions_by_category(
        self,
        budget_id: UUID,
        category_id: UUID,
        since_date: date | None = None,
        last_knowledge_of_server: int | None = None,
    ) -> list[TransactionDetail]:
        """
        Retrieve all transactions for a specific category in a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            category_id (UUID): The unique identifier of the category.
            since_date (date, optional): The date from which to retrieve transactions.
                ISO formatted (e.g. 2024-01-01). Defaults to None.
            last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

        Returns:
            list[TransactionDetail]: A list of transactions associated with the category.
        """
        params = self._prepare_params(since_date, last_knowledge_of_server)
        response = self.perform_api_call(
            ResponseTransactions,
            "GET",
            f"budgets/{budget_id}/categories/{category_id}/transactions",
            params=params or None,
        )
        return response.data.transactions

    def get_transactions_by_payee(
        self,
        budget_id: UUID,
        payee_id: UUID,
        since_date: date | None = None,
        last_knowledge_of_server: int | None = None,
    ) -> list[TransactionDetail]:
        """
        Retrieve all transactions for a specific payee in a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            payee_id (UUID): The unique identifier of the payee.
            since_date (date, optional): The date from which to retrieve transactions.
                ISO formatted (e.g. 2024-01-01). Defaults to None.
            last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

        Returns:
            list[TransactionDetail]: A list of transactions associated with the payee.
        """
        params = self._prepare_params(since_date, last_knowledge_of_server)
        response = self.perform_api_call(
            ResponseTransactions,
            "GET",
            f"budgets/{budget_id}/payees/{payee_id}/transactions",
            params=params or None,
        )
        return response.data.transactions

    def get_transactions_by_month(
        self,
        budget_id: UUID,
        month: date,
        since_date: date | None = None,
        last_knowledge_of_server: int | None = None,
    ) -> list[TransactionDetail]:
        """
        Retrieve all transactions for a specific month in a budget.

        Args:
            budget_id (UUID): The unique identifier of the budget.
            month (date): The budget month for which to retrieve transactions.
                ISO formatted (e.g. 2024-01-01)
            since_date (date, optional): The date from which to retrieve transactions.
                ISO formatted (e.g. 2024-01-01). Defaults to None.
            last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

        Returns:
            list[TransactionDetail]: A list of transactions associated with the month.
        """
        params = self._prepare_params(since_date, last_knowledge_of_server)
        response = self.perform_api_call(
            ResponseTransactions,
            "GET",
            f"budgets/{budget_id}/months/{month}/transactions",
            params=params or None,
        )
        return response.data.transactions

    @staticmethod
    def _prepare_params(
        since_date: date | None, last_knowledge_of_server: int | None
    ) -> dict[str, Any]:
        """
        Prepare a dictionary of parameters for a request.

        Args:
            since_date (date | None): The starting date for the request.
                If provided, it will be converted to a string.
                ISO formatted (e.g. 2024-01-01). Defaults to None.
            last_knowledge_of_server (int | None): The last known server state.
                If provided, it will be included as is. Defaults to None.

        Returns:
            dict: A dictionary containing the prepared parameters.
        """
        params: dict[str, str | int] = {}
        if since_date:
            params["since_date"] = str(since_date)
        if last_knowledge_of_server:
            params["last_knowledge_of_server"] = last_knowledge_of_server
        return params
create_transactions(budget_id, transactions)

Create new transactions in a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
transactions NewTransaction

The transaction object to be created.

required

Returns:

Name Type Description
TransactionDetail list[TransactionDetail]

The created transaction object.

Source code in src/uynab/service/transaction.py
def create_transactions(
    self, budget_id: UUID, transactions: list[NewTransaction]
) -> list[TransactionDetail]:
    """
    Create new transactions in a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        transactions (NewTransaction): The transaction object to be created.

    Returns:
        TransactionDetail: The created transaction object.
    """
    data: dict[str, list[str]] = {"transactions": []}
    for transaction in transactions:
        data["transactions"].append(transaction.model_dump_json())

    response = self.perform_api_call(
        ResponseTransactions,
        "POST",
        f"budgets/{budget_id}/transactions",
        data=data,
    )
    return response.data.transactions
delete_transaction(budget_id, transaction_id)

Delete a specific transaction from a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
transaction_id UUID

The unique identifier of the transaction.

required
Source code in src/uynab/service/transaction.py
def delete_transaction(
    self, budget_id: UUID, transaction_id: UUID
) -> TransactionDetail:
    """
    Delete a specific transaction from a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        transaction_id (UUID): The unique identifier of the transaction.
    """
    response = self.perform_api_call(
        ResponseTransaction,
        "DELETE",
        f"budgets/{budget_id}/transactions/{transaction_id}",
    )

    return response.data.transaction
get_all_transactions(budget_id, since_date=None, last_knowledge_of_server=None)

Retrieve all transactions for a given budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
since_date date

The date from which to retrieve transactions. ISO formatted (e.g. 2024-01-01). Defaults to None.

None
last_knowledge_of_server int

The last knowledge of the server. Defaults to None.

None

Returns:

Type Description
list[TransactionDetail]

list[TransactionDetail]: A list of transactions associated with the budget.

Source code in src/uynab/service/transaction.py
def get_all_transactions(
    self,
    budget_id: UUID,
    since_date: date | None = None,
    last_knowledge_of_server: int | None = None,
) -> list[TransactionDetail]:
    """
    Retrieve all transactions for a given budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        since_date (date, optional): The date from which to retrieve transactions.
            ISO formatted (e.g. 2024-01-01). Defaults to None.
        last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

    Returns:
        list[TransactionDetail]: A list of transactions associated with the budget.
    """
    params = self._prepare_params(since_date, last_knowledge_of_server)
    response = self.perform_api_call(
        ResponseTransactions,
        "GET",
        f"budgets/{budget_id}/transactions",
        params=params or None,
    )
    return response.data.transactions
get_transaction(budget_id, transaction_id)

Retrieve a specific transaction from a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
transaction_id UUID

The unique identifier of the transaction.

required

Returns:

Name Type Description
TransactionDetail TransactionDetail

The transaction object retrieved from the budget.

Source code in src/uynab/service/transaction.py
def get_transaction(
    self, budget_id: UUID, transaction_id: UUID
) -> TransactionDetail:
    """
    Retrieve a specific transaction from a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        transaction_id (UUID): The unique identifier of the transaction.

    Returns:
        TransactionDetail: The transaction object retrieved from the budget.
    """
    response = self.perform_api_call(
        ResponseTransaction,
        "GET",
        f"budgets/{budget_id}/transactions/{transaction_id}",
    )
    return response.data.transaction
get_transactions_by_account(budget_id, account_id, since_date=None, last_knowledge_of_server=None)

Retrieve all transactions for a specific account in a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
account_id UUID

The unique identifier of the account.

required
since_date date

The date from which to retrieve transactions. ISO formatted (e.g. 2024-01-01). Defaults to None.

None
last_knowledge_of_server int

The last knowledge of the server. Defaults to None.

None

Returns:

Type Description
list[TransactionDetail]

list[TransactionDetail]: A list of transactions associated with the account.

Source code in src/uynab/service/transaction.py
def get_transactions_by_account(
    self,
    budget_id: UUID,
    account_id: UUID,
    since_date: date | None = None,
    last_knowledge_of_server: int | None = None,
) -> list[TransactionDetail]:
    """
    Retrieve all transactions for a specific account in a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        account_id (UUID): The unique identifier of the account.
        since_date (date, optional): The date from which to retrieve transactions.
            ISO formatted (e.g. 2024-01-01). Defaults to None.
        last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

    Returns:
        list[TransactionDetail]: A list of transactions associated with the account.
    """
    params = self._prepare_params(since_date, last_knowledge_of_server)
    response = self.perform_api_call(
        ResponseTransactions,
        "GET",
        f"budgets/{budget_id}/accounts/{account_id}/transactions",
        params=params or None,
    )
    return response.data.transactions
get_transactions_by_category(budget_id, category_id, since_date=None, last_knowledge_of_server=None)

Retrieve all transactions for a specific category in a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
category_id UUID

The unique identifier of the category.

required
since_date date

The date from which to retrieve transactions. ISO formatted (e.g. 2024-01-01). Defaults to None.

None
last_knowledge_of_server int

The last knowledge of the server. Defaults to None.

None

Returns:

Type Description
list[TransactionDetail]

list[TransactionDetail]: A list of transactions associated with the category.

Source code in src/uynab/service/transaction.py
def get_transactions_by_category(
    self,
    budget_id: UUID,
    category_id: UUID,
    since_date: date | None = None,
    last_knowledge_of_server: int | None = None,
) -> list[TransactionDetail]:
    """
    Retrieve all transactions for a specific category in a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        category_id (UUID): The unique identifier of the category.
        since_date (date, optional): The date from which to retrieve transactions.
            ISO formatted (e.g. 2024-01-01). Defaults to None.
        last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

    Returns:
        list[TransactionDetail]: A list of transactions associated with the category.
    """
    params = self._prepare_params(since_date, last_knowledge_of_server)
    response = self.perform_api_call(
        ResponseTransactions,
        "GET",
        f"budgets/{budget_id}/categories/{category_id}/transactions",
        params=params or None,
    )
    return response.data.transactions
get_transactions_by_month(budget_id, month, since_date=None, last_knowledge_of_server=None)

Retrieve all transactions for a specific month in a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
month date

The budget month for which to retrieve transactions. ISO formatted (e.g. 2024-01-01)

required
since_date date

The date from which to retrieve transactions. ISO formatted (e.g. 2024-01-01). Defaults to None.

None
last_knowledge_of_server int

The last knowledge of the server. Defaults to None.

None

Returns:

Type Description
list[TransactionDetail]

list[TransactionDetail]: A list of transactions associated with the month.

Source code in src/uynab/service/transaction.py
def get_transactions_by_month(
    self,
    budget_id: UUID,
    month: date,
    since_date: date | None = None,
    last_knowledge_of_server: int | None = None,
) -> list[TransactionDetail]:
    """
    Retrieve all transactions for a specific month in a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        month (date): The budget month for which to retrieve transactions.
            ISO formatted (e.g. 2024-01-01)
        since_date (date, optional): The date from which to retrieve transactions.
            ISO formatted (e.g. 2024-01-01). Defaults to None.
        last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

    Returns:
        list[TransactionDetail]: A list of transactions associated with the month.
    """
    params = self._prepare_params(since_date, last_knowledge_of_server)
    response = self.perform_api_call(
        ResponseTransactions,
        "GET",
        f"budgets/{budget_id}/months/{month}/transactions",
        params=params or None,
    )
    return response.data.transactions
get_transactions_by_payee(budget_id, payee_id, since_date=None, last_knowledge_of_server=None)

Retrieve all transactions for a specific payee in a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
payee_id UUID

The unique identifier of the payee.

required
since_date date

The date from which to retrieve transactions. ISO formatted (e.g. 2024-01-01). Defaults to None.

None
last_knowledge_of_server int

The last knowledge of the server. Defaults to None.

None

Returns:

Type Description
list[TransactionDetail]

list[TransactionDetail]: A list of transactions associated with the payee.

Source code in src/uynab/service/transaction.py
def get_transactions_by_payee(
    self,
    budget_id: UUID,
    payee_id: UUID,
    since_date: date | None = None,
    last_knowledge_of_server: int | None = None,
) -> list[TransactionDetail]:
    """
    Retrieve all transactions for a specific payee in a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        payee_id (UUID): The unique identifier of the payee.
        since_date (date, optional): The date from which to retrieve transactions.
            ISO formatted (e.g. 2024-01-01). Defaults to None.
        last_knowledge_of_server (int, optional): The last knowledge of the server. Defaults to None.

    Returns:
        list[TransactionDetail]: A list of transactions associated with the payee.
    """
    params = self._prepare_params(since_date, last_knowledge_of_server)
    response = self.perform_api_call(
        ResponseTransactions,
        "GET",
        f"budgets/{budget_id}/payees/{payee_id}/transactions",
        params=params or None,
    )
    return response.data.transactions
update_transaction(budget_id, transaction_id, transaction)

Update existing transactions in a budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
transaction_id str

The unique identifier of the transaction.

required
transaction NewTransaction

The transaction object with updated data.

required

Returns:

Name Type Description
Transaction TransactionDetail

The updated transaction object.

Source code in src/uynab/service/transaction.py
def update_transaction(
    self, budget_id: UUID, transaction_id: str, transaction: NewTransaction
) -> TransactionDetail:
    """
    Update existing transactions in a budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        transaction_id (str): The unique identifier of the transaction.
        transaction (NewTransaction): The transaction object with updated data.

    Returns:
        Transaction: The updated transaction object.
    """
    data: dict[str, str] = {"transaction": transaction.model_dump_json()}

    response = self.perform_api_call(
        ResponseTransaction,
        "PATCH",
        f"budgets/{budget_id}/transactions/{transaction_id}",
        data=data,
    )
    return response.data.transaction
update_transactions(budget_id, transactions)

Updates a list of transactions for a given budget.

Parameters:

Name Type Description Default
budget_id UUID

The unique identifier of the budget.

required
transactions list[SaveTransactionWithIdOrImportId]

A list of transactions to be updated.

required

Returns:

Type Description
list[TransactionDetail]

list[TransactionDetail]: A list of updated transaction details.

Source code in src/uynab/service/transaction.py
def update_transactions(
    self, budget_id: UUID, transactions: list[SaveTransactionWithIdOrImportId]
) -> list[TransactionDetail]:
    """
    Updates a list of transactions for a given budget.

    Args:
        budget_id (UUID): The unique identifier of the budget.
        transactions (list[SaveTransactionWithIdOrImportId]): A list of transactions to be updated.

    Returns:
        list[TransactionDetail]: A list of updated transaction details.
    """
    data: dict[str, list[str]] = {"transactions": []}
    for transaction in transactions:
        data["transactions"].append(transaction.model_dump_json())

    response = self.perform_api_call(
        ResponseSaveTransactions,
        "PUT",
        f"budgets/{budget_id}/transactions",
        data=data,
    )
    return response.data.transactions