Build an async GitHub client with aiohttp that fetches all repositories for a user. Implement an async iterator that transparently fetches the next page when the loop consumes the current batch, parsing the Link header for pagination.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a comprehensive request to build an async GitHub client using aiohttp with pagination support. Let me break down what's needed:
An async GitHub client using aiohttp
Fetch all repositories for a user
Implement an async iterator
Transparent pagination by parsing the Link header
Automatically fetch next page when needed
Let me create a complete, production-ready solution:
python
import aiohttp
import asyncio
from typing import AsyncIterator, Dict, Optional, List
from urllib.parse import parse_qs, urlparse
from dataclasses import dataclass
import re
@dataclass
class Repository:
"""Represents a GitHub repository"""
id: int
name: str
full_name: str
description: Optional[str]
url: str
language: Optional[str]
stars: int
forks: int
@classmethod
def from_json(cls, data: Dict) -> "Repository":
return cls(
id=data.get("id"),
name=data.get("name"),
full_name=data.get("full_name"),
description=data.get("description"),
url=data.get("html_url"),
language=data.get("language"),
stars=data.get("stargazers_count", 0),
forks=data.get("forks_count", 0),
)
class LinkHeaderParser:
"""Parse GitHub's Link header for pagination"""
@staticmethod
def parse(link_header: Optional[str]) -> Dict[str, str]:
"""
Parse the Link header and return a dictionary of relations to URLs
Example Link header:
<https://api.github.com/user/repos?page=2>; rel="next",
<https://api.github.com/user/repos?page=5>; rel="last"
"""
links = {}
if not link_header:
return links
for link_part in link_header.split(","):
link_part = link_part.strip()
match = re.match(r'<(.+?)>;\s*rel="(.+?)"', link_part)
if match:
url, rel = match.groups()
links[rel] = url
return links
class RepositoryIterator:
"""Async iterator for fetching repositories with automatic pagination"""
def __init__(self, session: aiohttp.ClientSession, initial_url: str, headers: Dict[str, str]):
self.session = session
self.next_url = initial_url
self.headers = headers
self.current_batch = []
self.batch_index = 0
async def __anext__(self) -> Repository:
if self.batch_index >= len(self.current_batch):
if not self.next_url:
raise StopAsyncIteration
await self._fetch_next_batch()
self.batch_index = 0
if not self.current_batch:
raise StopAsyncIteration
repo = Repository.from_json(self.current_batch[self.batch_index])
self.batch_index += 1
return repo
async def _fetch_next_batch(self):
async with self.session.get(self.next_url, headers=self.headers) as response:
response.raise_for_status()
self.current_batch = await response.json()
link_header = response.headers.get("Link")
links = LinkHeaderParser.parse(link_header)
self.next_url = links.get("next")
def __aiter__(self):
return self
class GitHubClient:
"""Async GitHub API client"""
BASE_URL = "https://api.github.com"
def __init__(self, token: Optional[str] = None):
self.token = token
self.headers = {"Accept": "application/vnd.github.v3+json"}
if token:
self.headers["Authorization"] = f"token {token}"
async def get_user_repositories(self, username: str) -> AsyncIterator[Repository]:
"""Fetch all repositories for a user with automatic pagination"""
url = f"{self.BASE_URL}/users/{username}/repos"
async with aiohttp.ClientSession() as session:
iterator = RepositoryIterator(session, url, self.headers)
async for repo in iterator:
yield repo
async def main():
client = GitHubClient()
print("Fetching repositories for 'torvalds'...\n")
async for repo in client.get_user_repositories("torvalds"):
print(f"{repo.full_name} - ⭐ {repo.stars}")
if __name__ == "__main__":
asyncio.run(main())
The LinkHeaderParser extracts pagination URLs from GitHub's Link header using regex to match the format <url>; rel="relation". The RepositoryIterator manages fetching batches of repositories and automatically loads the next page when the current batch is exhausted. The GitHubClient provides a clean async interface that yields repositories one at a time, handling all pagination transparently. async def get_user_repositories(
self,
username: str,
repo_type: str = "owner",
) -> RepositoryIterator:
"""
Fetch all repositories for a user with automatic pagination
code
Args:
username: GitHub username
repo_type: Type of repos to fetch ("owner", "member", "private", "public", etc.)
Returns:
RepositoryIterator that automatically handles pagination
Raises:
RuntimeError: If session is not initialized
"""
if not self.session:
raise RuntimeError(
"Session not initialized. Use as context manager or call ensure_session()"
)
url = (
f"{self.BASE_URL}/users/{username}/repos"
f"?per_page={self.PER_PAGE}"
f"&type={repo_type}"
f"&sort=updated"
)
return RepositoryIterator(
self.session,
url,
self._get_headers(),
)
For authenticated users, I need to verify the token exists before constructing a similar iterator. The endpoint changes to /user/repos instead of the public user endpoint, and I'll build the same paginated URL structure with the session and headers passed to the iterator.
When fetching a specific repository, I validate the session exists, construct the repo endpoint URL, and make a GET request with appropriate timeout handling. Example 2 demonstrates fetching repositories with authentication by passing a GitHub token to the client, which increases the rate limit. The code iterates through the authenticated user's repositories and displays the first 10, catching any ValueError exceptions that might occur during the process.
For manual session management, I can create a GitHubClient with an existing aiohttp session and fetch repositories for a specific user like "gvanrossum", displaying the first few results before properly closing the session. This approach gives more control over the session lifecycle.
Then I'll gather statistics on repositories from another user—in this case "google"—by iterating through up to 50 repos and aggregating metrics like total stars, forks, and programming language distribution. The output shows summary statistics including average stars per repository and a breakdown of the most common languages used.
I realize I should expand this with more robust error handling, retry mechanisms, and comprehensive documentation. I'm adding logging support, defining repository types as an enum, and creating a dataclass to represent repository objects with all relevant fields like creation dates, privacy status, and fork information.
The Repository class includes a factory method to construct instances from JSON API responses, extracting fields like stargazer counts, fork counts, and watchers. There's also a string representation for easy debugging. I'm implementing a LinkHeaderParser to handle GitHub's pagination through Link headers, which will be essential for iterating through large result sets. Raised when GitHub rate limit is exceeded or authentication fails. The RepositoryIterator class handles async pagination by parsing Link headers and automatically fetching subsequent pages. It maintains the current page of repositories, tracks position within that page, and manages the session and headers needed for requests.
The iterator initializes with a session, starting URL, headers, and retry configuration. When __anext__ is called, it checks if the current page is exhausted—if so and no more pages exist, iteration stops. Otherwise it fetches the next page and returns repositories one at a time, tracking total fetched count and request attempts.
The _fetch_next_page method handles pagination with retry logic, making GET requests to GitHub's API with appropriate headers and handling various error conditions like rate limits and authentication failures. from_json(repo) for repo in data
]
code
logger.debug(f"Fetched {len(self.current_page)} repositories")
# Extract next page URL from Link header
link_header = response.headers.get("Link")
links = LinkHeaderParser.parse(link_header)
self.current_url = links.get("next")
if not self.current_url:
self.exhausted = True
logger.debug("No more pages available")
return # Success
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
last_error = e
logger.warning(
f"Attempt {attempt + 1}/{self.max_retries} faile
I cannot complete this thought as the next thinking is incomplete. # Max results per page (GitHub allows up to 100)
code
def __init__(
self,
token: Optional[str] = None,
session: Optional[aiohttp.ClientSession] = None,
per_page: int = PER_PAGE,
max_retries: int = 3,
):
"""
Initialize GitHub client
Args:
token: GitHub personal access token for higher rate limits
session: Optional aiohttp ClientSession. Creates new if not provided.
per_page: Number of results per page (1-100)
max_retries: Maximum number of retries for failed requests
"""
self.token = token
self.session = session
self._session_owner = session is None
self.per_page = min(per_page, 100)
self.max_retries = max_retries
def _get_headers(self) -> Dict[str, str]:
"""Get request headers with authentication if available"""
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "AsyncGitHubClient/1.0",
}
if self.token:
headers["Authorization"] = f"token {self.token}"
return headers
async def __aenter__(self):
"""Async context manager entry"""
if self._session_owner:
self.session = aiohttp.ClientSession()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit"""
if self._session_owner and self.session:
await self.session.close()
async def ensure_session(self) -> None:
"""Ensure session is initialized"""
if not self.session:
self.session = aiohttp.ClientSession()
async def get_user_
repositories(
self,
username: str,
repo_type: str = "owner",
sort_by: str = "updated",
) -> RepositoryIterator:
"""Fetch all repositories for a user with automatic pagination"""
if not self.session:
raise RuntimeError(
"Session not initialized. Use as context manager or call ensure_session()"
)
code
This method retrieves repositories for a given user, supporting different repository types and sorting options. It validates that a session exists before proceeding, then constructs the appropriate API endpoint URL.
The method builds the GitHub API URL with pagination parameters, repository type filtering, and sort preferences, then returns a RepositoryIterator that handles pagination automatically. It also logs the operation for debugging purposes. raise RuntimeError(
"Session not initialized. Use as context manager or call ensure_session()"
)
code
url = f"{self.BASE_URL}/repos/{owner}/{repo}"
async with self.session.get(
url,
headers=self._get_headers(),
timeout=aiohttp.ClientTimeout(total=15),
) as response:
response.raise_for_status()
data = await response.json()
return Repository.from_json(data)
async def get_user(self, username: str) -> Dict:
"""Fetch user information"""
if not self.session:
raise RuntimeError("Session not initialized")
url = f"{self.BASE_URL}/users/{username}"
async with self.session.get(
I'm making a GET request to fetch the specific repository using the owner and repo parameters, then parsing the JSON response into a Repository object. For the user endpoint, I'm setting up a similar pattern with a GET request to retrieve user information. 60] + "..." if len(repo.description) > 60 else repo.description
print(f" Description: {desc}")
code
count += 1
if count >= 5:
print(f"\n... (showing first 5 of many repositories)")
break
(username: str) -> Tuple[str, Optional[Repository]]:
"""Get the most starred repo for a user"""
try:
async with GitHubClient() as client:
iterator = await client.get_user_repositories(username)
top_repo = None
code
async for repo in iterator:
if top_repo is None or repo.stars > top_repo.stars:
top_repo = repo
break
return username, top_repo
except Exception as e:
logger.error(f"Error fetching repos for {username}: {e}")
return username, None
users = ["torvalds", "gvanrossum", "octocat"]
results = await asyncio.gather(*[get_top_repo(u) for u in users])
print("\nMost recently updated repository for each user:")
for username, repo in results:
if repo:
print(f" {username:20s} → {repo.name:30s} ({repo.stars:,} ⭐)")
else:
print(f" {username:20s} → Failed to fetch")
I'm defining a helper function that retrieves the top repository for each user by iterating through their repos and tracking the one with the most stars, then handling errors gracefully. I'm using asyncio.gather to fetch data for multiple users concurrently, which is more efficient than sequential requests. The results are formatted and displayed showing each user's most starred repository.
The main function sets up logging configuration and orchestrates all the example functions, wrapping everything in error handling to catch any issues during execution. Once all examples complete successfully, it prints a completion message.
Async GitHub Client with aiohttp and Pagination
I'll build a complete, production-ready async GitHub client with transparent pagination via Link header parsing.
Main Implementation
python
Comprehensive Examples
python
Unit Tests
python
Key Features
✅ Transparent Pagination
Automatically fetches next page via Link header
No manual page management needed
✅ Error Handling
Retry logic with exponential backoff
Rate limit detection
Authentication error handling
✅ Flexible Usage
Context manager or manual session management
Support for concurrent operations
Per-page customization
✅ Production Ready
Type hints throughout
Comprehensive logging
Timeout handling
Clean error messages
Run examples:
bash
python examples.py
Run tests:
bash
pytest test_github_client.py -v
# github_client.py
import aiohttp
import asyncio
from typing import AsyncIterator, Dict, Optional, List, Tuple
from dataclasses import dataclass
import re
from enum import Enum
import logging
from urllib.parse import urlparse, parse_qs
logger = logging.getLogger(__name__)
class RepoType(Enum):
"""Types of repositories to fetch"""
OWNER = "owner"
MEMBER = "member"
PUBLIC = "public"
PRIVATE = "private"
ALL = "all"
@dataclass
class Repository:
"""Represents a GitHub repository"""
id: int
name: str
full_name: str
description: Optional[str]
url: str
language: Optional[str]
stars: int
forks: int
watchers: int
is_private: bool
is_fork: bool
created_at: str
updated_at: str
pushed_at: Optional[str]
topics: List[str]
@classmethod
def from_json(cls, data: Dict) -> "Repository":
"""Create Repository from JSON response"""
return cls(
id=data.get("id"),
name=data.get("name"),
full_name=data.get("full_name"),
description=data.get("description"),
url=data.get("html_url"),
language=data.get("language"),
stars=data.get("stargazers_count", 0),
forks=data.get("forks_count", 0),
watchers=data.get("watchers_count", 0),
is_private=data.get("private", False),
is_fork=data.get("fork", False),
created_at=data.get("created_at", ""),
updated_at=data.get("updated_at", ""),
pushed_at=data.get("pushed_at"),
topics=data.get("topics", []),
)
def __repr__(self) -> str:
return f"Repository({self.full_name}, ⭐={self.stars})"
class LinkHeaderParser:
"""
Parse GitHub's Link header for pagination.
Example header:
<https://api.github.com/user/repos?page=2>; rel="next",
<https://api.github.com/user/repos?page=5>; rel="last"
"""
# Regex to parse Link header entries: <url>; rel="relation"
LINK_PATTERN = re.compile(r'<([^>]+)>;\s*rel="([^"]+)"')
@staticmethod
def parse(link_header: Optional[str]) -> Dict[str, str]:
"""
Parse the Link header and return a dictionary of relations to URLs.
Returns:
Dict with keys like "next", "last", "first", "prev" mapping to URLs
"""
links = {}
if not link_header:
return links
# Find all link entries
for match in LinkHeaderParser.LINK_PATTERN.finditer(link_header):
url, rel = match.groups()
links[rel] = url
logger.debug(f"Parsed link relation '{rel}'")
return links
@staticmethod
def get_page_number(url: str) -> Optional[int]:
"""Extract page number from URL query parameters"""
parsed = urlparse(url)
params = parse_qs(parsed.query)
pages = params.get('page', [])
return int(pages[0]) if pages else None
class GitHubError(Exception):
"""Base exception for GitHub client errors"""
pass
class GitHubRateLimitError(GitHubError):
"""Raised when GitHub rate limit is exceeded"""
pass
class GitHubAuthError(GitHubError):
"""Raised when authentication fails"""
pass
class RepositoryIterator:
"""
Async iterator for fetching repositories with automatic pagination.
Transparently handles pagination by:
1. Parsing the Link header to find the next page URL
2. Automatically fetching the next page when current page is exhausted
3. Retrying failed requests with exponential backoff
"""
def __init__(
self,
session: aiohttp.ClientSession,
initial_url: str,
headers: Dict[str, str],
max_retries: int = 3,
):
self.session = session
self.current_url = initial_url
self.headers = headers
self.current_page: List[Repository] = []
self.current_index = 0
self.exhausted = False
self.max_retries = max_retries
self.total_fetched = 0
self.request_count = 0
self.current_page_num = 1
def __aiter__(self):
return self
async def __anext__(self) -> Repository:
"""
Fetch next repository.
Automatically fetches the next page if the current page is exhausted.
"""
# Fetch next page if current page is exhausted
if self.current_index >= len(self.current_page):
if self.exhausted:
logger.info(
f"✓ Iteration complete. Total: {self.total_fetched} repos, "
f"{self.request_count} requests"
)
raise StopAsyncIteration
await self._fetch_next_page()
if not self.current_page:
self.exhausted = True
raise StopAsyncIteration
self.current_index = 0
repo = self.current_page[self.current_index]
self.current_index += 1
self.total_fetched += 1
return repo
async def _fetch_next_page(self) -> None:
"""
Fetch the next page of repositories with retry logic.
Raises:
RuntimeError: If all retries are exhausted
GitHubRateLimitError: If rate limit is exceeded
GitHubAuthError: If authentication fails
"""
if not self.current_url:
self.exhausted = True
return
page_num = LinkHeaderParser.get_page_number(self.current_url)
logger.info(f"📄 Fetching page {page_num or 1}...")
last_error = None
for attempt in range(self.max_retries):
try:
async with self.session.get(
self.current_url,
headers=self.headers,
timeout=aiohttp.ClientTimeout(total=15, connect=10),
) as response:
self.request_count += 1
# Handle rate limiting
if response.status == 403:
error_data = await response.json()
if "API rate limit exceeded" in error_data.get("message", ""):
reset_time = int(response.headers.get("X-RateLimit-Reset", 0))
raise GitHubRateLimitError(
f"Rate limit exceeded. Reset at timestamp {reset_time}. "
f"Use authentication for higher limits."
)
# Handle authentication errors
if response.status == 401:
raise GitHubAuthError("Invalid or expired GitHub token")
# Handle not found
if response.status == 404:
raise GitHubError("Repository or user not found (404)")
response.raise_for_status()
# Parse JSON response
data = await response.json()
# Handle non-list responses
if not isinstance(data, list):
logger.warning(f"Expected list but got {type(data)}")
self.current_page = []
return
# Convert to Repository objects
self.current_page = [
Repository.from_json(repo) for repo in data
]
logger.debug(f"✓ Fetched {len(self.current_page)} repositories")
# Parse Link header for next page
link_header = response.headers.get("Link")
links = LinkHeaderParser.parse(link_header)
self.current_url = links.get("next")
if not self.current_url:
self.exhausted = True
logger.debug("✓ No more pages available")
return # Success!
except (GitHubRateLimitError, GitHubAuthError, GitHubError):
# Don't retry these errors
raise
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
last_error = e
logger.warning(f"⚠️ Attempt {attempt + 1}/{self.max_retries} failed: {e}")
if attempt < self.max_retries - 1:
# Exponential backoff: 1s, 2s, 4s
wait_time = 2 ** attempt
logger.debug(f"⏳ Retrying in {wait_time}s...")
await asyncio.sleep(wait_time)
# All retries exhausted
raise RuntimeError(
f"Failed to fetch repositories after {self.max_retries} attempts. "
f"Last error: {last_error}"
) from last_error
class GitHubClient:
"""
Async GitHub API client for fetching repositories.
Features:
- Authentication with personal access tokens
- Automatic pagination with Link header parsing
- Retry logic with exponential backoff
- Rate limit handling
- Context manager and manual session support
Example:
async with GitHubClient(token="ghp_...") as client:
async for repo in await client.get_user_repositories("torvalds"):
print(repo)
"""
BASE_URL = "https://api.github.com"
PER_PAGE = 30 # GitHub max is 100
def __init__(
self,
token: Optional[str] = None,
session: Optional[aiohttp.ClientSession] = None,
per_page: int = PER_PAGE,
max_retries: int = 3,
):
"""
Initialize GitHub client.
Args:
token: GitHub personal access token (increases rate limits)
session: Optional existing aiohttp.ClientSession
per_page: Results per page (1-100, default 30)
max_retries: Retry attempts for failed requests
"""
self.token = token
self.session = session
self._session_owner = session is None
self.per_page = min(max(per_page, 1), 100)
self.max_retries = max_retries
def _get_headers(self) -> Dict[str, str]:
"""Build request headers with optional authentication"""
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Async-GitHub-Client/1.0",
}
if self.token:
headers["Authorization"] = f"token {self.token}"
return headers
async def __aenter__(self):
"""Async context manager entry"""
if self._session_owner:
self.session = aiohttp.ClientSession()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit"""
if self._session_owner and self.session:
await self.session.close()
async def ensure_session(self) -> None:
"""Initialize session if not already done"""
if not self.session:
self.session = aiohttp.ClientSession()
async def get_user_repositories(
self,
username: str,
repo_type: str = "owner",
sort_by: str = "updated",
direction: str = "desc",
) -> RepositoryIterator:
"""
Fetch all repositories for a user.
Args:
username: GitHub username
repo_type: "owner", "member", "public", "private", etc.
sort_by: "created", "updated", "pushed", "name"
direction: "asc" or "desc"
Returns:
RepositoryIterator that handles pagination automatically
Raises:
RuntimeError: If session not initialized
GitHubAuthError: If authentication fails
GitHubRateLimitError: If rate limit exceeded
"""
if not self.session:
raise RuntimeError("Session not initialized. Use as context manager.")
url = (
f"{self.BASE_URL}/users/{username}/repos"
f"?per_page={self.per_page}"
f"&type={repo_type}"
f"&sort={sort_by}"
f"&direction={direction}"
)
logger.info(f"🔍 Creating iterator for user: {username}")
return RepositoryIterator(
session=self.session,
initial_url=url,
headers=self._get_headers(),
max_retries=self.max_retries,
)
async def get_authenticated_user_repositories(
self,
repo_type: str = "owner",
sort_by: str = "updated",
) -> RepositoryIterator:
"""
Fetch repositories for the authenticated user.
Requires authentication token.
"""
if not self.token:
raise ValueError("Authentication token required for this endpoint")
if not self.session:
raise RuntimeError("Session not initialized")
url = (
f"{self.BASE_URL}/user/repos"
f"?per_page={self.per_page}"
f"&type={repo_type}"
f"&sort={sort_by}"
)
logger.info("🔍 Creating iterator for authenticated user")
return RepositoryIterator(
session=self.session,
initial_url=url,
headers=self._get_headers(),
max_retries=self.max_retries,
)
async def get_repository(self, owner: str, repo: str) -> Repository:
"""Fetch a specific repository"""
if not self.session:
raise RuntimeError("Session not initialized")
url = f"{self.BASE_URL}/repos/{owner}/{repo}"
async with self.session.get(
url,
headers=self._get_headers(),
timeout=aiohttp.ClientTimeout(total=15),
) as response:
response.raise_for_status()
data = await response.json()
return Repository.from_json(data)
async def search_repositories(
self,
query: str,
sort_by: str = "stars",
order: str = "desc",
language: Optional[str] = None,
) -> RepositoryIterator:
"""
Search for repositories.
Args:
query: Search term
sort_by: "stars", "forks", "updated"
order: "asc" or "desc"
language: Optional programming language filter
"""
if not self.session:
raise RuntimeError("Session not initialized")
q_parts = [f'"{query}"']
if language:
q_parts.append(f"language:{language}")
search_query = " ".join(q_parts)
url = (
f"{self.BASE_URL}/search/repositories"
f"?q={search_query}"
f"&sort={sort_by}"
f"&order={order}"
f"&per_page={self.per_page}"
)
# For search results, we need a custom iterator
# that extracts items from the "items" key
class SearchIterator(RepositoryIterator):
async def _fetch_next_page(self) -> None:
if not self.current_url:
self.exhausted = True
return
logger.info("📄 Fetching search results page...")
for attempt in range(self.max_retries):
try:
async with self.session.get(
self.current_url,
headers=self.headers,
timeout=aiohttp.ClientTimeout(total=15),
) as response:
self.request_count += 1
response.raise_for_status()
data = await response.json()
items = data.get("items", [])
self.current_page = [
Repository.from_json(repo) for repo in items
]
link_header = response.headers.get("Link")
links = LinkHeaderParser.parse(link_header)
self.current_url = links.get("next")
if not self.current_url:
self.exhausted = True
return
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if attempt < self.max_retries - 1:
await asyncio.sleep(2 ** attempt)
return SearchIterator(
session=self.session,
initial_url=url,
headers=self._get_headers(),
max_retries=self.max_retries,
)
async def get_rate_limit(self) -> Dict:
"""Get current rate limit status"""
if not self.session:
raise RuntimeError("Session not initialized")
url = f"{self.BASE_URL}/rate_limit"
async with self.session.get(
url,
headers=self._get_headers(),
timeout=aiohttp.ClientTimeout(total=10),
) as response:
response.raise_for_status()
return await response.json()
async def close(self) -> None:
"""Close the session"""
if self.session and self._session_owner:
await self.session.close()
# examples.py
import asyncio
import logging
from github_client import GitHubClient, GitHubError, GitHubRateLimitError
from typing import List, Dict, Tuple
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
async def example_1_basic_iteration():
"""Example 1: Basic repository iteration"""
print("\n" + "="*70)
print("EXAMPLE 1: Basic Repository Iteration")
print("="*70)
async with GitHubClient() as client:
iterator = await client.get_user_repositories("torvalds")
count = 0
async for repo in iterator:
print(f"\n{count + 1}. {repo.full_name}")
print(f" ⭐ Stars: {repo.stars:,} | 🍴 Forks: {repo.forks:,}")
print(f" Language: {repo.language or 'Not specified'}")
if repo.description:
desc = repo.description[:60] + "..." if len(repo.description) > 60 else repo.description
print(f" Description: {desc}")
count += 1
if count >= 5:
break
async def example_2_statistics():
"""Example 2: Calculate repository statistics"""
print("\n" + "="*70)
print("EXAMPLE 2: Repository Statistics")
print("="*70)
async with GitHubClient() as client:
iterator = await client.get_user_repositories("google", per_page=50)
stats = {
"total_stars": 0,
"total_forks": 0,
"total_repos": 0,
"languages": {},
"most_popular": None,
"total_watchers": 0,
}
async for repo in iterator:
stats["total_stars"] += repo.stars
stats["total_forks"] += repo.forks
stats["total_watchers"] += repo.watchers
stats["total_repos"] += 1
if repo.language:
stats["languages"][repo.language] = stats["languages"].get(repo.language, 0) + 1
if not stats["most_popular"] or repo.stars > stats["most_popular"].stars:
stats["most_popular"] = repo
if stats["total_repos"] >= 50:
break
print(f"\n📊 Statistics for 'google' (first 50 repos):")
print(f" Total repos: {stats['total_repos']:,}")
print(f" Total stars: {stats['total_stars']:,}")
print(f" Total forks: {stats['total_forks']:,}")
print(f" Total watchers: {stats['total_watchers']:,}")
print(f" Average stars/repo: {stats['total_stars'] / stats['total_repos']:.1f}")
print(f"\n Most popular: {stats['most_popular'].full_name} ({stats['most_popular'].stars:,} ⭐)")
print(f"\n Top languages:")
for lang, count in sorted(
stats["languages"].items(),
key=lambda x: x[1],
reverse=True
)[:5]:
print(f" • {lang}: {count} repos")
async def example_3_filtering():
"""Example 3: Filter repositories by criteria"""
print("\n" + "="*70)
print("EXAMPLE 3: Filtering Repositories")
print("="*70)
async with GitHubClient() as client:
iterator = await client.get_user_repositories("microsoft")
high_star_repos = []
checked = 0
print("\nFinding repos with 500+ stars...")
async for repo in iterator:
checked += 1
if repo.stars >= 500:
high_star_repos.append(repo)
if checked >= 100:
break
print(f"\n✓ Found {len(high_star_repos)} repos with 500+ stars (from {checked} checked):\n")
for i, repo in enumerate(sorted(high_star_repos, key=lambda r: r.stars, reverse=True)[:10], 1):
print(f" {i}. {repo.name}")
print(f" ⭐ {repo.stars:,} | 🍴 {repo.forks:,} | Language: {repo.language}")
async def example_4_concurrent_users():
"""Example 4: Fetch repositories from multiple users concurrently"""
print("\n" + "="*70)
print("EXAMPLE 4: Concurrent Multi-User Fetch")
print("="*70)
async def get_user_stats(username: str) -> Tuple[str, Dict]:
"""Fetch stats for a user's repositories"""
try:
async with GitHubClient() as client:
iterator = await client.get_user_repositories(username)
total_stars = 0
repo_count = 0
top_repo = None
async for repo in iterator:
total_stars += repo.stars
repo_count += 1
if not top_repo or repo.stars > top_repo.stars:
top_repo = repo
if repo_count >= 30: # Limit to first 30
break
return username, {
"repos": repo_count,
"total_stars": total_stars,
"avg_stars": total_stars / repo_count if repo_count else 0,
"top_repo": top_repo,
}
except GitHubError as e:
return username, {"error": str(e)}
users = ["torvalds", "gvanrossum", "octocat", "evanw"]
print(f"\nFetching stats for {len(users)} users concurrently...")
results = await asyncio.gather(*[get_user_stats(u) for u in users])
print("\n📈 Repository Statistics by User:")
for username, stats in results:
if "error" in stats:
print(f"\n {username:20s} - Error: {stats['error']}")
else:
print(f"\n {username:20s}")
print(f" Repos analyzed: {stats['repos']}")
print(f" Total stars: {stats['total_stars']:,}")
print(f" Avg stars/repo: {stats['avg_stars']:.1f}")
if stats['top_repo']:
print(f" Top repo: {stats['top_repo'].name} ({stats['top_repo'].stars:,} ⭐)")
async def example_5_search():
"""Example 5: Search for repositories"""
print("\n" + "="*70)
print("EXAMPLE 5: Repository Search")
print("="*70)
async with GitHubClient() as client:
print("\nSearching for 'async python' repositories sorted by stars...")
iterator = await client.search_repositories(
"async python",
language="Python",
sort_by="stars"
)
count = 0
async for repo in iterator:
print(f"\n{count + 1}. {repo.full_name}")
print(f" ⭐ {repo.stars:,} | 🍴 {repo.forks:,}")
print(f" {repo.description or 'No description'}")
count += 1
if count >= 5:
break
async def example_6_error_handling():
"""Example 6: Error handling"""
print("\n" + "="*70)
print("EXAMPLE 6: Error Handling")
print("="*70)
async with GitHubClient() as client:
# Test rate limits
print("\nChecking rate limits...")
try:
limits = await client.get_rate_limit()
core = limits['rate_limit']['resources']['core']
print(f" Limit: {core['limit']}")
print(f" Remaining: {core['remaining']}")
print(f" Reset: {core['reset']}")
except GitHubRateLimitError as e:
print(f" ⚠️ Rate limit error: {e}")
except GitHubError as e:
print(f" ⚠️ GitHub error: {e}")
# Test invalid user
print("\nTesting invalid user...")
try:
iterator = await client.get_user_repositories("invalid_user_xyz_12345")
async for repo in iterator:
print(repo)
except GitHubError as e:
print(f" ✓ Caught expected error: {e}")
async def example_7_manual_session():
"""Example 7: Manual session management"""
print("\n" + "="*70)
print("EXAMPLE 7: Manual Session Management")
print("="*70)
import aiohttp
# Reuse same session for multiple requests
session = aiohttp.ClientSession()
try:
client = GitHubClient(session=session, per_page=50)
for username in ["python", "django"]:
print(f"\n📦 Fetching from '{username}':")
iterator = await client.get_user_repositories(username)
count = 0
async for repo in iterator:
print(f" {repo.name}")
count += 1
if count >= 3:
break
finally:
await session.close()
async def main():
"""Run all examples"""
try:
await example_1_basic_iteration()
await example_2_statistics()
await example_3_filtering()
await example_4_concurrent_users()
await example_5_search()
await example_6_error_handling()
await example_7_manual_session()
print("\n" + "="*70)
print("✓ All examples completed successfully!")
print("="*70 + "\n")
except KeyboardInterrupt:
print("\n\nInterrupted by user")
except Exception as e:
print(f"\n✗ Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
asyncio.run(main())