0
# gidgethub
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: gidgethub
7
- **Language**: Python
8
- **Installation**: `pip install gidgethub`
9
- **Requirements**: Python 3.8+
10
- **Dependencies**: uritemplate>=3.0.1, PyJWT[crypto]>=2.4.0
11
12
## Core Imports
13
14
```python
15
import gidgethub
16
# Access version
17
print(gidgethub.__version__) # "5.4.0"
18
```
19
20
For using the abstract base class:
21
22
```python
23
from gidgethub.abc import GitHubAPI
24
```
25
26
For HTTP client implementations:
27
28
```python
29
from gidgethub.aiohttp import GitHubAPI
30
from gidgethub.httpx import GitHubAPI
31
from gidgethub.tornado import GitHubAPI
32
```
33
34
For sans-I/O functions:
35
36
```python
37
import gidgethub.sansio
38
```
39
40
## Basic Usage
41
42
```python
43
import asyncio
44
import aiohttp
45
from gidgethub.aiohttp import GitHubAPI
46
47
async def main():
48
async with aiohttp.ClientSession() as session:
49
gh = GitHubAPI(session, "my-app/1.0")
50
51
# Get repository information
52
repo = await gh.getitem("/repos/octocat/Hello-World")
53
print(f"Repository: {repo['name']}")
54
print(f"Stars: {repo['stargazers_count']}")
55
56
# Create an issue (requires authentication)
57
# gh = GitHubAPI(session, "my-app/1.0", oauth_token="your_token")
58
# issue = await gh.post("/repos/owner/repo/issues",
59
# data={"title": "New issue", "body": "Issue body"})
60
61
asyncio.run(main())
62
```
63
64
## Architecture
65
66
gidgethub uses a sans-I/O architecture that separates HTTP handling from GitHub API logic:
67
68
- **Sans-I/O Core** (`gidgethub.sansio`): Pure functions for request/response processing, webhook validation, and rate limit handling
69
- **Abstract Base Class** (`gidgethub.abc`): High-level API interface with HTTP method implementations
70
- **HTTP Implementations**: Concrete implementations for popular async HTTP libraries (aiohttp, httpx, tornado)
71
- **Specialized Modules**: GitHub Apps authentication, webhook routing, and GitHub Actions support
72
73
This design enables maximum reusability across different HTTP libraries while maintaining consistent GitHub API behavior patterns.
74
75
## Capabilities
76
77
### Exception Handling
78
79
Comprehensive exception hierarchy for GitHub API error responses including rate limiting, validation errors, and HTTP status code handling.
80
81
```python { .api }
82
class GitHubException(Exception): ...
83
class HTTPException(GitHubException): ...
84
class BadRequest(HTTPException): ...
85
class RateLimitExceeded(BadRequest): ...
86
class ValidationFailure(GitHubException): ...
87
```
88
89
[Exception Handling](./exceptions.md)
90
91
### Sans-I/O Core Functions
92
93
Pure functions for HTTP request/response processing, webhook validation, rate limiting, and URL formatting without performing any I/O operations.
94
95
```python { .api }
96
def validate_event(payload: bytes, *, signature: str, secret: str) -> None: ...
97
def create_headers(requester: str, *, accept: str = ..., oauth_token: Optional[str] = None, jwt: Optional[str] = None) -> Dict[str, str]: ...
98
def decipher_response(status_code: int, headers: Mapping[str, str], body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]: ...
99
def format_url(url: str, url_vars: Optional[variable.VariableValueDict], *, base_url: str = DOMAIN) -> str: ...
100
```
101
102
[Sans-I/O Functions](./sansio.md)
103
104
### Abstract Base Class
105
106
High-level GitHub API interface providing HTTP method implementations (GET, POST, PUT, PATCH, DELETE) with authentication, caching, and GraphQL support.
107
108
```python { .api }
109
class GitHubAPI(abc.ABC):
110
def __init__(self, requester: str, *, oauth_token: Optional[str] = None, cache: Optional[CACHE_TYPE] = None, base_url: str = sansio.DOMAIN) -> None: ...
111
async def getitem(self, url: str, url_vars: Optional[variable.VariableValueDict] = {}, **kwargs) -> Any: ...
112
async def getstatus(self, url: str, url_vars: Optional[variable.VariableValueDict] = {}, **kwargs) -> int: ...
113
async def post(self, url: str, url_vars: Optional[variable.VariableValueDict] = {}, *, data: Any, **kwargs) -> Any: ...
114
async def graphql(self, query: str, *, endpoint: str = "https://api.github.com/graphql", **variables: Any) -> Any: ...
115
```
116
117
[API Client](./api-client.md)
118
119
### HTTP Client Implementations
120
121
Ready-to-use implementations of the abstract base class for popular asynchronous HTTP libraries including aiohttp, httpx, and Tornado.
122
123
```python { .api }
124
# aiohttp implementation
125
class GitHubAPI(gh_abc.GitHubAPI):
126
def __init__(self, session: aiohttp.ClientSession, *args: Any, **kwargs: Any) -> None: ...
127
128
# httpx implementation
129
class GitHubAPI(gh_abc.GitHubAPI):
130
def __init__(self, client: httpx.AsyncClient, *args: Any, **kwargs: Any) -> None: ...
131
```
132
133
[HTTP Implementations](./http-implementations.md)
134
135
### Webhook Event Routing
136
137
Event routing system for handling GitHub webhook events with pattern matching and automatic dispatch to registered callback functions.
138
139
```python { .api }
140
class Router:
141
def __init__(self, *other_routers: "Router") -> None: ...
142
def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None: ...
143
def register(self, event_type: str, **data_detail: Any) -> Callable[[AsyncCallback], AsyncCallback]: ...
144
def fetch(self, event: sansio.Event) -> FrozenSet[AsyncCallback]: ...
145
async def dispatch(self, event: sansio.Event, *args: Any, **kwargs: Any) -> None: ...
146
```
147
148
[Webhook Routing](./routing.md)
149
150
### GitHub Apps Authentication
151
152
Support for GitHub Apps authentication including JWT creation and installation access token retrieval for app-based integrations.
153
154
```python { .api }
155
def get_jwt(*, app_id: str, private_key: str, expiration: int = 10 * 60) -> str: ...
156
async def get_installation_access_token(gh: GitHubAPI, *, installation_id: str, app_id: str, private_key: str) -> Dict[str, Any]: ...
157
```
158
159
[GitHub Apps](./apps.md)
160
161
### GitHub Actions Support
162
163
Utilities for GitHub Actions workflows including environment variable management, path manipulation, and logging command output.
164
165
```python { .api }
166
def workspace() -> pathlib.Path: ...
167
def event() -> Any: ...
168
def command(cmd: str, data: str = "", **parameters: str) -> None: ...
169
def setenv(name: str, value: str) -> None: ...
170
def addpath(path: Union[str, "os.PathLike[str]"]) -> None: ...
171
```
172
173
[GitHub Actions](./actions.md)
174
175
## Types
176
177
```python { .api }
178
from typing import Any, AsyncGenerator, Dict, Mapping, MutableMapping, Optional, Tuple, Callable, Awaitable, FrozenSet, Union
179
from uritemplate import variable
180
import http
181
import datetime
182
import pathlib
183
import os
184
185
# Cache type for HTTP caching
186
CACHE_TYPE = MutableMapping[str, Tuple[Optional[str], Optional[str], Any, Optional[str]]]
187
188
# Callback type for webhook routing
189
AsyncCallback = Callable[..., Awaitable[None]]
190
191
# Rate limit information
192
class RateLimit:
193
limit: int
194
remaining: int
195
reset_datetime: datetime.datetime
196
197
def __init__(self, *, limit: int, remaining: int, reset_epoch: float) -> None: ...
198
def __bool__(self) -> bool: ...
199
@classmethod
200
def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]: ...
201
202
# Webhook event data
203
class Event:
204
data: Any
205
event: str
206
delivery_id: str
207
208
def __init__(self, data: Any, *, event: str, delivery_id: str) -> None: ...
209
@classmethod
210
def from_http(cls, headers: Mapping[str, str], body: bytes, *, secret: Optional[str] = None) -> "Event": ...
211
```