0
# Core API Client
1
2
The core API client provides the main interface to the GitHub API through the GhApi class, along with utility functions for date handling and request debugging.
3
4
## Capabilities
5
6
### GhApi Class
7
8
The main API client that provides access to all GitHub API endpoints through dynamically generated methods organized by API groups.
9
10
```python { .api }
11
class GhApi:
12
def __init__(self, owner=None, repo=None, token=None, jwt_token=None,
13
debug=None, limit_cb=None, gh_host=None, authenticate=True, **kwargs):
14
"""
15
Create a GitHub API client.
16
17
Parameters:
18
- owner: str, default repository owner
19
- repo: str, default repository name
20
- token: str, GitHub personal access token
21
- jwt_token: str, GitHub JWT token
22
- debug: callable, debug function for requests
23
- limit_cb: callable, rate limit callback function
24
- gh_host: str, GitHub API host URL
25
- authenticate: bool, whether to authenticate requests
26
- **kwargs: additional default parameters
27
"""
28
29
def __call__(self, path: str, verb: str = None, headers: dict = None,
30
route: dict = None, query: dict = None, data=None, timeout=None, decode=True):
31
"""
32
Call a fully specified API path using HTTP verb.
33
34
Parameters:
35
- path: str, API endpoint path
36
- verb: str, HTTP method (GET, POST, PUT, DELETE, etc.)
37
- headers: dict, additional HTTP headers
38
- route: dict, path parameters for URL templating
39
- query: dict, query string parameters
40
- data: request body data
41
- timeout: int, request timeout in seconds
42
- decode: bool, whether to decode JSON response
43
44
Returns:
45
API response data
46
"""
47
48
def __getitem__(self, k):
49
"""
50
Lookup and call an endpoint by path and verb.
51
52
Parameters:
53
- k: tuple of (path, verb) or just path (defaults to GET)
54
55
Returns:
56
API endpoint function
57
"""
58
59
def full_docs(self):
60
"""
61
Return complete documentation for all API endpoints.
62
63
Returns:
64
str: Markdown documentation
65
"""
66
```
67
68
#### API Endpoint Access
69
70
The GhApi client organizes endpoints into groups that mirror GitHub's API structure:
71
72
```python
73
# Repository operations
74
api.repos.get(owner='user', repo='repo')
75
api.repos.list_for_user(username='user')
76
api.repos.create(name='new-repo', description='Description')
77
78
# Issue management
79
api.issues.list_for_repo(owner='user', repo='repo')
80
api.issues.create(owner='user', repo='repo', title='Title', body='Body')
81
api.issues.update(owner='user', repo='repo', issue_number=1, state='closed')
82
83
# Pull request operations
84
api.pulls.list(owner='user', repo='repo')
85
api.pulls.create(owner='user', repo='repo', title='Title', head='feature', base='main')
86
87
# Actions and workflows
88
api.actions.list_workflow_runs(owner='user', repo='repo')
89
api.actions.list_jobs_for_workflow_run(owner='user', repo='repo', run_id=123)
90
91
# Git operations
92
api.git.get_ref(owner='user', repo='repo', ref='heads/main')
93
api.git.create_ref(owner='user', repo='repo', ref='refs/heads/feature', sha='sha')
94
95
# User and organization operations
96
api.users.get_by_username(username='user')
97
api.orgs.get(org='organization')
98
```
99
100
### Extended Repository Operations
101
102
Additional methods added to GhApi for common repository operations.
103
104
```python { .api }
105
def create_gist(self, description, content, filename='gist.txt', public=False):
106
"""
107
Create a gist containing a single file.
108
109
Parameters:
110
- description: str, gist description
111
- content: str, file content
112
- filename: str, filename for the gist
113
- public: bool, whether gist is public
114
115
Returns:
116
Gist object
117
"""
118
119
def delete_release(self, release):
120
"""
121
Delete a release and its associated tag.
122
123
Parameters:
124
- release: release object with id and tag_name
125
"""
126
127
def upload_file(self, rel, fn):
128
"""
129
Upload file to release endpoint.
130
131
Parameters:
132
- rel: release object with upload_url
133
- fn: str or Path, file to upload
134
135
Returns:
136
Upload response
137
"""
138
139
def create_release(self, tag_name, branch='master', name=None, body='',
140
draft=False, prerelease=False, files=None):
141
"""
142
Create release and upload files.
143
144
Parameters:
145
- tag_name: str, git tag name
146
- branch: str, target branch
147
- name: str, release name
148
- body: str, release description
149
- draft: bool, whether release is draft
150
- prerelease: bool, whether release is prerelease
151
- files: list, files to upload
152
153
Returns:
154
Release object
155
"""
156
157
def list_tags(self, prefix: str = ''):
158
"""
159
List all tags, optionally filtered by prefix.
160
161
Parameters:
162
- prefix: str, tag name prefix filter
163
164
Returns:
165
List of tag references
166
"""
167
168
def list_branches(self, prefix: str = ''):
169
"""
170
List all branches, optionally filtered by prefix.
171
172
Parameters:
173
- prefix: str, branch name prefix filter
174
175
Returns:
176
List of branch references
177
"""
178
179
def create_branch_empty(self, branch):
180
"""
181
Create empty branch with dummy file.
182
183
Parameters:
184
- branch: str, branch name
185
186
Returns:
187
Branch reference
188
"""
189
190
def delete_tag(self, tag: str):
191
"""
192
Delete a tag.
193
194
Parameters:
195
- tag: str, tag name to delete
196
"""
197
198
def delete_branch(self, branch: str):
199
"""
200
Delete a branch.
201
202
Parameters:
203
- branch: str, branch name to delete
204
"""
205
206
def get_branch(self, branch=None):
207
"""
208
Get branch information.
209
210
Parameters:
211
- branch: str, branch name (defaults to repository default)
212
213
Returns:
214
Branch reference object
215
"""
216
217
def list_files(self, branch=None):
218
"""
219
List files in repository.
220
221
Parameters:
222
- branch: str, branch name (defaults to repository default)
223
224
Returns:
225
Dict mapping file paths to file objects
226
"""
227
228
def get_content(self, path):
229
"""
230
Get file content (base64 decoded).
231
232
Parameters:
233
- path: str, file path in repository
234
235
Returns:
236
bytes: File content
237
"""
238
239
def create_or_update_file(self, path, message, committer, author,
240
content=None, sha=None, branch=''):
241
"""
242
Create or update file in repository.
243
244
Parameters:
245
- path: str, file path
246
- message: str, commit message
247
- committer: dict, committer info
248
- author: dict, author info
249
- content: str or bytes, file content
250
- sha: str, current file SHA (for updates)
251
- branch: str, target branch
252
253
Returns:
254
Commit response
255
"""
256
257
def create_file(self, path, message, committer, author, content=None, branch=None):
258
"""
259
Create new file in repository.
260
261
Parameters:
262
- path: str, file path
263
- message: str, commit message
264
- committer: dict, committer info
265
- author: dict, author info
266
- content: str or bytes, file content
267
- branch: str, target branch
268
269
Returns:
270
Commit response
271
"""
272
273
def delete_file(self, path, message, committer, author, sha=None, branch=None):
274
"""
275
Delete file from repository.
276
277
Parameters:
278
- path: str, file path
279
- message: str, commit message
280
- committer: dict, committer info
281
- author: dict, author info
282
- sha: str, current file SHA
283
- branch: str, target branch
284
285
Returns:
286
Commit response
287
"""
288
289
def update_contents(self, path, message, committer, author, content, sha=None, branch=None):
290
"""
291
Update file contents in repository.
292
293
Parameters:
294
- path: str, file path
295
- message: str, commit message
296
- committer: dict, committer info
297
- author: dict, author info
298
- content: str or bytes, new file content
299
- sha: str, current file SHA
300
- branch: str, target branch
301
302
Returns:
303
Commit response
304
"""
305
306
def enable_pages(self, branch=None, path="/"):
307
"""
308
Enable or update GitHub Pages for repository.
309
310
Parameters:
311
- branch: str, pages source branch
312
- path: str, pages source path ("/docs" or "/")
313
314
Returns:
315
Pages configuration
316
"""
317
```
318
319
### Utility Functions
320
321
Helper functions for working with GitHub API requests and date formatting.
322
323
```python { .api }
324
def print_summary(req: Request):
325
"""
326
Print request summary with authorization token removed.
327
328
Parameters:
329
- req: Request object to summarize
330
"""
331
332
def date2gh(dt: datetime) -> str:
333
"""
334
Convert datetime to GitHub API format.
335
336
Parameters:
337
- dt: datetime object (assumed UTC)
338
339
Returns:
340
str: ISO format string with Z suffix
341
"""
342
343
def gh2date(dtstr: str) -> datetime:
344
"""
345
Convert GitHub API date string to datetime.
346
347
Parameters:
348
- dtstr: str, GitHub API date string
349
350
Returns:
351
datetime: UTC datetime object
352
"""
353
```
354
355
## Usage Examples
356
357
### Basic Repository Operations
358
359
```python
360
from ghapi.all import GhApi
361
362
# Initialize with authentication
363
api = GhApi(token='your_token', owner='username', repo='repository')
364
365
# Get repository information
366
repo_info = api.repos.get()
367
print(f"Repository: {repo_info.full_name}")
368
print(f"Description: {repo_info.description}")
369
print(f"Stars: {repo_info.stargazers_count}")
370
371
# List repository files
372
files = api.list_files()
373
for path, file_obj in files.items():
374
print(f"{path}: {file_obj.type}")
375
376
# Get file content
377
content = api.get_content('README.md')
378
print(content.decode('utf-8'))
379
```
380
381
### Working with Issues and Pull Requests
382
383
```python
384
# List open issues
385
issues = api.issues.list_for_repo(state='open', per_page=10)
386
for issue in issues:
387
print(f"#{issue.number}: {issue.title}")
388
389
# Create new issue
390
new_issue = api.issues.create(
391
title='Bug Report',
392
body='Description of the bug...',
393
labels=['bug', 'needs-triage']
394
)
395
396
# Create pull request
397
pr = api.pulls.create(
398
title='Feature: Add new functionality',
399
body='This PR adds...',
400
head='feature-branch',
401
base='main'
402
)
403
```
404
405
### Release Management
406
407
```python
408
# Create release with file uploads
409
release = api.create_release(
410
tag_name='v1.0.0',
411
name='Version 1.0.0',
412
body='Release notes...',
413
files=['dist/package.tar.gz', 'dist/package.zip']
414
)
415
416
# List all releases
417
releases = api.repos.list_releases()
418
for release in releases:
419
print(f"{release.tag_name}: {release.name}")
420
421
# Delete release and tag
422
api.delete_release(release)
423
```
424
425
### Branch and Tag Management
426
427
```python
428
# List branches
429
branches = api.list_branches()
430
for branch in branches:
431
print(f"Branch: {branch.ref}")
432
433
# Create new branch
434
api.create_branch_empty('new-feature')
435
436
# List tags with prefix filter
437
tags = api.list_tags(prefix='v1.')
438
for tag in tags:
439
print(f"Tag: {tag.ref}")
440
441
# Delete tag
442
api.delete_tag('old-tag')
443
```