GitHub Profile Analyzer in Python
About the project: This is a project for a GitHub Profile Analyzer in Python. This script will use the GitHub API to fetch and display public information about a user, such as their number of repositories, followers, and an overview of their popular projects.
This project is a great way to learn about fetching data from external APIs using the requests library.
The code is a single, self-contained Python file that prompts the user for a GitHub username and then displays the analysis.
This project requires the requests library, which is not included in the standard Python installation. You'll need to install it first by running the following command in your terminal:
pip install requests
Once installed, you can save the code as github_analyzer.py and run it from the command line:
python github_analyzer.py
The app will prompt you for a GitHub username, and then display a summary of their profile and a list of their top 5 most-starred public repositories.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# github_analyzer.py
import requests
import sys
def get_github_profile_data(username):
"""
Fetches public profile data for a given GitHub username from the GitHub API.
Args:
username (str): The GitHub username to search for.
Returns:
dict or None: A dictionary containing the user's profile data, or None if
the user is not found or an error occurs.
"""
api_url = f"https://api.github.com/users/{username}"
try:
response = requests.get(api_url)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as errh:
print(f"HTTP Error: {errh}")
return None
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
return None
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
return None
except requests.exceptions.RequestException as err:
print(f"An unexpected error occurred: {err}")
return None
def get_user_repositories(username):
"""
Fetches the public repositories for a given GitHub username.
Args:
username (str): The GitHub username to search for.
Returns:
list of dicts or None: A list of dictionaries, each representing a repository.
"""
api_url = f"https://api.github.com/users/{username}/repos"
try:
response = requests.get(api_url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching repositories: {e}")
return None
def main():
"""
Main function to run the GitHub Profile Analyzer.
"""
print("--- Python GitHub Profile Analyzer ---")
print("Enter a GitHub username to get their public profile data.")
while True:
username = input("Enter GitHub username (or 'q' to quit): ").strip()
if username.lower() == 'q':
print("Exiting. Goodbye!")
break
if not username:
print("Username cannot be empty. Please try again.")
continue
print(f"\nAnalyzing profile for '{username}'...")
# Get profile data
profile_data = get_github_profile_data(username)
if profile_data:
# Display core profile information
print("\n--- Profile Summary ---")
print(f"Name: {profile_data.get('name', 'N/A')}")
print(f"Bio: {profile_data.get('bio', 'N/A')}")
print(f"Location: {profile_data.get('location', 'N/A')}")
print(f"Public Repositories: {profile_data.get('public_repos', 0)}")
print(f"Followers: {profile_data.get('followers', 0)}")
print(f"Following: {profile_data.get('following', 0)}")
print(f"Joined GitHub: {profile_data.get('created_at', 'N/A').split('T')[0]}")
print(f"Profile URL: {profile_data.get('html_url', 'N/A')}")
# Get repository data and analyze
repos = get_user_repositories(username)
if repos:
# Sort repos by number of stars (a simple measure of popularity)
popular_repos = sorted(repos, key=lambda repo: repo['stargazers_count'], reverse=True)[:5]
if popular_repos:
print("\n--- Top 5 Public Repositories (by Stars) ---")
for i, repo in enumerate(popular_repos):
print(f"{i+1}. {repo['name']}")
print(f" - Stars: {repo['stargazers_count']} | Forks: {repo['forks_count']}")
print(f" - Description: {repo['description'] or 'No description provided.'}")
print(f" - Language: {repo['language'] or 'N/A'}")
print(f" - URL: {repo['html_url']}")
else:
print("\nNo public repositories found for this user.")
else:
print(f"Could not find a user with the username '{username}'. Please try again.")
print("\n" + "="*50 + "\n")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
# The 'requests' library is not a standard part of Python.
# Users will need to install it with 'pip install requests'.
try:
main()
except ImportError:
print("\nThe 'requests' library is not installed.")
print("Please install it by running: pip install requests")
print("You can then run this script again.")
← Back to Projects