Python wrapper for the GitHub API(http://developer.github.com/v3)
—
Comprehensive authentication functionality supporting multiple GitHub authentication methods including personal access tokens, OAuth applications, GitHub Apps, and enterprise instances with two-factor authentication support.
Create authenticated GitHub sessions using various credential types for different use cases and security requirements.
def login(username=None, password=None, token=None, two_factor_callback=None):
"""
Construct and return an authenticated GitHub session.
Parameters:
- username (str, optional): GitHub username for basic auth
- password (str, optional): Password for basic auth
- token (str, optional): Personal access token or OAuth token
- two_factor_callback (callable, optional): Function to provide 2FA code
Returns:
GitHub instance or None if no credentials provided
"""
def enterprise_login(username=None, password=None, token=None, url=None, two_factor_callback=None):
"""
Construct and return an authenticated GitHub Enterprise session.
Parameters:
- username (str, optional): Username for basic auth
- password (str, optional): Password for basic auth
- token (str, optional): Personal access token or OAuth token
- url (str, required): URL of GitHub Enterprise instance
- two_factor_callback (callable, optional): Function to provide 2FA code
Returns:
GitHubEnterprise instance or None if no credentials provided
"""# Token-based authentication (recommended)
import github3
gh = github3.login(token='ghp_your_personal_access_token')
# Username and token
gh = github3.login('username', token='ghp_your_token')
# Enterprise instance
gh = github3.enterprise_login(
url='https://github.your-company.com',
token='your_enterprise_token'
)
# Two-factor authentication
def two_factor_callback():
return input('Enter 2FA code: ')
gh = github3.login('username', 'password', two_factor_callback=two_factor_callback)Direct session management and authentication using the GitHub class constructor and login methods.
class GitHub:
def __init__(self, username="", password="", token="", session=None, api_version=""):
"""
Create a new GitHub instance.
Parameters:
- username (str): Username for authentication
- password (str): Password for authentication
- token (str): Token for authentication
- session (Session, optional): Custom requests session
- api_version (str, optional): API version header value
"""
def login(self, username=None, password=None, token=None, two_factor_callback=None):
"""
Log the user into GitHub for protected API calls.
Parameters:
- username (str, optional): Login name
- password (str, optional): Password for the login
- token (str, optional): OAuth token
- two_factor_callback (callable, optional): Function for 2FA code
"""
def set_client_id(self, id, secret):
"""
Set OAuth application credentials.
Parameters:
- id (str): 20-character hexadecimal client_id from GitHub
- secret (str): 40-character hexadecimal client_secret from GitHub
"""
def set_user_agent(self, user_agent):
"""
Set custom user agent string.
Parameters:
- user_agent (str): Custom user agent identifier
"""# Initialize with token
gh = github3.GitHub(token='your_token')
# Initialize and login separately
gh = github3.GitHub()
gh.login(token='your_token')
# Set OAuth app credentials for app-specific operations
gh.set_client_id('your_client_id', 'your_client_secret')
# Custom user agent
gh.set_user_agent('MyApp/1.0.0')Advanced authentication for GitHub Apps enabling programmatic access as applications rather than users.
def login_as_app(self, private_key_pem, app_id, expire_in=600):
"""
Login as a GitHub Application using JWT.
Parameters:
- private_key_pem (bytes): Private key for the GitHub App
- app_id (int): Integer identifier for the GitHub App
- expire_in (int): Token validity period in seconds (max 600)
"""
def login_as_app_installation(self, private_key_pem, app_id, installation_id, expire_in=30):
"""
Login using GitHub App installation credentials.
Parameters:
- private_key_pem (bytes): Private key for the GitHub App
- app_id (int): Integer identifier for the GitHub App
- installation_id (int): Installation ID for the app
- expire_in (int): JWT expiration in seconds (default 30)
"""# Read private key from file
with open('github-app-private-key.pem', 'rb') as f:
private_key = f.read()
# Authenticate as GitHub App
gh = github3.GitHub()
gh.login_as_app(private_key, app_id=12345)
# Authenticate as specific installation
gh.login_as_app_installation(private_key, app_id=12345, installation_id=67890)Complete OAuth authorization lifecycle for building applications that integrate with GitHub on behalf of users.
def authorize(self, username, password, scopes=None, note="", note_url="", client_id="", client_secret=""):
"""
Obtain an authorization token for OAuth applications.
Parameters:
- username (str, required): GitHub username
- password (str, required): GitHub password
- scopes (list, optional): Permission scopes for the token
- note (str, optional): Note about the authorization
- note_url (str, optional): URL for the application
- client_id (str, optional): OAuth client key
- client_secret (str, optional): OAuth client secret
Returns:
Authorization object with token details
"""
def authorization(self, id_num):
"""
Get information about a specific authorization.
Parameters:
- id_num (int): Unique ID of the authorization
Returns:
Authorization object or None
"""
def authorizations(self, number=-1, etag=None):
"""
Iterate over authorizations for the authenticated user.
Parameters:
- number (int): Number of authorizations to return (-1 for all)
- etag (str, optional): ETag from previous request
Returns:
Generator of Authorization objects
"""
def check_authorization(self, access_token):
"""
Check if an authorization token is valid.
Parameters:
- access_token (str): Token to validate
Returns:
bool: True if valid, False otherwise
"""
def revoke_authorization(self, access_token):
"""
Revoke a specific authorization token.
Parameters:
- access_token (str): Token to revoke
Returns:
bool: True if successful, False otherwise
"""
def revoke_authorizations(self):
"""
Revoke all authorization tokens for the OAuth application.
Returns:
bool: True if successful, False otherwise
"""# Create authorization with specific scopes
auth = gh.authorize(
'username',
'password',
scopes=['repo', 'user'],
note='MyApp Authorization',
note_url='https://myapp.com'
)
print(f"Token: {auth.token}")
# Check authorization validity
is_valid = gh.check_authorization('token_to_check')
# List all authorizations
for auth in gh.authorizations():
print(f"ID: {auth.id}, Note: {auth.note}")
# Revoke specific authorization
gh.revoke_authorization('token_to_revoke')Special authentication handling for GitHub Enterprise instances with custom URLs and SSL verification options.
class GitHubEnterprise(GitHub):
def __init__(self, url, username="", password="", token="", verify=True, session=None):
"""
Create a client for a GitHub Enterprise instance.
Parameters:
- url (str, required): Base URL of the Enterprise instance
- username (str): Username for authentication
- password (str): Password for authentication
- token (str): Token for authentication
- verify (bool): Enable SSL certificate verification
- session (Session, optional): Custom requests session
"""# Enterprise with SSL verification
gh = github3.GitHubEnterprise(
'https://github.company.com',
token='enterprise_token'
)
# Enterprise with custom SSL settings
gh = github3.GitHubEnterprise(
'https://github.company.com',
token='enterprise_token',
verify=False # For self-signed certificates
)class Authorization:
"""OAuth authorization token representation"""
id: int
token: str
note: str
note_url: str
scopes: list
# ... additional authorization properties# Most secure and flexible method
gh = github3.login(token='ghp_your_personal_access_token')# For applications acting on behalf of users
gh = github3.GitHub()
gh.set_client_id('client_id', 'client_secret')
auth = gh.authorize('user', 'pass', scopes=['repo'])# For applications with enhanced permissions
gh = github3.GitHub()
gh.login_as_app_installation(private_key, app_id, installation_id)# For GitHub Enterprise users
gh = github3.enterprise_login(
url='https://github.company.com',
token='enterprise_token'
)Install with Tessl CLI
npx tessl i tessl/pypi-github3--py