-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
Garot Conklin edited this page Oct 10, 2025
·
2 revisions
This page documents all public APIs available in githubauthlib.
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
"""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}")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.
"""# 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)}")class GitHubAuthError(Exception):
"""Base exception for GitHub authentication errors."""
passclass TokenNotFoundError(GitHubAuthError):
"""Raised when no GitHub token is found in the system keychain."""
passclass InvalidTokenError(GitHubAuthError):
"""Raised when the retrieved token is invalid or malformed."""
passclass PlatformNotSupportedError(GitHubAuthError):
"""Raised when the current platform is not supported."""
passclass CredentialHelperError(GitHubAuthError):
"""Raised when credential helper operations fail."""
passThese functions are used internally but may be useful for debugging or extending the library:
def _get_token_macos() -> Optional[str]:
"""Retrieve token from macOS keychain."""def _get_token_windows() -> Optional[str]:
"""Retrieve token from Windows Credential Manager."""def _get_token_linux() -> Optional[str]:
"""Retrieve token from Linux libsecret."""The library uses Python type hints throughout:
from typing import Optional
# Common return type for token retrieval functions
Token = Optional[str]The library doesn't expose any public constants, but internally uses:
- Regular expression for token validation
- Logging configuration
- Platform-specific command strings
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__)The library supports the following platforms:
-
macOS (Darwin)
- Uses
git credential-osxkeychain - Requires Keychain Access
- Uses
-
Windows
- Uses Windows Credential Manager
- Supports
manager,manager-core, andwincredhelpers
-
Linux
- Uses
libsecret - Requires
secret-toolcommand-line utility
- Uses
All errors inherit from GitHubAuthError:
Exception
└── GitHubAuthError
├── TokenNotFoundError
├── InvalidTokenError
├── PlatformNotSupportedError
└── CredentialHelperError- Always handle exceptions:
try:
token = get_github_token()
except GitHubAuthError as e:
# Handle error- Validate tokens before use:
token = get_github_token()
if token and validate_token(token):
# Use token- Configure logging as needed:
logging.getLogger('githubauthlib').setLevel(logging.DEBUG)The current version can be accessed via:
from githubauthlib import __version__
print(__version__) # e.g., '2.0.1'