0
# PyGithub
1
2
A comprehensive Python client library providing full access to the GitHub REST API v3. PyGithub enables developers to programmatically manage GitHub resources including repositories, user profiles, organizations, issues, pull requests, and other GitHub entities within their Python applications.
3
4
## Package Information
5
6
- **Package Name**: PyGithub
7
- **Language**: Python
8
- **Installation**: `pip install PyGithub`
9
- **Documentation**: https://pygithub.readthedocs.io/en/stable/
10
- **Repository**: https://github.com/pygithub/pygithub
11
12
## Core Imports
13
14
```python
15
import github
16
```
17
18
Most common usage with main Github client:
19
20
```python
21
from github import Github
22
```
23
24
Individual components can be imported directly:
25
26
```python
27
from github import Auth, GithubIntegration, GithubException
28
```
29
30
## Basic Usage
31
32
```python
33
from github import Github, Auth
34
35
# Authentication using personal access token
36
auth = Auth.Token("your_access_token")
37
38
# Create Github instance
39
g = Github(auth=auth)
40
41
# Get a user
42
user = g.get_user("octocat")
43
print(f"User: {user.name} ({user.login})")
44
print(f"Public repos: {user.public_repos}")
45
46
# Get a repository
47
repo = g.get_repo("octocat/Hello-World")
48
print(f"Repository: {repo.full_name}")
49
print(f"Description: {repo.description}")
50
print(f"Language: {repo.language}")
51
52
# Create an issue
53
issue = repo.create_issue(
54
title="Found a bug",
55
body="I'm having trouble with...",
56
labels=["bug"]
57
)
58
print(f"Created issue #{issue.number}")
59
60
# List repository issues
61
for issue in repo.get_issues(state='open'):
62
print(f"Issue #{issue.number}: {issue.title}")
63
```
64
65
## Architecture
66
67
PyGithub follows a hierarchical object-oriented design that mirrors the GitHub API structure:
68
69
- **Github**: Main client providing entry points to GitHub API resources
70
- **Resource Objects**: Individual GitHub entities (Repository, NamedUser, Organization, Issue, PullRequest, etc.)
71
- **Authentication**: Pluggable authentication system supporting multiple GitHub auth methods
72
- **Pagination**: Automatic handling of paginated API responses through PaginatedList
73
- **Error Handling**: Comprehensive exception hierarchy for different API error conditions
74
75
All GitHub objects inherit from GithubObject, providing consistent behavior for lazy loading, attribute access, and API interaction patterns.
76
77
## Capabilities
78
79
### Authentication and Client Setup
80
81
Multiple authentication methods for accessing GitHub API including personal access tokens, GitHub Apps, OAuth, and legacy authentication. The Github client serves as the main entry point for all API operations.
82
83
```python { .api }
84
class Github:
85
def __init__(
86
self,
87
login_or_token: str = None, # deprecated, use auth parameter
88
password: str = None, # deprecated, use auth parameter
89
jwt: str = None, # deprecated, use auth parameter
90
app_auth: AppAuthentication = None, # deprecated, use auth parameter
91
base_url: str = "https://api.github.com",
92
timeout: int = 15,
93
user_agent: str = "PyGithub/Python",
94
per_page: int = 30,
95
verify: Union[bool, str] = True,
96
retry: Union[int, GithubRetry] = None,
97
pool_size: int = None,
98
seconds_between_requests: float = None,
99
seconds_between_writes: float = None,
100
auth: Auth = None,
101
lazy: bool = False
102
): ...
103
104
# Authentication classes
105
class Auth:
106
class Token:
107
def __init__(self, token: str): ...
108
109
class Login:
110
def __init__(self, username: str, password: str): ...
111
112
class AppAuth:
113
def __init__(self, app_id: str, private_key: str): ...
114
```
115
116
[Authentication](./authentication.md)
117
118
### Repository Management
119
120
Comprehensive repository operations including content management, branch operations, collaboration features, webhooks, and repository settings. Supports both repository-level operations and Git-level operations.
121
122
```python { .api }
123
class Repository:
124
def get_contents(self, path: str, ref: str = None): ...
125
def create_file(self, path: str, message: str, content: str | bytes, branch: str = None, committer: InputGitAuthor = None, author: InputGitAuthor = None): ...
126
def update_file(self, path: str, message: str, content: str, sha: str, branch: str = None): ...
127
def get_branches(self): ...
128
def get_branch(self, branch: str): ...
129
def create_git_ref(self, ref: str, sha: str): ...
130
def get_collaborators(self): ...
131
def add_to_collaborators(self, collaborator: str, permission: str = None): ...
132
```
133
134
[Repository Management](./repository-management.md)
135
136
### User and Organization Management
137
138
User profile access, organization management, membership operations, and social features. Handles both public user information and authenticated user capabilities.
139
140
```python { .api }
141
class NamedUser:
142
def get_repos(self, type: str = None, sort: str = None, direction: str = None): ...
143
def get_gists(self): ...
144
def get_followers(self): ...
145
def get_following(self): ...
146
def get_starred(self): ...
147
148
class AuthenticatedUser:
149
def create_repo(self, name: str, description: str = None, private: bool = False): ...
150
def create_gist(self, description: str, files: dict, public: bool = True): ...
151
def get_notifications(self): ...
152
153
class Organization:
154
def get_repos(self, type: str = None): ...
155
def create_repo(self, name: str, description: str = None): ...
156
def get_members(self, filter: str = None, role: str = None): ...
157
def get_teams(self): ...
158
def create_team(self, name: str, repo_names: list = None): ...
159
```
160
161
[User and Organization Management](./user-organization-management.md)
162
163
### Issues and Pull Requests
164
165
Complete issue and pull request lifecycle management including creation, editing, commenting, labeling, milestone assignment, and review processes.
166
167
```python { .api }
168
class Issue:
169
def edit(self, title: str = None, body: str = None, assignee: str = None, state: str = None): ...
170
def create_comment(self, body: str): ...
171
def get_comments(self): ...
172
def add_to_labels(self, *labels): ...
173
def remove_from_labels(self, *labels): ...
174
175
class PullRequest:
176
def merge(self, commit_message: str = None, commit_title: str = None, merge_method: str = None): ...
177
def get_commits(self): ...
178
def get_files(self): ...
179
def create_review(self, body: str = None, event: str = None, comments: list = None): ...
180
def get_reviews(self): ...
181
```
182
183
[Issues and Pull Requests](./issues-pull-requests.md)
184
185
### Git Operations
186
187
Low-level Git operations including commit creation, tree manipulation, blob handling, references, and tags. Provides direct access to Git objects and operations.
188
189
```python { .api }
190
class Repository:
191
def create_git_commit(self, message: str, tree: str, parents: list): ...
192
def create_git_tree(self, tree: list, base_tree: str = None): ...
193
def create_git_blob(self, content: str, encoding: str): ...
194
def get_git_ref(self, ref: str): ...
195
def create_git_tag(self, tag: str, message: str, object: str, type: str): ...
196
197
# Git object classes
198
class GitCommit:
199
@property
200
def sha(self) -> str: ...
201
@property
202
def message(self) -> str: ...
203
@property
204
def author(self) -> GitAuthor: ...
205
206
class GitTree:
207
@property
208
def sha(self) -> str: ...
209
@property
210
def tree(self) -> list: ...
211
```
212
213
[Git Operations](./git-operations.md)
214
215
### Search and Discovery
216
217
Search functionality across repositories, users, issues, code, commits, and topics. Provides comprehensive search capabilities with filtering and sorting options.
218
219
```python { .api }
220
class Github:
221
def search_repositories(self, query: str, sort: str = None, order: str = None): ...
222
def search_users(self, query: str, sort: str = None, order: str = None): ...
223
def search_issues(self, query: str, sort: str = None, order: str = None): ...
224
def search_code(self, query: str, sort: str = None, order: str = None): ...
225
def search_commits(self, query: str, sort: str = None, order: str = None): ...
226
def search_topics(self, query: str): ...
227
```
228
229
[Search and Discovery](./search-discovery.md)
230
231
### Workflows and Actions
232
233
GitHub Actions workflow management, workflow runs, jobs, artifacts, and self-hosted runners. Supports automation and CI/CD pipeline integration.
234
235
```python { .api }
236
class Workflow:
237
def create_dispatch(self, ref: str, inputs: dict = None): ...
238
def get_runs(self, actor: str = None, branch: str = None, event: str = None): ...
239
240
class WorkflowRun:
241
def cancel(self): ...
242
def rerun(self): ...
243
def get_jobs(self): ...
244
def get_artifacts(self): ...
245
246
class Repository:
247
def get_workflows(self): ...
248
def get_workflow_runs(self): ...
249
```
250
251
[Workflows and Actions](./workflows-actions.md)
252
253
## Core Types
254
255
```python { .api }
256
# Main client class
257
class Github:
258
def close(self) -> None: ...
259
def get_user(self, login: str = None) -> Union[AuthenticatedUser, NamedUser]: ...
260
def get_repo(self, full_name_or_id: Union[str, int]) -> Repository: ...
261
def get_organization(self, login: str) -> Organization: ...
262
263
# Pagination support
264
class PaginatedList:
265
def totalCount(self) -> int: ...
266
def __iter__(self): ...
267
def __getitem__(self, index: Union[int, slice]): ...
268
269
# Input helper classes
270
class InputFileContent:
271
def __init__(self, content: str, new_name: str | None = None): ...
272
273
class InputGitAuthor:
274
def __init__(self, name: str, email: str, date: str = None): ...
275
276
class InputGitTreeElement:
277
def __init__(self, path: str, mode: str, type: str, content: str = None, sha: str = None): ...
278
279
# Rate limiting
280
class RateLimit:
281
@property
282
def limit(self) -> int: ...
283
@property
284
def remaining(self) -> int: ...
285
@property
286
def reset(self) -> datetime: ...
287
288
# Exception classes
289
class GithubException(Exception):
290
"""Base exception class for all PyGithub errors"""
291
@property
292
def status(self) -> int: ...
293
@property
294
def data(self) -> Any: ...
295
@property
296
def headers(self) -> dict: ...
297
@property
298
def message(self) -> str: ...
299
300
class BadCredentialsException(GithubException):
301
"""Authentication failures (401/403 errors)"""
302
303
class UnknownObjectException(GithubException):
304
"""Resource not found (404 errors)"""
305
306
class RateLimitExceededException(GithubException):
307
"""API rate limit exceeded"""
308
309
class BadUserAgentException(GithubException):
310
"""Invalid user agent string"""
311
312
class TwoFactorException(GithubException):
313
"""Two-factor authentication required"""
314
315
class BadAttributeException(Exception):
316
"""Type conversion errors when parsing API responses"""
317
@property
318
def actual_value(self) -> Any: ...
319
@property
320
def expected_type(self) -> Any: ...
321
322
class IncompletableObject(GithubException):
323
"""Missing URL data for lazy loading"""
324
```
325
326
## Configuration
327
328
```python { .api }
329
# Rate limiting information
330
def get_rate_limit(self) -> RateLimit: ...
331
332
# Retry configuration
333
class GithubRetry:
334
def __init__(
335
self,
336
total: int = None,
337
status_forcelist: list = None,
338
backoff_factor: float = None
339
): ...
340
341
# Utility functions
342
def set_log_level(level: int) -> None: ...
343
def enable_console_debug_logging() -> None: ...
344
```