-
Notifications
You must be signed in to change notification settings - Fork 0
Usage
Garot Conklin edited this page Oct 10, 2025
·
2 revisions
This guide covers the basic and advanced usage of githubauthlib.
The most common use case is retrieving a GitHub token:
from githubauthlib import (
get_github_token,
GitHubAuthError,
TokenNotFoundError,
InvalidTokenError,
PlatformNotSupportedError,
CredentialHelperError
)
try:
token = get_github_token()
print("Token retrieved successfully!")
print(f"Token type: {token[:4]}_...")
except TokenNotFoundError:
print("No GitHub token found in system keychain")
except InvalidTokenError:
print("Invalid token format detected")
except PlatformNotSupportedError:
print("Current platform is not supported")
except CredentialHelperError:
print("Failed to access system credential store")
except GitHubAuthError as e:
print(f"GitHub authentication error: {e}")The library provides specific exceptions for different error cases:
from githubauthlib import (
get_github_token,
GitHubAuthError,
TokenNotFoundError,
InvalidTokenError,
PlatformNotSupportedError,
CredentialHelperError
)
try:
token = get_github_token()
except TokenNotFoundError:
print("No token found in system keychain")
except InvalidTokenError:
print("Token format is invalid")
except PlatformNotSupportedError:
print("Operating system not supported")
except CredentialHelperError:
print("Failed to access credential store")
except GitHubAuthError as e:
print(f"General authentication error: {e}")You can validate a token's format:
from githubauthlib.github_auth import _validate_token
# 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)}")The library uses Python's built-in logging module:
import logging
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Get token with detailed logging
token = get_github_token()from githubauthlib import get_github_token
import requests
def get_github_user():
try:
token = get_github_token()
headers = {'Authorization': f'token {token}'}
response = requests.get('https://api.github.com/user', headers=headers)
return response.json()
except TokenNotFoundError:
raise ValueError("No GitHub token found in system keychain")
except InvalidTokenError:
raise ValueError("Invalid token format")
except GitHubAuthError as e:
raise ValueError(f"Authentication error: {e}")
# Usage
try:
user_info = get_github_user()
print(f"Logged in as: {user_info['login']}")
except Exception as e:
print(f"Error: {e}")import subprocess
from githubauthlib import get_github_token
def run_github_cli_command(command):
try:
token = get_github_token()
env = {'GITHUB_TOKEN': token}
result = subprocess.run(
command,
env=env,
capture_output=True,
text=True
)
return result.stdout
except TokenNotFoundError:
raise ValueError("No GitHub token found in system keychain")
except InvalidTokenError:
raise ValueError("Invalid token format")
except GitHubAuthError as e:
raise ValueError(f"Authentication error: {e}")
# Usage
try:
repos = run_github_cli_command(['gh', 'repo', 'list'])
print(repos)
except Exception as e:
print(f"Error: {e}")-
Error Handling
- Always wrap token retrieval in try-except blocks
- Handle specific exceptions for better error reporting
-
Token Security
- Never log or print the actual token
- Don't store tokens in plain text
- Use environment variables when needed
-
Performance
- Cache the token if making multiple API calls
- Reuse the token within the same session
-
Logging
- Configure logging appropriately for your environment
- Avoid logging sensitive information
from functools import lru_cache
from githubauthlib import get_github_token
@lru_cache(maxsize=1)
def get_cached_token():
return get_github_token()
# Usage
token = get_cached_token() # First call retrieves token
token = get_cached_token() # Subsequent calls use cached valuefrom contextlib import contextmanager
from githubauthlib import get_github_token
@contextmanager
def github_token_context():
try:
token = get_github_token()
yield token
except TokenNotFoundError:
raise ValueError("No GitHub token found in system keychain")
except InvalidTokenError:
raise ValueError("Invalid token format")
except GitHubAuthError as e:
raise ValueError(f"Authentication error: {e}")
finally:
# Cleanup if needed
pass
# Usage
with github_token_context() as token:
# Use token here
print("Token is available")- Check the API Reference for detailed documentation
- Visit the Troubleshooting guide if you encounter issues
- Read the Contributing guide to help improve the library