or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

actions.mdapi-client.mdapps.mdexceptions.mdhttp-implementations.mdindex.mdrouting.mdsansio.md
tile.json

tessl/pypi-gidgethub

An asynchronous GitHub API library designed as a sans-I/O library for GitHub API access

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/gidgethub@5.4.x

To install, run

npx @tessl/cli install tessl/pypi-gidgethub@5.4.0

index.mddocs/

gidgethub

An asynchronous GitHub API library designed as a sans-I/O library that performs no I/O operations itself. gidgethub allows users to choose their preferred HTTP library while handling GitHub-specific API details, making it ideal for GitHub integrations, bot development, automation tools, and any application requiring GitHub API access.

Package Information

  • Package Name: gidgethub
  • Language: Python
  • Installation: pip install gidgethub
  • Requirements: Python 3.8+
  • Dependencies: uritemplate>=3.0.1, PyJWT[crypto]>=2.4.0

Core Imports

import gidgethub
# Access version
print(gidgethub.__version__)  # "5.4.0"

For using the abstract base class:

from gidgethub.abc import GitHubAPI

For HTTP client implementations:

from gidgethub.aiohttp import GitHubAPI
from gidgethub.httpx import GitHubAPI  
from gidgethub.tornado import GitHubAPI

For sans-I/O functions:

import gidgethub.sansio

Basic Usage

import asyncio
import aiohttp
from gidgethub.aiohttp import GitHubAPI

async def main():
    async with aiohttp.ClientSession() as session:
        gh = GitHubAPI(session, "my-app/1.0")
        
        # Get repository information
        repo = await gh.getitem("/repos/octocat/Hello-World")
        print(f"Repository: {repo['name']}")
        print(f"Stars: {repo['stargazers_count']}")
        
        # Create an issue (requires authentication)
        # gh = GitHubAPI(session, "my-app/1.0", oauth_token="your_token")
        # issue = await gh.post("/repos/owner/repo/issues", 
        #                       data={"title": "New issue", "body": "Issue body"})

asyncio.run(main())

Architecture

gidgethub uses a sans-I/O architecture that separates HTTP handling from GitHub API logic:

  • Sans-I/O Core (gidgethub.sansio): Pure functions for request/response processing, webhook validation, and rate limit handling
  • Abstract Base Class (gidgethub.abc): High-level API interface with HTTP method implementations
  • HTTP Implementations: Concrete implementations for popular async HTTP libraries (aiohttp, httpx, tornado)
  • Specialized Modules: GitHub Apps authentication, webhook routing, and GitHub Actions support

This design enables maximum reusability across different HTTP libraries while maintaining consistent GitHub API behavior patterns.

Capabilities

Exception Handling

Comprehensive exception hierarchy for GitHub API error responses including rate limiting, validation errors, and HTTP status code handling.

class GitHubException(Exception): ...
class HTTPException(GitHubException): ...
class BadRequest(HTTPException): ...
class RateLimitExceeded(BadRequest): ...
class ValidationFailure(GitHubException): ...

Exception Handling

Sans-I/O Core Functions

Pure functions for HTTP request/response processing, webhook validation, rate limiting, and URL formatting without performing any I/O operations.

def validate_event(payload: bytes, *, signature: str, secret: str) -> None: ...
def create_headers(requester: str, *, accept: str = ..., oauth_token: Optional[str] = None, jwt: Optional[str] = None) -> Dict[str, str]: ...
def decipher_response(status_code: int, headers: Mapping[str, str], body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]: ...
def format_url(url: str, url_vars: Optional[variable.VariableValueDict], *, base_url: str = DOMAIN) -> str: ...

Sans-I/O Functions

Abstract Base Class

High-level GitHub API interface providing HTTP method implementations (GET, POST, PUT, PATCH, DELETE) with authentication, caching, and GraphQL support.

class GitHubAPI(abc.ABC):
    def __init__(self, requester: str, *, oauth_token: Optional[str] = None, cache: Optional[CACHE_TYPE] = None, base_url: str = sansio.DOMAIN) -> None: ...
    async def getitem(self, url: str, url_vars: Optional[variable.VariableValueDict] = {}, **kwargs) -> Any: ...
    async def getstatus(self, url: str, url_vars: Optional[variable.VariableValueDict] = {}, **kwargs) -> int: ...
    async def post(self, url: str, url_vars: Optional[variable.VariableValueDict] = {}, *, data: Any, **kwargs) -> Any: ...
    async def graphql(self, query: str, *, endpoint: str = "https://api.github.com/graphql", **variables: Any) -> Any: ...

API Client

HTTP Client Implementations

Ready-to-use implementations of the abstract base class for popular asynchronous HTTP libraries including aiohttp, httpx, and Tornado.

# aiohttp implementation
class GitHubAPI(gh_abc.GitHubAPI):
    def __init__(self, session: aiohttp.ClientSession, *args: Any, **kwargs: Any) -> None: ...

# httpx implementation  
class GitHubAPI(gh_abc.GitHubAPI):
    def __init__(self, client: httpx.AsyncClient, *args: Any, **kwargs: Any) -> None: ...

HTTP Implementations

Webhook Event Routing

Event routing system for handling GitHub webhook events with pattern matching and automatic dispatch to registered callback functions.

class Router:
    def __init__(self, *other_routers: "Router") -> None: ...
    def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None: ...
    def register(self, event_type: str, **data_detail: Any) -> Callable[[AsyncCallback], AsyncCallback]: ...
    def fetch(self, event: sansio.Event) -> FrozenSet[AsyncCallback]: ...
    async def dispatch(self, event: sansio.Event, *args: Any, **kwargs: Any) -> None: ...

Webhook Routing

GitHub Apps Authentication

Support for GitHub Apps authentication including JWT creation and installation access token retrieval for app-based integrations.

def get_jwt(*, app_id: str, private_key: str, expiration: int = 10 * 60) -> str: ...
async def get_installation_access_token(gh: GitHubAPI, *, installation_id: str, app_id: str, private_key: str) -> Dict[str, Any]: ...

GitHub Apps

GitHub Actions Support

Utilities for GitHub Actions workflows including environment variable management, path manipulation, and logging command output.

def workspace() -> pathlib.Path: ...
def event() -> Any: ...
def command(cmd: str, data: str = "", **parameters: str) -> None: ...
def setenv(name: str, value: str) -> None: ...
def addpath(path: Union[str, "os.PathLike[str]"]) -> None: ...

GitHub Actions

Types

from typing import Any, AsyncGenerator, Dict, Mapping, MutableMapping, Optional, Tuple, Callable, Awaitable, FrozenSet, Union
from uritemplate import variable
import http
import datetime
import pathlib
import os

# Cache type for HTTP caching
CACHE_TYPE = MutableMapping[str, Tuple[Optional[str], Optional[str], Any, Optional[str]]]

# Callback type for webhook routing
AsyncCallback = Callable[..., Awaitable[None]]

# Rate limit information
class RateLimit:
    limit: int
    remaining: int  
    reset_datetime: datetime.datetime
    
    def __init__(self, *, limit: int, remaining: int, reset_epoch: float) -> None: ...
    def __bool__(self) -> bool: ...
    @classmethod
    def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]: ...

# Webhook event data
class Event:
    data: Any
    event: str
    delivery_id: str
    
    def __init__(self, data: Any, *, event: str, delivery_id: str) -> None: ...
    @classmethod  
    def from_http(cls, headers: Mapping[str, str], body: bytes, *, secret: Optional[str] = None) -> "Event": ...