Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Python script that interacts with a web API, processes JSON data, and stores the resu filter_list
Author
Message
Python script that interacts with a web API, processes JSON data, and stores the resu #1
Install requests library: pip install requests

python

import requests
import sqlite3

def fetch_github_repos(username):
url = f"https://api.github.com/users/{username}/repos"
response = requests.get(url)

if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to fetch GitHub repositories. Status Code: {response.status_code}")

def create_database():
connection = sqlite3.connect("github_repos.db")
cursor = connection.cursor()

cursor.execute('''
CREATE TABLE IF NOT EXISTS repositories (
id INTEGER PRIMARY KEY,
name TEXT,
description TEXT,
language TEXT
)
''')

connection.commit()
connection.close()

def insert_repository(repo):
connection = sqlite3.connect("github_repos.db")
cursor = connection.cursor()

cursor.execute('''
INSERT INTO repositories (name, description, language)
VALUES (?, ?, ?)
''', (repo['name'], repo.get('description', ''), repo.get('language', '')))

connection.commit()
connection.close()

def main():
username = input("Enter GitHub username: ")

try:
repos = fetch_github_repos(username)
create_database()

for repo in repos:
insert_repository(repo)

print("GitHub repositories information successfully stored in the database.")
except Exception as e:
print(f"Error: {e}")

if __name__ == "__main__":
main()

Explanation:

The script uses the requests library to make HTTP requests to the GitHub API.
It defines functions to fetch GitHub repositories, create an SQLite database, and insert repository data.
The database has a table named repositories with columns for repository name, description, and language.
The main function prompts the user for a GitHub username, fetches repositories, and stores them in the database.
The script handles errors gracefully and provides informative messages

Reply







Users browsing this thread: 1 Guest(s)