GitHub API
Authentication
GitHub Apps vs OAuth Apps
GitHub Apps
OAuth apps
Full Python Code to Generate JWT, Request Access Token and Access Repo
import jwt
import time
import requests
# Replace these with your GitHub App credentials
APP_ID = "your_github_app_id"
INSTALLATION_ID = "your_installation_id"
PRIVATE_KEY_PATH = "path/to/your/private-key.pem"
# Step 1: Generate a JSON Web Token (JWT)
def generate_jwt(app_id, private_key_path):
with open(private_key_path, "r") as key_file:
private_key = key_file.read()
current_time = int(time.time())
payload = {
"iat": current_time, # Issued at time
"exp": current_time + (10 * 60), # Expiration time (10 minutes)
"iss": app_id # GitHub App ID
}
token = jwt.encode(payload, private_key, algorithm="RS256")
return token
# Step 2: Request an Installation Access Token
def get_installation_access_token(jwt_token, installation_id):
headers = {
"Authorization": f"Bearer {jwt_token}",
"Accept": "application/vnd.github+json"
}
url = f"https://api.github.com/app/installations/{installation_id}/access_tokens"
response = requests.post(url, headers=headers)
if response.status_code == 201:
return response.json()["token"]
else:
raise Exception(f"Failed to get access token: {response.status_code} {response.text}")
# Step 3: Use the Installation Access Token to Access the GitHub API
def access_github_api(access_token):
headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github+json"
}
url = "https://api.github.com/user" # Example API endpoint
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"API request failed: {response.status_code} {response.text}")
# Main Flow
try:
# Generate JWT
jwt_token = generate_jwt(APP_ID, PRIVATE_KEY_PATH)
# Request Installation Access Token
access_token = get_installation_access_token(jwt_token, INSTALLATION_ID)
# Use the token to interact with the GitHub API
user_data = access_github_api(access_token)
print("User Data:", user_data)
except Exception as e:
print("Error:", str(e))
Get Content
Reference
Last updated