Skip to content

Instantly share code, notes, and snippets.

@dougdomingos
Last active July 8, 2023 02:18
Show Gist options
  • Save dougdomingos/3fabb3bd781fb772dee5158f8afb18a7 to your computer and use it in GitHub Desktop.
Save dougdomingos/3fabb3bd781fb772dee5158f8afb18a7 to your computer and use it in GitHub Desktop.
A Python script to retrieve data from a GitHub user's public repositories and store it on JSON file. This code uses the GitHub API.
def fetch_repos(username: str):
"""This function retrieves data from all the public repositories of a GitHub profile
Args:
username (str): The username of the GitHub profile
Raises:
requests.HTTPError: If the request fails
Returns:
list: A list of dictionaries containing the data of each repository
"""
import requests
response = requests.get(f"https://api.github.com/users/{username}/repos")
if response.status_code != 200:
raise requests.HTTPError(
f"Unable to fetch user repositories: HTTP {response.status_code}"
)
repositories = []
json = response.json()
for repo in json:
# change the dictionary to include/remove stats
repositories.append(
{
"name": repo["name"],
"description": repo["description"],
"topics": repo["topics"],
"html_url": repo["html_url"],
}
)
return repositories
def save_json_file(repositories, target_folder="./"):
"""This function stores the repository list into a JSON file
Args:
repositories (list): A list with all the repository dictionaries
target_folder (str, optional): The folder where the JSON file will be stored. Defaults to "./".
"""
import json, os
filepath = os.path.join(target_folder, "repositories.json")
with open(filepath, "w") as json_file:
json.dump(repositories, json_file, indent=2)
print(f"Repositories saved on: {filepath}")
def main():
username = input("Type GitHub username: ")
repositories = fetch_repos(username)
save_json_file(repositories)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment