As developers, we’ve all been there – struggling with complex, hard-to-maintain code for making API calls to GitHub. Writing raw HTTP requests, managing tokens, and parsing JSON responses manually can lead to verbose implementations and potential errors. But what if there was a better way?
The Problem with Raw API Calls
Let’s take a look at a typical example of making a raw API call to GitHub:
import requests
TOKEN = "your_github_token"
owner = "khuyentran1401"
repo_name = "Efficient_Python_tricks_and_tools_for_data_scientists"
url = f"https://api.github.com/repos/{owner}/{repo_name}"
headers = {
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/vnd.github.v3+json",
}
response = requests.get(url, headers=headers)
repo = response.json()
print(f"Name: {repo['name']}")
print(f"Full Name: {repo['full_name']}")
print(f"Description: {repo['description']}")
print(f"Stars: {repo['stargazers_count']}")
print(f"Forks: {repo['forks_count']}")
print(f"Language: {repo['language']}")
print(f"URL: {repo['html_url']}")
Outpu:
Name: Efficient_Python_tricks_and_tools_for_data_scientists
Full Name: khuyentran1401/Efficient_Python_tricks_and_tools_for_data_scientists
Description: Efficient Python Tricks and Tools for Data Scientists
Stars: 1445
Forks: 373
Language: Jupyter Notebook
URL: https://github.com/khuyentran1401/Efficient_Python_tricks_and_tools_for_data_scientists
This code works, but it’s cumbersome and prone to errors. We have to manually construct the API URL, handle authentication, and parse the JSON response.
Introducing githubkit
This is where githubkit comes in – a Python library that provides a clean, typed interface for interacting with GitHub’s API. With githubkit, you can make API calls using a simple, intuitive syntax:
from githubkit import Response
from githubkit.versions.latest.models import FullRepository
from githubkit import GitHub
github = GitHub(TOKEN)
resp: Response[FullRepository] = github.rest.repos.get(owner, repo_name)
repo: FullRepository = resp.parsed_data
print(f"Name: {repo.name}")
print(f"Full Name: {repo.full_name}")
print(f"Description: {repo.description}")
print(f"Stars: {repo.stargazers_count}")
print(f"Forks: {repo.forks_count}")
print(f"Language: {repo.language}")
print(f"URL: {repo.html_url}")
Output:
Name: Efficient_Python_tricks_and_tools_for_data_scientists
Full Name: khuyentran1401/Efficient_Python_tricks_and_tools_for_data_scientists
Description: Efficient Python Tricks and Tools for Data Scientists
Stars: 1445
Forks: 373
Language: Jupyter Notebook
URL: https://github.com/khuyentran1401/Efficient_Python_tricks_and_tools_for_data_scientists
githubkit handles the authentication header, makes the API request, and automatically parses the response into a strongly-typed FullRepository
object. The type hints provide IDE support and catch potential errors before runtime.