Detailed information on the GhApi API

You can set an environment variable named GH_HOST to override the default of https://api.github.com incase you are running GitHub Enterprise(GHE). However, this library has not been tested on GHE, so proceed at your own risk.

class GhApi[source]

GhApi(owner=None, repo=None, token=None, debug=None, limit_cb=None, **kwargs) :: _GhObj

Access by path

GhApi.__call__[source]

GhApi.__call__(path:str, verb:str=None, headers:dict=None, route:dict=None, query:dict=None, data=None)

Call a fully specified path using HTTP verb, passing arguments to fastcore.core.urlsend

api = GhApi()

You can call a GhApi object as a function, passing in the path to the endpoint, the HTTP verb, and any route, query parameter, or post data parameters as required.

api('/repos/{owner}/{repo}/git/ref/{ref}', 'GET', route=dict(
    owner='fastai', repo='ghapi-test', ref='heads/master'))

GhApi.__getitem__[source]

GhApi.__getitem__(k)

Lookup and call an endpoint by path and verb (which defaults to 'GET')

You can access endpoints by indexing into the object. When using the API this way, you do not need to specify what type of parameter (route, query, or post data) is being used. This is, therefore, the same call as above:

api['/repos/{owner}/{repo}/git/ref/{ref}'](owner='fastai', repo='ghapi-test', ref='heads/master')

Rate limits

GitHub has various rate limits for their API. After each call, the response includes information about how many requests are remaining in the hourly quota. If you'd like to add alerts, or indications showing current quota usage, you can register a callback with GhApi by passing a callable to the limit_cb parameter. This callback will be called whenever the amount of quota used changes. It will be called with two arguments: the new quota remaining, and the total hourly quota.

def _f(rem,quota): print(f"Quota remaining: {rem} of {quota}")

api = GhApi(limit_cb=_f)
api['/repos/{owner}/{repo}/git/ref/{ref}'](owner='fastai', repo='ghapi-test', ref='heads/master').ref
Quota remaining: 4864 of 5000
'refs/heads/master'

You can always get the remaining quota from the limit_rem attribute:

api.limit_rem
'4864'

Operations

Instead of passing a path to GhApi, you will more often use the operation methods provided in the API's operation groups, which include documentation, signatures, and auto-complete.

If you provide owner and/or repo to the constructor, they will be automatically inserted into any calls which use them (except when calling GhApi as a function). You can also pass any other arbitrary keyword arguments you like to have them used as defaults for any relevant calls.

You must include a GitHub API token if you need to access any authenticated endpoints. If don't pass the token param, then your GITHUB_TOKEN environment variable will be used, if available.

api = GhApi(owner='fastai', repo='ghapi-test', token=token)

Operation groups

The following groups of endpoints are provided, which you can list at any time along with a link to documentation for all endpoints in that group, by displaying the GhApi object:

api.codes_of_conduct

Calling endpoints

The GitHub API's endpoint names generally start with a verb like "get", "list", "delete", "create", etc, followed _, then by a noun such as "ref", "webhook", "issue", etc.

Each endpoint has a different signature, which you can see by using Shift-Tab in Jupyter, or by just printing the endpoint object (which also shows a link to the GitHub docs):

print(api.repos.create_webhook)
repos.create_webhook(name: str = None, config: dict = None, events: list = ['push'], active: bool = True)
https://docs.github.com/rest/reference/repos#create-a-repository-webhook

Displaying an endpoint object in Jupyter also provides a formatted summary and link to the official GitHub documentation:

api.repos.create_webhook

repos.create_webhook(name, config, events, active): Create a repository webhook

Endpoint objects are called using standard Python method syntax:

ref = api.git.get_ref('heads/master')
test_eq(ref.object.type, 'commit')

Information about the endpoint are available as attributes:

api.git.get_ref.path,api.git.get_ref.verb
('/repos/fastai/ghapi-test/git/ref/{ref}', 'get')

You can get a list of all endpoints available in a group, along with a link to documentation for each, by viewing the group:

api.git

For "list" endpoints, the noun will be a plural form, e.g.:

hooks = api.repos.list_webhooks()
test_eq(len(hooks), 0)

You can pass dicts, lists, etc. directly, where they are required for GitHub API endpoints:

url = 'https://example.com'
cfg = dict(url=url, content_type='json', secret='XXX')
hook = api.repos.create_webhook(config=cfg, events=['ping'])
test_eq(hook.config.url, url)

Let's confirm that our new webhook has been created:

hooks = api.repos.list_webhooks()
test_eq(len(hooks), 1)
test_eq(hooks[0].events, ['ping'])

Finally, we can delete our new webhook:

api.repos.delete_webhook(hooks[0].id)

Convenience functions

date2gh[source]

date2gh(dt:datetime)

Convert dt (which is assumed to be in UTC time zone) to a format suitable for GitHub API operations

The GitHub API assumes that dates will be in a specific string format. date2gh converts Python standard datetime objects to that format. For instance, to find issues opened in the 'fastcore' repo in the last 4 weeks:

dt = date2gh(datetime.utcnow() - timedelta(weeks=4))
issues = GhApi('fastai').issues.list_for_repo(repo='fastcore', since=dt)
len(issues)
1

gh2date[source]

gh2date(dtstr:str)

Convert date string dtstr received from a GitHub API operation to a UTC datetime

created = issues[0].created_at
print(created, '->', gh2date(created))
2021-06-25T02:05:34Z -> 2021-06-25 02:05:34

Preview endpoints

GitHub's preview API functionality requires a special header to be passed to enable it. This is added automatically for you.

print_summary(req:Request)

Print Request.summary with the token (if any) removed

You can set the debug attribute to any callable to intercept all requests, for instance to print Request.summary. print_summary is provided for this purpose. Using this, we can see the preview header that is added for preview functionality, e.g.

api.debug=print_summary
api.codes_of_conduct.get_all_codes_of_conduct()[0]
api.debug=None
{'data': None,
 'full_url': 'https://api.github.com/codes_of_conduct',
 'headers': {'Accept': 'application/vnd.github.scarlet-witch-preview+json'},
 'method': 'GET'}

Convenience methods

There are some multi-step processes in the GitHub API that GhApi provide convenient wrappers for. The methods currently available are shown below; do not hesitate to create an issue or pull request if there are other processes that you'd like to see supported better.

Releases

GhApi.upload_file[source]

GhApi.upload_file(rel, fn)

Upload fn to endpoint for release rel

GhApi.create_release[source]

GhApi.create_release(tag_name, branch='master', name=None, body='', draft=False, prerelease=False, files=None)

Wrapper for GhApi.repos.create_release which also uploads files

Creating a release and attaching files to it is normally a multi-stage process, so create_release wraps this up for you. It takes the same arguments as repos.create_release, along with files, which can contain a single file name, or a list of file names to upload to your release:

rel = api.create_release('0.0.1', files=['docs/index.html'])
test_eq(rel.name, 'v0.0.1')
rels = api.repos.list_releases()
test_eq(len(rels), 1)

We can check that our file has been uploaded; GitHub refers to them as "assets":

assets = api.repos.list_release_assets(rels[0].id)
test_eq(assets[0].name, 'index.html')
test_eq(assets[0].content_type, 'text/html')

GhApi.delete_release[source]

GhApi.delete_release(release)

Delete a release and its associated tag

Branches and tags

GhApi.list_tags[source]

GhApi.list_tags(prefix:str='')

List all tags, optionally filtered to those starting with prefix

With no prefix, all tags are listed.

test_eq(len(api.list_tags()), 1)

Using the full tag name will return just that tag.

test_eq(len(api.list_tags(rel.tag_name)), 1)

GhApi.list_branches[source]

GhApi.list_branches(prefix:str='')

List all branches, optionally filtered to those starting with prefix

Branches can be listed in the exactly the same way as tags.

test_eq(len(api.list_branches('master')), 1)

We can delete our release and confirm that it is removed:

api.delete_release(rels[0])
test_eq(len(api.repos.list_releases()), 0)

GhApi.create_branch_empty[source]

GhApi.create_branch_empty(branch)

ref = api.create_branch_empty("testme")
test_eq(len(api.list_branches('testme')), 1)

GhApi.delete_tag[source]

GhApi.delete_tag(tag:str)

Delete a tag

GhApi.delete_branch[source]

GhApi.delete_branch(branch:str)

Delete a branch

api.delete_branch('testme')
test_eq(len(api.list_branches('testme')), 0)

GhApi.get_branch[source]

GhApi.get_branch(branch=None)

Content (git files)

GhApi.list_files[source]

GhApi.list_files(branch=None)

files = api.list_files()
files['README.md']

GhApi.get_content[source]

GhApi.get_content(path)

readme = api.get_content('README.md').decode()
assert 'ghapi' in readme

GhApi.update_contents[source]

GhApi.update_contents(path, message=None, content=None, sha=None, branch=None, committer=None, author=None)

res = api.update_contents(
    path='README.md',
    message="Update README",
    content=readme+"foobar"
)
res.content.size
72
readme = api.get_content('README.md').decode()
assert 'foobar' in readme
api.update_contents('README.md', "Revert README", content=readme[:-6]);

GhApi.enable_pages[source]

GhApi.enable_pages(branch=None, path='/')

Enable or update pages for a repo to point to a branch and path.

branch is set to the default branch if None. path must be /docs or /.

res = api.enable_pages(branch='new-branch', path='/')
test_eq(res.source.branch, 'new-branch')
test_eq(res.source.path, '/')
api.repos.delete_pages_site()
api.delete_branch('new-branch')