Implementing async GitHub client with pagination
The plan is to implement a GithubClient with an async iterator handling automatic page fetching by parsing Link headers, including a robust parse_link_header function and usage example with proper async context management and aiohttp usage.
import asyncio
from typing import AsyncIterator, Dict, List, Optional
import aiohttp
def parse_link_header(link_header: Optional[str]) -> Dict[str, str]:
"""
Parse an RFC-5988 Link header into a dict of {rel: url}.
Example header:
<https://api.github.com/user/repos?page=2>; rel="next",
<https://api.github.com/user/repos?page=34>; rel="last"
"""
links: Dict[str, str] = {}
if not link_header:
return links
for part in link_header.split(","):
section = part.strip().split(";")
if len(section) < 2:
continue
url_part = section[0].strip()
rel_part = section[1].strip()
# url_part: <https://...>
if not (url_part.startswith("<") and url_part.endswith(">")):
continue
url = url_part[1:-1]
# rel_part: rel="next"
if "rel=" in rel_part:
rel_value = rel_part.split("=", 1)[1].strip().strip('"')
links[rel_value] = url
return links
class RepoIterator:
"""
Asynchronous iterator over all repositories returned by the GitHub API
for a user. It transparently follows pagination.
"""
def __init__(self, session: aiohttp.ClientSession, url: str, headers: Dict[str, str]):
self._session = session
self._next_url = url # URL to fetch next, None when done
self._headers = headers
self._buffer: List[dict] = []
self._idx = 0
self._exhausted = False
def __aiter__(self) -> "RepoIterator":
return self
async def __anext__(self) -> dict:
# If we have buffered items, serve them first
if self._idx < len(self._buffer):
item = self._buffer[self._idx]
self._idx += 1
return item
# Buffer exhausted, fetch next page if available
if self._exhausted or self._next_url is None:
raise StopAsyncIteration
async with self._session.get(self._next_url, headers=self._headers) as resp:
if resp.status != 200:
# In a real implementation, you'd probably raise an exception here
raise StopAsyncIteration
# GitHub returns a JSON array of repos for this endpoint
self._buffer = await resp.json()
self._idx = 0
# Parse Link header for pagination
link_header = resp.headers.get("Link")
links = parse_link_header(link_header)
self._next_url = links.get("next")
# If there is no "next" relation, mark exhausted after this buffer
if not self._next_url:
self._exhausted = True
# After refilling buffer, recurse to serve the first element
return await self.__anext__()
class GitHubClient:
def __init__(self, token: Optional[str] = None, session: Optional[aiohttp.ClientSession] = None):
self._session_provided = session is not None
self._session = session or aiohttp.ClientSession()
self._token = token
async def close(self) -> None:
if not self._session_provided:
await self._session.close()
async def __aenter__(self) -> "GitHubClient":
return self
async def __aexit__(self, exc_type, exc, tb) -> None:
await self.close()
def _headers(self) -> Dict[str, str]:
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "aiohttp-client"
}
if self._token:
headers["Authorization"] = f"token {self._token}"
return headers
def iter_user_repos(self, username: str, per_page: int = 100) -> AsyncIterator[dict]:
"""
Return an async iterator over all repos for a given user.
`per_page` controls how many repos are requested per page (max 100).
"""
url = f"https://api.github.com/users/{username}/repos?per_page={per_page}"
return RepoIterator(self._session, url, self._headers())
# Example usage
async def main():
# Optionally provide a personal access token to avoid low rate limits
async with GitHubClient(token=None) as gh:
async for repo in gh.iter_user_repos("octocat", per_page=50):
print(repo["full_name"])
if __name__ == "__main__":
asyncio.run(main())
This defines a GitHubClient with an iter_user_repos method that returns an asynchronous iterator. The iterator lazily fetches pages of repositories from the GitHub API, parses the Link header to find the URL for the next page (rel="next"), and yields repositories one by one. When there are no more pages, it raises StopAsyncIteration, ending the loop.