Skip to content

Authentication

Interfaces

interfaces

Authentication credential interfaces for the T3 API.

T3Credentials

Bases: TypedDict

Credentials required to authenticate with the T3 API via Metrc.

Used by :func:t3api_utils.auth.utils.create_credentials_authenticated_client_or_error and related helpers to build an authenticated API client.

hostname instance-attribute

hostname: str

Metrc state hostname (e.g. "ca.metrc.com", "co.metrc.com").

username instance-attribute

username: str

Metrc account username.

password instance-attribute

password: str

Metrc account password.

otp instance-attribute

otp: Optional[str]

One-time password for two-factor authentication. Required for hostnames in the OTP whitelist (e.g. mi.metrc.com).

email instance-attribute

email: Optional[str]

Email address associated with the Metrc account. Required for hostnames in the credential-email whitelist (e.g. co.metrc.com).

Utilities

utils

Authentication utilities for T3 API using httpx-based client.

This module provides authentication functions using our async httpx implementation with sync wrappers for compatibility.

create_credentials_authenticated_client_or_error_async async

create_credentials_authenticated_client_or_error_async(*, hostname: str, username: str, password: str, host: Optional[str] = None, otp: Optional[str] = None, email: Optional[str] = None) -> T3APIClient

Authenticates with the T3 API using credentials and returns an authenticated client (async).

Parameters:

Name Type Description Default
hostname str

Metrc hostname used for authentication (e.g., "api-ca").

required
username str

Metrc account username.

required
password str

Metrc account password.

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None
otp Optional[str]

One-time password for multi-factor authentication.

None
email Optional[str]

Email address associated with the Metrc account.

None

Returns:

Name Type Description
T3APIClient T3APIClient

An authenticated async client instance ready for use.

Raises:

Type Description
AuthenticationError

If authentication fails.

Source code in t3api_utils/auth/utils.py
async def create_credentials_authenticated_client_or_error_async(
    *,
    hostname: str,
    username: str,
    password: str,
    host: Optional[str] = None,
    otp: Optional[str] = None,
    email: Optional[str] = None,
) -> T3APIClient:
    """
    Authenticates with the T3 API using credentials and returns an authenticated client (async).

    Args:
        hostname: Metrc hostname used for authentication (e.g., "api-ca").
        username: Metrc account username.
        password: Metrc account password.
        host: T3 API host URL. Defaults to production if not provided.
        otp: One-time password for multi-factor authentication.
        email: Email address associated with the Metrc account.

    Returns:
        T3APIClient: An authenticated async client instance ready for use.

    Raises:
        AuthenticationError: If authentication fails.
    """
    try:
        # Create HTTP config with host from config or parameter
        effective_host = host or config_manager.get_api_host()
        config = HTTPConfig(host=effective_host)

        # Create and authenticate the client
        client = T3APIClient(config=config, logging_hooks=LoggingHooks.from_env())

        await client.authenticate_with_credentials(
            hostname=hostname,
            username=username,
            password=password,
            otp=otp,
            email=email,
        )

        return client

    except T3HTTPError as e:
        raise AuthenticationError(f"T3 API authentication failed: {e}") from e
    except Exception as e:
        raise AuthenticationError(f"Unexpected authentication error: {str(e)}") from e

create_credentials_authenticated_client_or_error

create_credentials_authenticated_client_or_error(*, hostname: str, username: str, password: str, host: Optional[str] = None, otp: Optional[str] = None, email: Optional[str] = None) -> T3APIClient

Authenticates with the T3 API using credentials and returns an authenticated client (sync wrapper).

This function provides a sync wrapper around the async implementation.

Parameters:

Name Type Description Default
hostname str

Metrc hostname used for authentication (e.g., "api-ca").

required
username str

Metrc account username.

required
password str

Metrc account password.

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None
otp Optional[str]

One-time password for multi-factor authentication.

None
email Optional[str]

Email address associated with the Metrc account.

None

Returns:

Name Type Description
T3APIClient T3APIClient

An authenticated client instance ready for use

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
def create_credentials_authenticated_client_or_error(
    *,
    hostname: str,
    username: str,
    password: str,
    host: Optional[str] = None,
    otp: Optional[str] = None,
    email: Optional[str] = None,
) -> T3APIClient:
    """
    Authenticates with the T3 API using credentials and returns an authenticated client (sync wrapper).

    This function provides a sync wrapper around the async implementation.

    Args:
        hostname: Metrc hostname used for authentication (e.g., "api-ca").
        username: Metrc account username.
        password: Metrc account password.
        host: T3 API host URL. Defaults to production if not provided.
        otp: One-time password for multi-factor authentication.
        email: Email address associated with the Metrc account.

    Returns:
        T3APIClient: An authenticated client instance ready for use

    Raises:
        AuthenticationError: If authentication fails
    """
    return asyncio.run(create_credentials_authenticated_client_or_error_async(
        hostname=hostname,
        username=username,
        password=password,
        host=host,
        otp=otp,
        email=email,
    ))

authenticate_and_get_token_async async

authenticate_and_get_token_async(*, hostname: str, username: str, password: str, host: Optional[str] = None, otp: Optional[str] = None, email: Optional[str] = None) -> str

Authenticate and return just the access token (async).

This is a convenience function for when you only need the token and not the full client.

Parameters:

Name Type Description Default
hostname str

Metrc hostname used for authentication (e.g., "api-ca").

required
username str

Metrc account username.

required
password str

Metrc account password.

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None
otp Optional[str]

One-time password for multi-factor authentication.

None
email Optional[str]

Email address associated with the Metrc account.

None

Returns:

Name Type Description
str str

The access token.

Raises:

Type Description
AuthenticationError

If authentication fails.

Source code in t3api_utils/auth/utils.py
async def authenticate_and_get_token_async(
    *,
    hostname: str,
    username: str,
    password: str,
    host: Optional[str] = None,
    otp: Optional[str] = None,
    email: Optional[str] = None,
) -> str:
    """
    Authenticate and return just the access token (async).

    This is a convenience function for when you only need the token
    and not the full client.

    Args:
        hostname: Metrc hostname used for authentication (e.g., "api-ca").
        username: Metrc account username.
        password: Metrc account password.
        host: T3 API host URL. Defaults to production if not provided.
        otp: One-time password for multi-factor authentication.
        email: Email address associated with the Metrc account.

    Returns:
        str: The access token.

    Raises:
        AuthenticationError: If authentication fails.
    """
    client = await create_credentials_authenticated_client_or_error_async(
        hostname=hostname,
        username=username,
        password=password,
        host=host,
        otp=otp,
        email=email,
    )

    if client.access_token is None:
        raise AuthenticationError("Authentication succeeded but no access token was returned")

    # Clean up the client
    await client.close()

    return client.access_token

authenticate_and_get_token

authenticate_and_get_token(*, hostname: str, username: str, password: str, host: Optional[str] = None, otp: Optional[str] = None, email: Optional[str] = None) -> str

Authenticate and return just the access token (sync wrapper).

This is a convenience function for when you only need the token and not the full client.

Parameters:

Name Type Description Default
hostname str

Metrc hostname used for authentication (e.g., "api-ca").

required
username str

Metrc account username.

required
password str

Metrc account password.

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None
otp Optional[str]

One-time password for multi-factor authentication.

None
email Optional[str]

Email address associated with the Metrc account.

None

Returns:

Name Type Description
str str

The access token

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
def authenticate_and_get_token(
    *,
    hostname: str,
    username: str,
    password: str,
    host: Optional[str] = None,
    otp: Optional[str] = None,
    email: Optional[str] = None,
) -> str:
    """
    Authenticate and return just the access token (sync wrapper).

    This is a convenience function for when you only need the token
    and not the full client.

    Args:
        hostname: Metrc hostname used for authentication (e.g., "api-ca").
        username: Metrc account username.
        password: Metrc account password.
        host: T3 API host URL. Defaults to production if not provided.
        otp: One-time password for multi-factor authentication.
        email: Email address associated with the Metrc account.

    Returns:
        str: The access token

    Raises:
        AuthenticationError: If authentication fails
    """
    return asyncio.run(authenticate_and_get_token_async(
        hostname=hostname,
        username=username,
        password=password,
        host=host,
        otp=otp,
        email=email,
    ))

authenticate_and_get_response_async async

authenticate_and_get_response_async(*, hostname: str, username: str, password: str, host: Optional[str] = None, otp: Optional[str] = None, email: Optional[str] = None) -> AuthResponseData

Authenticate and return the full authentication response (async).

This function provides access to all authentication response data including refresh tokens and expiration information.

Parameters:

Name Type Description Default
hostname str

Metrc hostname used for authentication (e.g., "api-ca").

required
username str

Metrc account username.

required
password str

Metrc account password.

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None
otp Optional[str]

One-time password for multi-factor authentication.

None
email Optional[str]

Email address associated with the Metrc account.

None

Returns:

Name Type Description
AuthResponseData AuthResponseData

The complete authentication response.

Raises:

Type Description
AuthenticationError

If authentication fails.

Source code in t3api_utils/auth/utils.py
async def authenticate_and_get_response_async(
    *,
    hostname: str,
    username: str,
    password: str,
    host: Optional[str] = None,
    otp: Optional[str] = None,
    email: Optional[str] = None,
) -> AuthResponseData:
    """
    Authenticate and return the full authentication response (async).

    This function provides access to all authentication response data
    including refresh tokens and expiration information.

    Args:
        hostname: Metrc hostname used for authentication (e.g., "api-ca").
        username: Metrc account username.
        password: Metrc account password.
        host: T3 API host URL. Defaults to production if not provided.
        otp: One-time password for multi-factor authentication.
        email: Email address associated with the Metrc account.

    Returns:
        AuthResponseData: The complete authentication response.

    Raises:
        AuthenticationError: If authentication fails.
    """
    try:
        # Create HTTP config with host from config or parameter
        effective_host = host or config_manager.get_api_host()
        config = HTTPConfig(host=effective_host)

        # Create client and authenticate
        async with T3APIClient(config=config, logging_hooks=LoggingHooks.from_env()) as client:
            auth_response = await client.authenticate_with_credentials(
                hostname=hostname,
                username=username,
                password=password,
                otp=otp,
                email=email,
            )

            return auth_response

    except T3HTTPError as e:
        raise AuthenticationError(f"T3 API authentication failed: {e}") from e
    except Exception as e:
        raise AuthenticationError(f"Unexpected authentication error: {str(e)}") from e

authenticate_and_get_response

authenticate_and_get_response(*, hostname: str, username: str, password: str, host: Optional[str] = None, otp: Optional[str] = None, email: Optional[str] = None) -> AuthResponseData

Authenticate and return the full authentication response (sync wrapper).

This function provides access to all authentication response data including refresh tokens and expiration information.

Parameters:

Name Type Description Default
hostname str

Metrc hostname used for authentication (e.g., "api-ca").

required
username str

Metrc account username.

required
password str

Metrc account password.

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None
otp Optional[str]

One-time password for multi-factor authentication.

None
email Optional[str]

Email address associated with the Metrc account.

None

Returns:

Name Type Description
AuthResponseData AuthResponseData

The complete authentication response

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
def authenticate_and_get_response(
    *,
    hostname: str,
    username: str,
    password: str,
    host: Optional[str] = None,
    otp: Optional[str] = None,
    email: Optional[str] = None,
) -> AuthResponseData:
    """
    Authenticate and return the full authentication response (sync wrapper).

    This function provides access to all authentication response data
    including refresh tokens and expiration information.

    Args:
        hostname: Metrc hostname used for authentication (e.g., "api-ca").
        username: Metrc account username.
        password: Metrc account password.
        host: T3 API host URL. Defaults to production if not provided.
        otp: One-time password for multi-factor authentication.
        email: Email address associated with the Metrc account.

    Returns:
        AuthResponseData: The complete authentication response

    Raises:
        AuthenticationError: If authentication fails
    """
    return asyncio.run(authenticate_and_get_response_async(
        hostname=hostname,
        username=username,
        password=password,
        host=host,
        otp=otp,
        email=email,
    ))

create_jwt_authenticated_client

create_jwt_authenticated_client(*, jwt_token: str, host: Optional[str] = None, config: Optional[HTTPConfig] = None, retry_policy: Optional[RetryPolicy] = None, logging_hooks: Optional[LoggingHooks] = None, headers: Optional[Dict[str, str]] = None) -> T3APIClient

Creates an authenticated T3 API client using a pre-existing JWT token.

This function allows users to directly provide their JWT token instead of going through the username/password authentication flow.

Parameters:

Name Type Description Default
jwt_token str

Valid JWT access token issued by the T3 API.

required
host Optional[str]

T3 API host URL. Defaults to production if no config provided.

None
config Optional[HTTPConfig]

HTTP configuration for timeout, SSL, and proxy settings.

None
retry_policy Optional[RetryPolicy]

Retry policy controlling backoff and max attempts for failed requests.

None
logging_hooks Optional[LoggingHooks]

Hooks for logging outgoing requests and incoming responses.

None
headers Optional[Dict[str, str]]

Additional HTTP headers to include with every request.

None

Returns:

Name Type Description
T3APIClient T3APIClient

An authenticated async client instance

Raises:

Type Description
ValueError

If jwt_token is empty or None

AuthenticationError

If jwt_token is expired

Example

token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." client = create_jwt_authenticated_client(jwt_token=token)

Client is ready to use for API calls (note: it's async)

Source code in t3api_utils/auth/utils.py
def create_jwt_authenticated_client(
    *,
    jwt_token: str,
    host: Optional[str] = None,
    config: Optional[HTTPConfig] = None,
    retry_policy: Optional[RetryPolicy] = None,
    logging_hooks: Optional[LoggingHooks] = None,
    headers: Optional[Dict[str, str]] = None,
) -> T3APIClient:
    """
    Creates an authenticated T3 API client using a pre-existing JWT token.

    This function allows users to directly provide their JWT token instead of
    going through the username/password authentication flow.

    Args:
        jwt_token: Valid JWT access token issued by the T3 API.
        host: T3 API host URL. Defaults to production if no config provided.
        config: HTTP configuration for timeout, SSL, and proxy settings.
        retry_policy: Retry policy controlling backoff and max attempts for failed requests.
        logging_hooks: Hooks for logging outgoing requests and incoming responses.
        headers: Additional HTTP headers to include with every request.

    Returns:
        T3APIClient: An authenticated async client instance

    Raises:
        ValueError: If jwt_token is empty or None
        AuthenticationError: If jwt_token is expired

    Example:
        >>> token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
        >>> client = create_jwt_authenticated_client(jwt_token=token)
        >>> # Client is ready to use for API calls (note: it's async)
    """
    if not jwt_token or not jwt_token.strip():
        raise ValueError("JWT token cannot be empty or None")

    _check_jwt_expiry(jwt_token)

    # Handle host and config parameters
    if config is None:
        # No config provided, create one with specified host or default
        effective_host = host or config_manager.get_api_host()
        config = HTTPConfig(host=effective_host)
    elif host is not None and config.host != host:
        # Config provided but different host explicitly specified
        config = HTTPConfig(
            host=host,
            timeout=config.timeout,
            verify_ssl=config.verify_ssl,
            base_headers=config.base_headers,
            proxies=config.proxies,
        )
    # Otherwise, use the provided config as-is

    # Create the client
    client = T3APIClient(
        config=config,
        retry_policy=retry_policy,
        logging_hooks=logging_hooks if logging_hooks is not None else LoggingHooks.from_env(),
        headers=headers,
    )

    # Set the JWT token
    client.set_access_token(jwt_token.strip())

    return client

create_api_key_authenticated_client

create_api_key_authenticated_client(*, api_key: str, state_code: str, host: Optional[str] = None, config: Optional[HTTPConfig] = None, retry_policy: Optional[RetryPolicy] = None, logging_hooks: Optional[LoggingHooks] = None, headers: Optional[Dict[str, str]] = None) -> T3APIClient

Creates an authenticated T3 API client using an API key.

This function provides API key authentication by calling the /v2/auth/apikey endpoint with the provided API key and state code.

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if no config provided.

None
config Optional[HTTPConfig]

HTTP configuration for timeout, SSL, and proxy settings.

None
retry_policy Optional[RetryPolicy]

Retry policy controlling backoff and max attempts for failed requests.

None
logging_hooks Optional[LoggingHooks]

Hooks for logging outgoing requests and incoming responses.

None
headers Optional[Dict[str, str]]

Additional HTTP headers to include with every request.

None

Returns:

Name Type Description
T3APIClient T3APIClient

An authenticated async client instance

Raises:

Type Description
ValueError

If api_key or state_code is empty or None

AuthenticationError

If API key authentication fails

Example

client = create_api_key_authenticated_client( ... api_key="your-api-key", ... state_code="CA" ... )

Client is ready to use for API calls (note: it's async)

Source code in t3api_utils/auth/utils.py
def create_api_key_authenticated_client(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
    config: Optional[HTTPConfig] = None,
    retry_policy: Optional[RetryPolicy] = None,
    logging_hooks: Optional[LoggingHooks] = None,
    headers: Optional[Dict[str, str]] = None,
) -> T3APIClient:
    """
    Creates an authenticated T3 API client using an API key.

    This function provides API key authentication by calling the /v2/auth/apikey
    endpoint with the provided API key and state code.

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if no config provided.
        config: HTTP configuration for timeout, SSL, and proxy settings.
        retry_policy: Retry policy controlling backoff and max attempts for failed requests.
        logging_hooks: Hooks for logging outgoing requests and incoming responses.
        headers: Additional HTTP headers to include with every request.

    Returns:
        T3APIClient: An authenticated async client instance

    Raises:
        ValueError: If api_key or state_code is empty or None
        AuthenticationError: If API key authentication fails

    Example:
        >>> client = create_api_key_authenticated_client(
        ...     api_key="your-api-key",
        ...     state_code="CA"
        ... )
        >>> # Client is ready to use for API calls (note: it's async)
    """
    if not api_key or not api_key.strip():
        raise ValueError("API key cannot be empty or None")

    if not state_code or not state_code.strip():
        raise ValueError("State code cannot be empty or None")

    # Handle host and config parameters
    if config is None:
        # No config provided, create one with specified host or default
        effective_host = host or config_manager.get_api_host()
        config = HTTPConfig(host=effective_host)
    elif host is not None and config.host != host:
        # Config provided but different host explicitly specified
        config = HTTPConfig(
            host=host,
            timeout=config.timeout,
            verify_ssl=config.verify_ssl,
            base_headers=config.base_headers,
            proxies=config.proxies,
        )
    # Otherwise, use the provided config as-is

    # Create the client
    client = T3APIClient(
        config=config,
        retry_policy=retry_policy,
        logging_hooks=logging_hooks if logging_hooks is not None else LoggingHooks.from_env(),
        headers=headers,
    )

    # Note: This function creates the client but doesn't authenticate it yet
    # The caller needs to call authenticate_with_api_key() or use the high-level functions
    return client

create_api_key_authenticated_client_or_error_async async

create_api_key_authenticated_client_or_error_async(*, api_key: str, state_code: str, host: Optional[str] = None) -> T3APIClient

Authenticates with the T3 API using API key and returns an authenticated client (async).

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None

Returns:

Name Type Description
T3APIClient T3APIClient

An authenticated async client instance ready for use

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
async def create_api_key_authenticated_client_or_error_async(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
) -> T3APIClient:
    """
    Authenticates with the T3 API using API key and returns an authenticated client (async).

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if not provided.

    Returns:
        T3APIClient: An authenticated async client instance ready for use

    Raises:
        AuthenticationError: If authentication fails
    """
    try:
        # Create HTTP config with host from config or parameter
        effective_host = host or config_manager.get_api_host()
        config = HTTPConfig(host=effective_host)

        # Create and authenticate the client
        client = T3APIClient(config=config, logging_hooks=LoggingHooks.from_env())

        await client.authenticate_with_api_key(
            api_key=api_key,
            state_code=state_code,
        )

        return client

    except T3HTTPError as e:
        raise AuthenticationError(f"T3 API key authentication failed: {e}") from e
    except Exception as e:
        raise AuthenticationError(f"Unexpected API key authentication error: {str(e)}") from e

create_api_key_authenticated_client_or_error

create_api_key_authenticated_client_or_error(*, api_key: str, state_code: str, host: Optional[str] = None) -> T3APIClient

Authenticates with the T3 API using API key and returns an authenticated client (sync wrapper).

This function provides a sync wrapper around the async implementation.

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None

Returns:

Name Type Description
T3APIClient T3APIClient

An authenticated client instance ready for use

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
def create_api_key_authenticated_client_or_error(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
) -> T3APIClient:
    """
    Authenticates with the T3 API using API key and returns an authenticated client (sync wrapper).

    This function provides a sync wrapper around the async implementation.

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if not provided.

    Returns:
        T3APIClient: An authenticated client instance ready for use

    Raises:
        AuthenticationError: If authentication fails
    """
    return asyncio.run(create_api_key_authenticated_client_or_error_async(
        api_key=api_key,
        state_code=state_code,
        host=host,
    ))

authenticate_and_get_token_with_api_key_async async

authenticate_and_get_token_with_api_key_async(*, api_key: str, state_code: str, host: Optional[str] = None) -> str

Authenticate with API key and return just the access token (async).

This is a convenience function for when you only need the token and not the full client.

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None

Returns:

Name Type Description
str str

The access token

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
async def authenticate_and_get_token_with_api_key_async(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
) -> str:
    """
    Authenticate with API key and return just the access token (async).

    This is a convenience function for when you only need the token
    and not the full client.

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if not provided.

    Returns:
        str: The access token

    Raises:
        AuthenticationError: If authentication fails
    """
    client = await create_api_key_authenticated_client_or_error_async(
        api_key=api_key,
        state_code=state_code,
        host=host,
    )

    if client.access_token is None:
        raise AuthenticationError("API key authentication succeeded but no access token was returned")

    # Clean up the client
    await client.close()

    return client.access_token

authenticate_and_get_token_with_api_key

authenticate_and_get_token_with_api_key(*, api_key: str, state_code: str, host: Optional[str] = None) -> str

Authenticate with API key and return just the access token (sync wrapper).

This is a convenience function for when you only need the token and not the full client.

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None

Returns:

Name Type Description
str str

The access token

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
def authenticate_and_get_token_with_api_key(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
) -> str:
    """
    Authenticate with API key and return just the access token (sync wrapper).

    This is a convenience function for when you only need the token
    and not the full client.

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if not provided.

    Returns:
        str: The access token

    Raises:
        AuthenticationError: If authentication fails
    """
    return asyncio.run(authenticate_and_get_token_with_api_key_async(
        api_key=api_key,
        state_code=state_code,
        host=host,
    ))

authenticate_and_get_response_with_api_key_async async

authenticate_and_get_response_with_api_key_async(*, api_key: str, state_code: str, host: Optional[str] = None) -> AuthResponseData

Authenticate with API key and return the full authentication response (async).

This function provides access to all authentication response data including refresh tokens and expiration information.

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None

Returns:

Name Type Description
AuthResponseData AuthResponseData

The complete authentication response

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
async def authenticate_and_get_response_with_api_key_async(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
) -> AuthResponseData:
    """
    Authenticate with API key and return the full authentication response (async).

    This function provides access to all authentication response data
    including refresh tokens and expiration information.

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if not provided.

    Returns:
        AuthResponseData: The complete authentication response

    Raises:
        AuthenticationError: If authentication fails
    """
    try:
        # Create HTTP config with host from config or parameter
        effective_host = host or config_manager.get_api_host()
        config = HTTPConfig(host=effective_host)

        # Create client and authenticate
        async with T3APIClient(config=config, logging_hooks=LoggingHooks.from_env()) as client:
            auth_response = await client.authenticate_with_api_key(
                api_key=api_key,
                state_code=state_code,
            )

            return auth_response

    except T3HTTPError as e:
        raise AuthenticationError(f"T3 API key authentication failed: {e}") from e
    except Exception as e:
        raise AuthenticationError(f"Unexpected API key authentication error: {str(e)}") from e

authenticate_and_get_response_with_api_key

authenticate_and_get_response_with_api_key(*, api_key: str, state_code: str, host: Optional[str] = None) -> AuthResponseData

Authenticate with API key and return the full authentication response (sync wrapper).

This function provides access to all authentication response data including refresh tokens and expiration information.

Parameters:

Name Type Description Default
api_key str

T3 API key used for authentication via the /v2/auth/apikey endpoint.

required
state_code str

Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").

required
host Optional[str]

T3 API host URL. Defaults to production if not provided.

None

Returns:

Name Type Description
AuthResponseData AuthResponseData

The complete authentication response

Raises:

Type Description
AuthenticationError

If authentication fails

Source code in t3api_utils/auth/utils.py
def authenticate_and_get_response_with_api_key(
    *,
    api_key: str,
    state_code: str,
    host: Optional[str] = None,
) -> AuthResponseData:
    """
    Authenticate with API key and return the full authentication response (sync wrapper).

    This function provides access to all authentication response data
    including refresh tokens and expiration information.

    Args:
        api_key: T3 API key used for authentication via the /v2/auth/apikey endpoint.
        state_code: Two-letter US state code for the target Metrc instance (e.g., "CA", "MO").
        host: T3 API host URL. Defaults to production if not provided.

    Returns:
        AuthResponseData: The complete authentication response

    Raises:
        AuthenticationError: If authentication fails
    """
    return asyncio.run(authenticate_and_get_response_with_api_key_async(
        api_key=api_key,
        state_code=state_code,
        host=host,
    ))