Skip to content

API Reference

Garot Conklin edited this page Oct 10, 2025 · 2 revisions

API Reference

This page documents all public APIs available in githubauthlib.

Core Functions

get_github_token()

from githubauthlib import get_github_token

def get_github_token() -> str:
    """
    Retrieves the GitHub token from the system's secure storage.

    Returns:
        str: The GitHub token if found and valid

    Raises:
        TokenNotFoundError: If no token is found in the system keychain
        InvalidTokenError: If the retrieved token is invalid or malformed
        PlatformNotSupportedError: If the current platform is not supported
        CredentialHelperError: If credential helper operations fail
        GitHubAuthError: Base exception for GitHub authentication errors
    """

Example Usage

try:
    token = get_github_token()
    print("Token retrieved successfully")
    print(f"Token type: {token[:4]}_...")
except TokenNotFoundError:
    print("No token found in system keychain")
except InvalidTokenError:
    print("Invalid token format")
except GitHubAuthError as e:
    print(f"Error: {e}")

_validate_token()

from githubauthlib.github_auth import _validate_token

def _validate_token(token: str) -> bool:
    """
    Validate the format of a GitHub token.

    Args:
        token (str): The token to validate

    Returns:
        bool: True if the token format is valid, False otherwise

    Note:
        This function validates personal (ghp_), organization (gho_),
        and fine-grained (github_pat_) tokens.
    """

Example Usage

# Test different token types
personal_token = "ghp_1234567890abcdef1234567890abcdef123456"
org_token = "gho_1234567890abcdef1234567890abcdef123456"
fine_grained_token = "github_pat_1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"

print(f"Personal token valid: {_validate_token(personal_token)}")
print(f"Organization token valid: {_validate_token(org_token)}")
print(f"Fine-grained token valid: {_validate_token(fine_grained_token)}")

Exceptions

GitHubAuthError

class GitHubAuthError(Exception):
    """Base exception for GitHub authentication errors."""
    pass

TokenNotFoundError

class TokenNotFoundError(GitHubAuthError):
    """Raised when no GitHub token is found in the system keychain."""
    pass

InvalidTokenError

class InvalidTokenError(GitHubAuthError):
    """Raised when the retrieved token is invalid or malformed."""
    pass

PlatformNotSupportedError

class PlatformNotSupportedError(GitHubAuthError):
    """Raised when the current platform is not supported."""
    pass

CredentialHelperError

class CredentialHelperError(GitHubAuthError):
    """Raised when credential helper operations fail."""
    pass

Internal Functions

These functions are used internally but may be useful for debugging or extending the library:

_get_token_macos()

def _get_token_macos() -> Optional[str]:
    """Retrieve token from macOS keychain."""

_get_token_windows()

def _get_token_windows() -> Optional[str]:
    """Retrieve token from Windows Credential Manager."""

_get_token_linux()

def _get_token_linux() -> Optional[str]:
    """Retrieve token from Linux libsecret."""

Type Hints

The library uses Python type hints throughout:

from typing import Optional

# Common return type for token retrieval functions
Token = Optional[str]

Constants

The library doesn't expose any public constants, but internally uses:

  • Regular expression for token validation
  • Logging configuration
  • Platform-specific command strings

Logging

The library uses Python's standard logging module:

import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

Platform Support

The library supports the following platforms:

  • macOS (Darwin)

    • Uses git credential-osxkeychain
    • Requires Keychain Access
  • Windows

    • Uses Windows Credential Manager
    • Supports manager, manager-core, and wincred helpers
  • Linux

    • Uses libsecret
    • Requires secret-tool command-line utility

Error Handling

All errors inherit from GitHubAuthError:

Exception
└── GitHubAuthError
    ├── TokenNotFoundError
    ├── InvalidTokenError
    ├── PlatformNotSupportedError
    └── CredentialHelperError

Best Practices

  1. Always handle exceptions:
try:
    token = get_github_token()
except GitHubAuthError as e:
    # Handle error
  1. Validate tokens before use:
token = get_github_token()
if token and validate_token(token):
    # Use token
  1. Configure logging as needed:
logging.getLogger('githubauthlib').setLevel(logging.DEBUG)

Version Information

The current version can be accessed via:

from githubauthlib import __version__
print(__version__)  # e.g., '2.0.1'
Clone this wiki locally