github3.py: A Library for Using GitHub’s REST API
Release v4.0.1.
github3.py is wrapper for the GitHub API written in python. The design of github3.py is centered around having a logical organization of the methods needed to interact with the API. As an example, let’s get information about a user:
from github3 import login
gh = login('sigmavirus24', password='<password>')
sigmavirus24 = gh.me()
# <AuthenticatedUser [sigmavirus24:Ian Stapleton Cordasco]>
print(sigmavirus24.name)
# Ian Stapleton Cordasco
print(sigmavirus24.login)
# sigmavirus24
print(sigmavirus24.followers_count)
# 4
for f in gh.followers():
print(str(f))
kennethreitz = gh.user('kennethreitz')
# <User [kennethreitz:Kenneth Reitz]>
print(kennethreitz.name)
print(kennethreitz.login)
print(kennethreitz.followers_count)
followers = [str(f) for f in gh.followers_of('kennethreitz')]
There are several examples of different aspects of using github3.py
Using Two-factor Authentication with github3.py
GitHub recently added support for Two-factor Authentication to github.com
and shortly thereafter added support for it on api.github.com
. In version
0.8, github3.py also added support for it and you can use it right now.
To use Two-factor Authentication, you must define your own function that will return your one time authentication code. You then provide that function when logging in with github3.py.
For example:
import github3
def my_two_factor_function():
# The user could accidentally press Enter before being ready,
# let's protect them from doing that.
return input('Enter 2FA code: ').strip() or my_two_factor_function()
g = github3.login('sigmavirus24', 'my_password',
two_factor_callback=my_two_factor_function)
Then each time the API tells github3.py it requires a Two-factor Authentication
code, github3.py will call my_two_factor_function
which prompt you for it.
Using Tokens for Your Projects
Let’s say you’re designing an application that uses github3.py. If your intention is to have users authenticate, you have a few options.
Ask the user to enter their credentials each time they start the application. (Or save the username somewhere, and just ask for the password.)
Ask the user to supply their credentials once and store them somewhere for later use.
Ask the user to supply their credentials once, get an authorization token and store that for later use.
The first isn’t a bad method at all, it just unfortunately may lead to unhappy users, this should always be an option though. The second (as I already noted) is a bad idea. Even if you obfuscate the username and password, they can still be discovered and no level of obfuscation is clever enough. (May I also take this moment to remind people that base64 is not encryption.) The last is probably the least objectionable of the evils. The token has scopes so there is only so much someone can do with it and it works well with github3.py.
Requesting a token
If you’re not doing a web application, you are more than welcome to use
github3.py (otherwise work with redirects). Let’s say your application needs
access to public and private repositories, and the users but not to gists.
Your scopes should be ['user', 'repo']
. I’m also assuming your
application will not be deleting any repositories. The only things left to do
are collect the username and password and give a good description for your
application.
from github3 import authorize
from getpass import getuser, getpass
user = getuser()
password = ''
while not password:
password = getpass('Password for {0}: '.format(user))
note = 'github3.py example app'
note_url = 'http://example.com'
scopes = ['user', 'repo']
auth = authorize(user, password, scopes, note, note_url)
with open(CREDENTIALS_FILE, 'w') as fd:
fd.write(auth.token + '\n')
fd.write(str(auth.id))
In the future, you can then read that token in without having to bother your user. If at some later point in the lifetime of your application you need more privileges, you simply do the following:
from github3 import login
token = id = ''
with open(CREDENTIALS_FILE, 'r') as fd:
token = fd.readline().strip() # Can't hurt to be paranoid
id = fd.readline().strip()
gh = login(token=token)
auth = gh.authorization(id)
auth.update(add_scopes=['repo:status', 'gist'], rm_scopes=['user'])
# if you want to be really paranoid, you can then test:
# token == auth.token
# in case the update changes the token
Gist Code Examples
Examples with Gist
s
Listing gists after authenticating
from github3 import login
gh = login(username, password)
gists = [g for g in gh.iter_gists()]
Creating a gist after authenticating
from github3 import login
gh = login(username, password)
files = {
'spam.txt' : {
'content': 'What... is the air-speed velocity of an unladen swallow?'
}
}
gist = gh.create_gist('Answer this to cross the bridge', files, public=False)
# gist == <Gist [gist-id]>
print(gist.html_url)
Creating an anonymous gist
from github3 import create_gist
files = {
'spam.txt' : {
'content': 'What... is the air-speed velocity of an unladen swallow?'
}
}
gist = create_gist('Answer this to cross the bridge', files)
comments = [c for c in gist.iter_comments()]
# []
comment = gist.create_comment('Bogus. This will not work.')
# Which of course it didn't, because you're not logged in
# comment == None
print(gist.html_url)
In the above examples 'spam.txt'
is the file name. GitHub will autodetect
file type based on extension provided. 'What… is the air-speed velocity of
an unladen swallow?'
is the file’s content or body. 'Answer this to cross
the bridge'
is the gist’s description. While required by github3.py, it is
allowed to be empty, e.g., ''
is accepted by GitHub.
Note that anonymous gists are always public.
Git Code Examples
The GitHub API does not just provide an API to interact with GitHub’s features. A whole section of the API provides a RESTful API to git operations that one might normally perform at the command-line or via your git client.
Creating a Blob Object
One of the really cool (and under used, it seems) parts of the GitHub API involves the ability to create blob objects.
from github3 import login
g = login(username, password)
repo = g.repository('sigmavirus24', 'Todo.txt-python')
sha = repo.create_blob('Testing blob creation', 'utf-8')
sha
# u'57fad9a39b27e5eb4700f66673ce860b65b93ab8'
blob = repo.blob(sha)
blob.content
# u'VGVzdGluZyBibG9iIGNyZWF0aW9u\n'
blob.decoded
# u'Testing blob creation'
blob.encoding
# u'base64'
Creating a Tag Object
GitHub provides tar files for download via tag objects. You can create one via
git tag
or you can use the API.
from github3 import login
g = login(username, password)
repo = g.repository('sigmavirus24', 'github3.py')
tag = repo.tag('cdba84b4fede2c69cb1ee246b33f49f19475abfa')
tag
# <Tag [cdba84b4fede2c69cb1ee246b33f49f19475abfa]>
tag.object.sha
# u'24ea44d302c6394a0372dcde8fd8aed899c0034b'
tag.object.type
# u'commit'
GitHub Examples
Examples using the GitHub
object.
Assumptions
I’ll just make some basic assumptions for the examples on this page. First,
let’s assume that all you ever import from github3.py is login
and
GitHub
and that you have already received your GitHub
object g
. That might look like this:
from github3 import login, GitHub
from getpass import getpass, getuser
import sys
try:
import readline
except ImportError:
pass
try:
user = input('GitHub username: ') or getuser()
except KeyboardInterrupt:
user = getuser()
password = getpass('GitHub password for {0}: '.format(user))
# Obviously you could also prompt for an OAuth token
if not (user and password):
print("Cowardly refusing to login without a username and password.")
sys.exit(1)
g = login(user, password)
So anywhere you see g
used, you can safely assume that it is an instance
where a user has authenticated already.
For the cases where we do not need an authenticated user, or where we are
trying to demonstrate the differences between the two, I will use anon
.
anon
could be instantiated like so:
anon = GitHub()
Also let’s define the following constants:
sigma = 'sigmavirus24'
github3 = 'github3.py'
todopy = 'Todo.txt-python'
kr = 'kennethreitz'
requests = 'requests'
We may not need all of them, but they’ll be useful
Adding a new key to your account
try:
path = input('Path to key: ')
except KeyboardInterrupt:
path = ''
try:
name = input('Key name: ')
except KeyboardInterrupt:
name = ''
if not (path and name): # Equivalent to not path or not name
print("Cannot create a new key without a path or name")
sys.exit(1)
with open(path, 'r') as key_file:
key = g.create_key(name, key_file)
if key:
print('Key {0} created.'.format(key.title))
else:
print('Key addition failed.')
Deleting the key we just created
Assuming we still have key
from the previous example:
if g.delete_key(key.id):
print("Successfully deleted key {0}".format(key.id))
There would actually be an easier way of doing this, however, if we do have the
key
object that we created:
if key.delete():
print("Successfully deleted key {0}".format(key.id))
Creating a new repository
repo = {}
keys = ['name', 'description', 'homepage', 'private', 'has_issues',
'has_wiki', 'has_downloads']
for key in keys:
try:
repo[key] = input(key + ': ')
except KeyboardInterrupt:
pass
r = None
if repo.get('name'):
r = g.create_repository(repo.pop('name'), **repo)
if r:
print("Created {0} successfully.".format(r.name))
Create a commit to change an existing file
repo.file_contents('/README.md').update('commit message', 'file content'.encode('utf-8'))
Follow another user on GitHub
I’m cheating here and using most of the follow functions in one example
if not g.is_following(sigma):
g.follow(sigma)
if not g.is_subscribed(sigma, github3py):
g.subscribe(sigma, github3py)
if g.is_subscribed(sigma, todopy):
g.unsubscribe(sigma, todopy)
for follower in g.iter_followers():
print("{0} is following me.".format(follower.login))
for followee in g.iter_following():
print("I am following {0}.".format(followee.login))
if g.is_following(sigma):
g.unfollow(sigma)
Changing your user information
Note that you can not change your login name via the API.
new_name = 'J. Smith'
blog = 'http://www.example.com/'
company = 'Vandelay Industries'
bio = """# J. Smith
A simple man working at a latex factory
"""
if g.update_user(new_name, blog, company, bio=bio):
print('Profile updated.')
This is the same as:
me = g.me() # or me = g.user(your_user_name)
if me.update(new_name, blog, company, bio=bio):
print('Profile updated.')
Issue Code Examples
Examples using Issue
s
Administering Issues
Let’s assume you have your username and password stored in user
and pw
respectively, you have your repository name stored in repo
, and the number
of the issue you’re concerned with in num
.
from github3 import login
gh = login(user, pw)
issue = gh.issue(user, repo, num)
if issue.is_closed():
issue.reopen()
issue.edit('New issue title', issue.body + '\n------\n**Update:** Text to append')
Closing and Commenting on Issues
# Assuming issue is the same as above ...
issue.create_comment('This should be fixed in 6d4oe5. Closing as fixed.')
issue.close()
Example issue to comment on
If you would like to test the above, see issue #108. Just follow the code there and fill in your username, password (or token), and comment message. Then run the script and watch as the issue opens in your browser focusing on the comment you just created.
The following shows how you could use github3.py to fetch and display your issues in your own style and in your web browser.
import tempfile
import webbrowser
import github3
template = """<html><head></head><body>{0}</body></html>"""
i = github3.issue("kennethreitz", "requests", 868)
with tempfile.NamedTemporaryFile() as tmpfd:
tmpfd.write(template.format(i.body_html))
webbrowser.open("file://" + tmpfd.name)
Or how to do the same by wrapping the lines in your terminal.
import textwrap
import github3
i = github3.issue("kennethreitz", "requests", 868)
for line in textwrap.wrap(i.body_text, 78, replace_whitespace=False):
print(line)
Importing an issue
Not only can you create new issues, but you can import existing ones. When importing, you preserve the timestamp creation date; you can preserve the timestamp(s) for comment(s) too.
import github3
gh = github3.login(token=token)
issue = {
'title': 'Documentation issue',
'body': 'Missing links in index.html',
'created_at': '2011-03-11T17:00:40Z'
}
repository = gh.repository(user, repo)
repository.import_issue(**issue)
Status of imported issue
Here’s how to check the status of the imported issue.
import github3
issue = repository.imported_issue(issue_num)
print(issue.status)
Using Logging with github3.py
New in version 0.6.0.
The following example shows how to set up logging for github3.py. It is off by default in the library and will not pollute your logs.
import logging
import github3
# Set up a file to have all the logs written to
file_handler = logging.FileHandler("github_script.log")
# Send the logs to stderr as well
stream_handler = logging.StreamHandler()
# Format the log output and include the log level's name and the time it was
# generated
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
# Use that Formatter on both handlers
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# Get the logger used by github3.py internally by referencing its name
# directly
logger = logging.getLogger("github3")
# Add the handlers to it
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
# Set the level which determines what you see
logger.setLevel(logging.DEBUG)
# Make a library call and see the information posted
r = github3.repository("sigmavirus24", "github3.py")
print("{0} - {0.html_url}".format(r))
One thing to note is that if you want more detailed information about what is happening while the requests are sent, you can do the following:
import logging
urllib3 = logging.getLogger('requests.packages.urllib3')
And configure the logger for urllib3. Unfortunately, requests itself doesn’t
provide any logging, so the best you can actually get is by configuring
urllib3
.
You will see messages about the following in the logs:
Construction of URLs used in requests, usually in the form:
('https://api.github.com', 'repos', 'sigmavirus24', 'github3.py')
What request is being sent, e.g.,
POST https://api.github.com/user kwargs={}
If JSON is trying to be extracted from the response, what the response’s status code was, what the expected status code was and whether any JSON was actually returned.
A Conversation With Octocat
import github3
print("Hey Octocat")
print(github3.octocat("Hey Ian"))
print("What do you think about github3.py?")
print(github3.octocat("github3.py rocks!"))
print("Thanks Octocat, that means a lot coming from you.")
print("FIN.")
print(
"""Epilogue:
The preceding conversation was entirely fictional. If you didn't realize
that, you need to get out more.
"""
)
What you should see
Hey Octocat
MMM. .MMM
MMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMM _________
MMMMMMMMMMMMMMMMMMMMM | |
MMMMMMMMMMMMMMMMMMMMMMM | Hey Ian |
MMMMMMMMMMMMMMMMMMMMMMMM |_ _____|
MMMM::- -:::::::- -::MMMM |/
MM~:~ ~:::::~ ~:~MM
.. MMMMM::. .:::+:::. .::MMMMM ..
.MM::::: ._. :::::MM.
MMMM;:::::;MMMM
-MM MMMMMMM
^ M+ MMMMMMMMM
MMMMMMM MM MM MM
MM MM MM MM
MM MM MM MM
.~~MM~MM~MM~MM~~.
~~~~MM:~MM~~~MM~:MM~~~~
~~~~~~==~==~~~==~==~~~~~~
~~~~~~==~==~==~==~~~~~~
:~==~==~==~==~~
What do you think about github3.py?
MMM. .MMM
MMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMM ___________________
MMMMMMMMMMMMMMMMMMMMM | |
MMMMMMMMMMMMMMMMMMMMMMM | github3.py rocks! |
MMMMMMMMMMMMMMMMMMMMMMMM |_ _______________|
MMMM::- -:::::::- -::MMMM |/
MM~:~ ~:::::~ ~:~MM
.. MMMMM::. .:::+:::. .::MMMMM ..
.MM::::: ._. :::::MM.
MMMM;:::::;MMMM
-MM MMMMMMM
^ M+ MMMMMMMMM
MMMMMMM MM MM MM
MM MM MM MM
MM MM MM MM
.~~MM~MM~MM~MM~~.
~~~~MM:~MM~~~MM~:MM~~~~
~~~~~~==~==~~~==~==~~~~~~
~~~~~~==~==~==~==~~~~~~
:~==~==~==~==~~
Thanks Octocat, that means a lot coming from you.
FIN.
Epilogue:
The preceding conversation was entirely fictional. If you didn't realize
that, you need to get out more. And yes, I did just have a
conversation with an API. Cool, no? (Sad too, I guess.)
Installation
$ pip install github3.py
User Guide
User Guide for github3.py
This section of our documentation is intended to guide you, the user, through various ways of using the library and to introduce you to some high-level concepts in the library.
Getting Started
This chapter in our documentation will teach you how to get started using github3.py after you’ve installed the library.
Using the library
To get started using the library, it’s important to note that the module that
is provided by this library is called github3
. To use it you can run:
import github3
where necessary.
Logging into GitHub using github3.py
Once you’ve imported the module, you can get started using the API. It’s recommended that you authenticate with GitHub to avoid running into their rate limits. To do so you have a few options.
First, you can use your username and password. We advise you not to type your
password into your shell or python console directly as others can view that
after the fact. For the sake of an example, let’s assume that you have two
variables bound as username
and password
that contain your username
and password. You can then do:
import github3
github = github3.login(username=username, password=password)
Second, you can generate an access token and use that. Let’s presume you
have a variable bound as token
that contains your access token.
import github3
github = github3.login(token=token)
Third, if you’re using a GitHub Enterprise installation you can use similar
methods above, but you’ll need to use enterprise_login()
,
e.g.,
import github3
githubent = github3.enterprise_login(
url='https://github.myenterprise.example.com',
username=username,
password=password,
)
githubent = github3.enterprise_login(
url='https://github.myenterprise.example.com',
token=token,
)
Two-Factor Authentication and github3.py
GitHub has long supported the use of a second-factor authentication (a.k.a, 2FA) mechanism for logging in. This provides some extra security, especially around administrative actions on the website. If you choose to login with simply your username and password and you have to provide github3.py with a mechanism for obtaining your token and providing it to GitHub.
An example mechanism is as follows:
# This assumes Python 3
import github3
def second_factor_retrieval():
"""Provide a way to retrieve the code from the user."""
code = ''
while not code:
code = input('Enter 2FA code: ')
return code
github = github3.login(username, password,
two_factor_callback=second_factor_retrieval)
This means that for every API call made, GitHub will force us to prompt you for a new 2FA code. This is obviously not ideal. In those situations, you almost certainly want to obtain an access token.
Using the Repository APIs
Now that we have learned how to set up a client for use with our APIs, let’s begin to review how github3.py implements the Repositories API.
Retrieving Repositories
Once you’ve logged in you will have an instance of
GitHub
or GitHubEnterprise
.
Let’s assume either one is bound to a variable called github
. To retrieve
a single repository
that we know the
owner and name of, we would do the following:
repository = github.repository(owner, repository_name)
For example, let’s retrieve the repository of the uritemplate
package that
github3.py relies on:
uritemplate = github.repository('python-hyper', 'uritemplate')
It’s also possible for us to retrieve multiple repositories owned by the same user or organization:
for short_repository in github.repositories_by('python-hyper'):
...
When listing repositories, like listing other objects, the GitHub API doesn’t
return the full representation of the object. In this case, github3.py returns
a different object to represent a short repository
. This object has fewer attributes, but
can be converted into a full repository like so:
for short_repository in github.repositories_by('python-hyper'):
full_repository = short_repository.refresh()
We now have two separate objects for the repository based on how GitHub represents them. Both objects have the same methods attached to them. There’s just a different set of attributes on each.
Interacting with Repositories
Repositories are central to many things in GitHub as well as in the API and as result they have many attributes and methods. It’s possible to list branches, collaborators, commits, contributors, deployments, forks, issues, projects, pull requests, refs, and more.
For example, we could build a tiny function that checks if a contributor has deleted their fork:
uritemplate = github.repository('python-hyper', 'uritemplate')
contributors_without_forks = (set(uritemplate.contributors()) -
set(fork.owner for fork in uritemplate.forks()))
print(f'The following contributors deleted their forks of {uritemplate!r}')
for contributor in sorted(contributors_without_forks, key=lambda c: c.login):
print(f' * {contributor.login}')
The output should look like
The following contributors deleted their forks of <Repository [python-hyper/uritemplate]>
* eugene-eeo
* jpotts18
* sigmavirus24
* thierryba
API Reference Documentation
API Reference
Anonymous Functional API
This part of the documentation covers the API. This is intended to be a
beautifully written module which allows the user (developer) to interact with
github3.py
elegantly and easily.
Module Contents
To interact with the GitHub API you can either authenticate to access protected functionality or you can interact with it anonymously. Authenticating provides more functionality to the user (developer).
To authenticate, you may use github3.login()
.
- github3.login(username=None, password=None, token=None, two_factor_callback=None)
Construct and return an authenticated GitHub session.
Note
To allow you to specify either a username and password combination or a token, none of the parameters are required. If you provide none of them, you will receive
None
.- Parameters:
username (str) – login name
password (str) – password for the login
token (str) – OAuth token
two_factor_callback (func) – (optional), function you implement to provide the Two-factor Authentication code to GitHub when necessary
- Returns:
With the GitHub
object that is returned you have
access to more functionality. See that object’s documentation for more
information.
To use the API anonymously, you can also create a new
GitHub
object, e.g.,
from github3 import GitHub
gh = GitHub()
Enterprise Use
If you’re using github3.py to interact with an enterprise installation of
GitHub, you must use the GitHubEnterprise
object.
Upon initialization, the only parameter you must supply is the URL of your
enterprise installation, e.g.
from github3 import GitHubEnterprise
g = GitHubEnterprise('https://github.examplesintl.com')
stats = g.admin_stats('all')
assert 'issues' in stats, ('Key issues is not included in the admin'
'statistics')
App and Installation API Objects
This section of the documentation covers the representations of various objects related to the Apps API.
- class github3.apps.App(json, session: GitHubSession)
An object representing a GitHub App.
New in version 1.2.0.
See also
- GitHub Apps
Documentation for Apps on GitHub
- GitHub Apps API Documentation
API documentation of what’s available about an App.
This object has the following attributes:
- created_at
A
datetime
object representing the day and time the App was created.
- description
The description of the App provided by the owner.
- events
An array of the event types an App receives
- external_url
The URL provided for the App by the owner.
- html_url
The HTML URL provided for the App by the owner.
- id
The unique identifier for the App. This is useful in cases where you may want to authenticate either as an App or as a specific installation of an App.
- name
The display name of the App that the user sees.
- node_id
A base64-encoded blob returned by the GitHub API for who knows what reason.
- permissions
A dictionary describing the permissions the App has
- slug
A short string used to identify the App
- updated_at
A
datetime
object representing the day and time the App was last updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- class github3.apps.Installation(json, session: GitHubSession)
An installation of a GitHub App either on a User or Org.
New in version 1.2.0.
This has the following attributes:
- access_tokens_url
- account
- app_id
- created_at
- events
- html_url
- id
- permissions
- repositories_url
- repository_selection
- single_file_name
- target_id
- target_type
- updated_at
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
Events API Classes
This part of the documentation covers the objects that represent data returned by the Events API.
The Event Object
- class github3.events.Event(json, session: GitHubSession)
Represents an event as returned by the API.
It structures and handles the data returned by via the Events section of the GitHub API.
Two events can be compared like so:
e1 == e2 e1 != e2
And that is equivalent to:
e1.id == e2.id e1.id != e2.id
- created_at
A
datetime
representing when this event was created.
- id
The unique identifier for this event.
- org
If present, a
EventOrganization
representing the organization on which this event occurred.
- type
The type of event this is.
See also
- Event Types Documentation
GitHub’s documentation of different event types
- payload
The payload of the event which has all of the details relevant to this event.
- repo
The string representation of the repository this event pertains to.
Changed in version 1.0.0: This restores the behaviour of the API. To get a tuple, representation, use
self.repo.split('/', 1)
- public
A boolean representing whether the event is publicly viewable or not.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- static list_types()
List available payload types.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
When accessing the payload of the event, you should notice that you receive a dictionary where the keys depend on the event type. Note:
where they reference an array in the documentation but index it like a dictionary, you are given a regular dictionary
where they reference a key as returning an object, you receive the equivalent object from the dictionary, e.g., for a Fork Event
>>> event <Event [Fork]> >>> event.payload {u'forkee': <Repository [eweap/redactor-js]>} >>> event.payload['forkee'] <ShortRepository [eweap/redactor-js]>
Using the dictionary returned as the payload makes far more sense than creating an object for the payload in this instance. For one, creating a class for each payload type would be insanity. I did it once, but it isn’t worth the effort. Having individual handlers as we have now which modify the payload to use our objects when available is more sensible.
Gist API Objects
The Gists API has a rich set of objects it returns.
Gist Representations
- class github3.gists.gist.ShortGist(json, session: GitHubSession)
Short representation of a gist.
GitHub’s API returns different amounts of information about gists based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific gist. For example, you would receive this class when calling
all_gists()
. To provide a clear distinction between the types of gists, github3.py uses different classes with different sets of attributes.This object only has the following attributes:
- url
The GitHub API URL for this repository, e.g.,
https://api.github.com/gists/6faaaeb956dec3f51a9bd630a3490291
.
- comments_count
Number of comments on this gist
- description
Description of the gist as written by the creator
- html_url
The URL of this gist on GitHub, e.g.,
https://gist.github.com/sigmavirus24/6faaaeb956dec3f51a9bd630a3490291
- id
The unique identifier for this gist.
- public
This is a boolean attribute describing if the gist is public or private
- git_pull_url
The git URL to pull this gist, e.g.,
git://gist.github.com/sigmavirus24/6faaaeb956dec3f51a9bd630a3490291.git
- git_push_url
The git URL to push to gist, e.g.,
git@gist.github.com/sigmavirus24/6faaaeb956dec3f51a9bd630a3490291.git
- created_at
This is a datetime object representing when the gist was created.
- updated_at
- This is a datetime object representing the last time this gist was
- most recently updated.
- files
A dictionary mapping the filename to a
GistFile
object.Changed in version 1.0.0: Previously this was a list but it has been converted to a dictionary to preserve the structure of the API.
- comments_url
The URL to retrieve the list of comments on the Gist via the API.
- class github3.gists.gist.GistFork(json, session: GitHubSession)
This object represents a forked Gist.
This has a subset of attributes of a
ShortGist
:- created_at
The date and time when the gist was created.
- id
The unique identifier of the gist.
- owner
The user who forked the gist.
- updated_at
The date and time of the most recent modification of the fork.
- url
The API URL for the fork.
- class github3.gists.gist.Gist(json, session: GitHubSession)
This object constitutes the full representation of a Gist.
GitHub’s API returns different amounts of information about gists based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific gist. For example, you would receive this class when calling
gist()
. To provide a clear distinction between the types of gists, github3.py uses different classes with different sets of attributes.This object has all the same attributes as
ShortGist
as well as:- commits_url
The URL to retrieve gist commits from the GitHub API.
- original_forks
A list of
GistFork
objects representing each fork of this gist. To retrieve the most recent list of forks, use theforks()
method.
- forks_url
The URL to retrieve the current listing of forks of this gist.
- history
A list of
GistHistory
objects representing each change made to this gist.
- truncated
This is a boolean attribute that indicates whether the content of this Gist has been truncated or not.
Files in a Gist
Gists have files which have two representations:
- class github3.gists.file.GistFile(json, session: GitHubSession)
This represents the full file object returned by interacting with gists.
The object has all of the attributes as returned by the API for a ShortGistFile as well as:
- truncated
A boolean attribute that indicates whether
original_content
contains all of the file’s contents.
- original_content
The contents of the file (potentially truncated) returned by the API. If the file was truncated use
content()
to retrieve it in its entirety.
- class github3.gists.file.ShortGistFile(json, session: GitHubSession)
This represents the file object returned by interacting with gists.
The object has the following attributes as returned by the API for a Gist:
- raw_url
This URL provides access to the complete, untruncated content of the file represented by this object.
- filename
The string for the filename.
- language
The GitHub detected language for the file, e.g., Erlang, Python, text.
- size
The file size in bytes.
The History of a Gist
- class github3.gists.history.GistHistory(json, session: GitHubSession)
This object represents one version (or revision) of a gist.
The GitHub API returns the following attributes:
- url
The URL to the revision of the gist retrievable through the API.
- version
The commit ID of the revision of the gist.
- committed_at
The date and time of the revision’s commit.
- change_status
A dictionary with the number of deletions, additions, and total changes to the gist.
For convenience, github3.py also exposes the following attributes from the
change_status
:- additions
The number of additions to the gist compared to the previous revision.
- deletions
The number of deletions from the gist compared to the previous revision.
- total
The total number of changes to the gist compared to the previous revision.
Git API Classes
This part of the documentation covers the module associated with the Git Data section of the GitHub API.
Like much of the GitHub API, many objects have different representations.
Blob Object(s)
- class github3.git.Blob(json, session: GitHubSession)
This object provides an interface to the API representation of a blob.
See also: http://developer.github.com/v3/git/blobs/
Changed in version 1.0.0:
The
content
is no longer forcibly coerced to bytes.
This object has the following atributes
- content
The raw content of the blob. This may be base64 encoded text. Use
decode_content()
to receive the non-encoded text.
- encoding
The encoding that GitHub reports for this blob’s content.
- size
The size of this blob’s content in bytes.
- sha
The SHA1 of this blob’s content.
Commit Object(s)
- class github3.git.Commit(json, session: GitHubSession)
This represents a commit as returned by the git API.
This is distinct from
RepoCommit
. Primarily this object represents the commit data stored by git and it has no relationship to the repository on GitHub.See also: http://developer.github.com/v3/git/commits/
This object has all of the attributes of a
ShortCommit
as well as the following attributes:- parents
The list of commits that are the parents of this commit. This may be empty if this is the initial commit, or it may have several if it is the result of an octopus merge. Each parent is represented as a dictionary with the API URL and SHA1.
- sha
The unique SHA1 which identifies this commit.
- verification
The GPG verification data about this commit. See https://developer.github.com/v3/git/commits/#commit-signature-verification for more information.
- class github3.git.ShortCommit(json, session: GitHubSession)
This represents a commit as returned by the git API.
This is distinct from
RepoCommit
. Primarily this object represents the commit data stored by git. This shorter representation of a Commit is most often found on aRepoCommit
to represent the git data associated with it.See also: http://developer.github.com/v3/git/commits/
This object has the following attributes:
- author
This is a dictionary with at least the name and email of the author of this commit as well as the date it was authored.
- committer
This is a dictionary with at least the name and email of the committer of this commit as well as the date it was committed.
- message
The commit message that describes the changes as written by the author and committer.
- tree
The git tree object this commit points to.
Tree Object(s)
- class github3.git.CommitTree(json, session: GitHubSession)
This object represents the abbreviated tree data in a commit.
The API returns different representations of different objects. When representing a
ShortCommit
orCommit
, the API returns an abbreviated representation of a git tree.This object has the following attributes:
- sha
The SHA1 of this tree in the git repository.
- class github3.git.Hash(json, session: GitHubSession)
This is used to represent the elements of a tree.
This provides the path to the object and the type of object it is. For a brief explanation of what these types are and represent, this StackOverflow question answers some of that: https://stackoverflow.com/a/18605496/1953283
See also: http://developer.github.com/v3/git/trees/#create-a-tree
This object has the following attributes:
- mode
The mode of the file, directory, or link.
- path
The path to the file, directory, or link.
- sha
The SHA1 for this hash.
- type
The type of git object this is representing, e.g., tree, blob, etc.
- class github3.git.Tree(json, session: GitHubSession)
This represents a tree object from a git repository.
Trees tend to represent directories and subdirectories.
See also: http://developer.github.com/v3/git/trees/
This object has the following attributes:
- sha
The SHA1 of this tree in the git repository.
Git Object, Reference, and Tag Object(s)
Yes, we know, GitObject
is a funky name.
- class github3.git.GitObject(json, session: GitHubSession)
This object represents an arbitrary ‘object’ in git.
This object is intended to be versatile and is usually found on one of the following:
This object has the following attributes:
- sha
The SHA1 of the object this is representing.
- type
The name of the type of object this is representing.
- class github3.git.Reference(json, session: GitHubSession)
Object representing a git reference associated with a repository.
This represents a reference (or ref) created on a repository via git.
See also: http://developer.github.com/v3/git/refs/
This object has the following attributes:
- ref
The string path to the reference, e.g.,
'refs/heads/sc/feature-a'
.
- class github3.git.Tag(json, session: GitHubSession)
This represents an annotated tag.
Tags are a special kind of git reference and annotated tags have more information than lightweight tags.
See also: http://developer.github.com/v3/git/tags/
This object has the following attributes:
- message
This is the message that was written to accompany the creation of the annotated tag.
- sha
The SHA1 of this tag in the git repository.
- tag
The “lightweight” tag (or reference) that backs this annotated tag.
- tagger
The person who created this tag.
GitHub Object
The GitHub objects is the point at which most usage of github3.py works.
GitHub.com Object
- class github3.github.GitHub(username='', password='', token='', session=None, api_version='')
Stores all the session information.
There are two ways to log into the GitHub API
from github3 import login g = login(user, password) g = login(token=token) g = login(user, token=token)
or
from github3 import GitHub g = GitHub(user, password) g = GitHub(token=token) g = GitHub(user, token=token)
This is simple backward compatibility since originally there was no way to call the GitHub object with authentication parameters.
- activate_membership(organization)
Activate the membership to an organization.
- Parameters:
organization (
Organization
) – the organization or organization login for which to activate the membership- Returns:
the activated membership
- Return type:
- add_email_addresses(addresses=[])
Add the addresses to the authenticated user’s account.
- Parameters:
addresses (list) – (optional), email addresses to be added
- Returns:
list of email objects
- Return type:
[
Email
]
- all_events(number=-1, etag=None)
Iterate over public events.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events
- Return type:
- all_organizations(number=-1, since=None, etag=None, per_page=None)
Iterate over every organization in the order they were created.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1, returns all of them
since (int) – (optional), last organization id seen (allows restarting an iteration)
etag (str) – (optional), ETag from a previous request to the same endpoint
per_page (int) – (optional), number of organizations to list per request
- Returns:
generator of organizations
- Return type:
- all_repositories(number=-1, since=None, etag=None, per_page=None)
Iterate over every repository in the order they were created.
- Parameters:
number (int) – (optional), number of repositories to return. Default: -1, returns all of them
since (int) – (optional), last repository id seen (allows restarting an iteration)
etag (str) – (optional), ETag from a previous request to the same endpoint
per_page (int) – (optional), number of repositories to list per request
- Returns:
generator of repositories
- Return type:
- all_users(number=-1, etag=None, per_page=None, since=None)
Iterate over every user in the order they signed up for GitHub.
Changed in version 1.0.0: Inserted the
since
parameter after thenumber
parameter.- Parameters:
number (int) – (optional), number of users to return. Default: -1, returns all of them
since (int) – (optional), ID of the last user that you’ve seen.
etag (str) – (optional), ETag from a previous request to the same endpoint
per_page (int) – (optional), number of users to list per request
- Returns:
generator of users
- Return type:
- app(app_slug)
Retrieve information about a specific app using its “slug”.
New in version 1.2.0.
See also
- Get a single GitHub App
API Documentation
- Parameters:
app_slug – The identifier for the specific slug, e.g.,
test-github3-py-apps
.- Returns:
The app if and only if it is public.
- Return type:
- app_installation(installation_id)
Retrieve a specific App installation by its ID.
See also
- Get a single installation
API Documentation
- Parameters:
installation_id (int) – The ID of the specific installation.
- Returns:
The installation.
- Return type:
- app_installation_for_organization(organization)
Retrieve an App installation for a specific organization.
New in version 1.2.0.
See also
- Find organization installation
API Documentation
- Parameters:
organization (str) – The name of the organization.
- Returns:
The installation
- Return type:
- app_installation_for_repository(owner, repository)
Retrieve an App installation for a specific repository.
New in version 1.2.0.
See also
- Find repository installation
API Documentation
- Parameters:
owner (str) – The name of the owner.
repostory (str) – The name of the repository.
- Returns:
The installation
- Return type:
- app_installation_for_user(user)
Retrieve an App installation for a specific repository.
New in version 1.2.0.
See also
- Find user installation
API Documentation
- Parameters:
user (str) – The name of the user.
- Returns:
The installation
- Return type:
- app_installation_repos(number=-1, etag=None)
Retrieve repositories accessible by app installation.
New in version 3.2.1.
See also
- List repositories accessible to the app installation
API Documentation
- Returns:
The repositories accessible to the app installation
- Return type:
- app_installations(number=-1)
Retrieve the list of installations for the authenticated app.
New in version 1.2.0.
See also
- Find installations
API Documentation
- Returns:
The installations of the authenticated App.
- Return type:
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- authenticated_app()
Retrieve information about the current app.
New in version 1.2.0.
See also
- Get the authenticated GitHub App
API Documentation
- Returns:
Metadata about the application
- Return type:
- authorization(id_num)
Get information about authorization
id
.- Parameters:
id_num (int) – (required), unique id of the authorization
- Returns:
- authorizations(number=-1, etag=None)
Iterate over authorizations for the authenticated user.
Note
This will return a 404 if you are using a token for authentication.
- Parameters:
number (int) – (optional), number of authorizations to return. Default: -1 returns all available authorizations
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of authorizations
- Return type:
- authorize(username, password, scopes=None, note='', note_url='', client_id='', client_secret='')
Obtain an authorization token.
The retrieved token will allow future consumers to use the API without a username and password.
- Parameters:
username (str) – (required)
password (str) – (required)
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
note (str) – (optional), note about the authorization
note_url (str) – (optional), url for the application
client_id (str) – (optional), 20 character OAuth client key for which to create a token
client_secret (str) – (optional), 40 character OAuth client secret for which to create the token
- Returns:
created authorization
- Return type:
- block(username: ShortUser | User | AuthenticatedUser | Collaborator | Contributor | str) bool
Block a specific user from an organization.
New in version 2.1.0.
- Parameters:
username (str) – Name (or user-like instance) of the user to block.
- Returns:
True if successful, Fales otherwise
- Return type:
bool
- blocked_users(number: int = -1, etag: str | None = None) Iterator[ShortUser]
Iterate over the users blocked by this organization.
New in version 2.1.0.
- Parameters:
number (int) – (optional), number of users to iterate over. Default: -1 iterates over all values
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of the members of this team
- Return type:
- check_authorization(access_token)
Check an authorization created by a registered application.
OAuth applications can use this method to check token validity without hitting normal rate limits because of failed login attempts. If the token is valid, it will return True, otherwise it will return False.
- Returns:
True if token is valid, False otherwise
- Return type:
bool
- create_gist(description, files, public=True)
Create a new gist.
Changed in version 1.1.0: Per GitHub’s recent announcement authentication is now required for creating gists.
- Parameters:
description (str) – (required), description of gist
files (dict) – (required), file names with associated dictionaries for content, e.g.
{'spam.txt': {'content': 'File contents ...'}}
public (bool) – (optional), make the gist public if True
- Returns:
the created gist if successful, otherwise
None
- Return type:
created gist
- Return type:
- create_gpg_key(armored_public_key)
Create a new GPG key.
New in version 1.2.0.
- Parameters:
armored_public_key (str) – (required), your GPG key, generated in ASCII-armored format
- Returns:
the created GPG key if successful, otherwise
None
- Return type:
GPGKey
- create_issue(owner, repository, title, body=None, assignee=None, milestone=None, labels=[], assignees=None)
Create an issue on the repository.
Note
body
,assignee
,assignees
,milestone
,labels
are all optional.Warning
This method retrieves the repository first and then uses it to create an issue. If you’re making several issues, you should use
repository
and then usecreate_issue
- Parameters:
owner (str) – (required), login of the owner
repository (str) – (required), repository name
title (str) – (required), Title of issue to be created
body (str) – (optional), The text of the issue, markdown formatted
assignee (str) – (optional), Login of person to assign the issue to
assignees – (optional), logins of the users to assign the issue to
milestone (int) – (optional), id number of the milestone to attribute this issue to (e.g. if
m
is aMilestone
object,m.number
is what you pass here.)labels (list) – (optional), List of label names.
- Returns:
created issue
- Return type:
ShortIssue
- create_key(title, key, read_only=False)
Create a new key for the authenticated user.
- Parameters:
title (str) – (required), key title
key (str) – (required), actual key contents, accepts path as a string or file-like object
read_only (bool) – (optional), restrict key access to read-only, default to False
- Returns:
created key
- Return type:
- create_repository(name, description='', homepage='', private=False, has_issues=True, has_wiki=True, auto_init=False, gitignore_template='', has_projects=True)
Create a repository for the authenticated user.
- Parameters:
name (str) –
(required), name of the repository
description (str) – (optional)
homepage (str) – (optional)
private (str) – (optional), If
True
, create a private repository. API default:False
has_issues (bool) – (optional), If
True
, enable issues for this repository. API default:True
has_wiki (bool) – (optional), If
True
, enable the wiki for this repository. API default:True
auto_init (bool) – (optional), auto initialize the repository
gitignore_template (str) – (optional), name of the git template to use; ignored if auto_init = False.
has_projects (bool) – (optional), If
True
, enable projects for this repository. API default:True
- Returns:
created repository
- Return type:
- delete_email_addresses(addresses=[])
Delete the specified addresses the authenticated user’s account.
- Parameters:
addresses (list) – (optional), email addresses to be removed
- Returns:
True if successful, False otherwise
- Return type:
bool
- emails(number=-1, etag=None)
Iterate over email addresses for the authenticated user.
- Parameters:
number (int) – (optional), number of email addresses to return. Default: -1 returns all available email addresses
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of emails
- Return type:
- emojis()
Retrieve a dictionary of all of the emojis that GitHub supports.
- Returns:
dictionary where the key is what would be in between the colons and the value is the URL to the image, e.g.,
{ '+1': 'https://github.global.ssl.fastly.net/images/...', # ... }
- feeds()
List GitHub’s timeline resources in Atom format.
- Returns:
dictionary parsed to include URITemplates
- Return type:
dict
- follow(username)
Make the authenticated user follow the provided username.
- Parameters:
username (str) – (required), user to follow
- Returns:
True if successful, False otherwise
- Return type:
bool
- followed_by(username, number=-1, etag=None)
Iterate over users being followed by
username
.New in version 1.0.0: This replaces iter_following(‘sigmavirus24’).
- Parameters:
username (str) – (required), login of the user to check
number (int) – (optional), number of people to return. Default: -1 returns all people you follow
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users
- Return type:
- followers(number=-1, etag=None)
Iterate over followers of the authenticated user.
New in version 1.0.0: This replaces iter_followers().
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all followers
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of followers
- Return type:
- followers_of(username, number=-1, etag=None)
Iterate over followers of
username
.New in version 1.0.0: This replaces iter_followers(‘sigmavirus24’).
- Parameters:
username (str) – (required), login of the user to check
number (int) – (optional), number of followers to return. Default: -1 returns all followers
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of followers
- Return type:
- following(number=-1, etag=None)
Iterate over users the authenticated user is following.
New in version 1.0.0: This replaces iter_following().
- Parameters:
number (int) – (optional), number of people to return. Default: -1 returns all people you follow
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gist(id_num)
Retrieve the gist using the specified id number.
- Parameters:
id_num (int) – (required), unique id of the gist
- Returns:
the gist identified by
id_num
- Return type:
- gists(number=-1, etag=None)
Retrieve the authenticated user’s gists.
New in version 1.0.
- Parameters:
number (int) – (optional), number of gists to return. Default: -1, returns all available gists
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of short gists
- Return type:
:class:~github3.gists.ShortGist`
- gists_by(username, number=-1, etag=None)
Iterate over the gists owned by a user.
New in version 1.0.
- Parameters:
username (str) – login of the user who owns the gists
number (int) – (optional), number of gists to return. Default: -1 returns all available gists
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of short gists owned by the specified user
- Return type:
ShortGist
- gitignore_template(language)
Return the template for language.
- Returns:
the template string
- Return type:
str
- gitignore_templates()
Return the list of available templates.
- Returns:
list of template names
- Return type:
[str]
- gpg_key(id_num)
Retrieve the GPG key of the authenticated user specified by id_num.
New in version 1.2.0.
- Returns:
the GPG key specified by id_num
- Return type:
GPGKey
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of the authenticated user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of the GPG keys belonging to the authenticated user
- Return type:
GPGKey
- is_blocking(username: ShortUser | User | AuthenticatedUser | Collaborator | Contributor | str) bool
Check if this organization is blocking a specific user.
New in version 2.1.0.
- Parameters:
username (str) – Name (or user-like instance) of the user to unblock.
- Returns:
True if successful, Fales otherwise
- Return type:
bool
- is_following(username)
Check if the authenticated user is following login.
- Parameters:
username (str) – (required), login of the user to check if the authenticated user is checking
- Returns:
True if following, False otherwise
- Return type:
bool
- is_starred(username, repo)
Check if the authenticated user starred username/repo.
- Parameters:
username (str) – (required), owner of repository
repo (str) – (required), name of repository
- Returns:
True if starred, False otherwise
- Return type:
bool
- issue(username, repository, number)
Fetch issue from owner/repository.
- Parameters:
username (str) – (required), owner of the repository
repository (str) – (required), name of the repository
number (int) – (required), issue number
- Returns:
the issue
- Return type:
- issues(filter='', state='', labels='', sort='', direction='', since=None, number=-1, etag=None)
List all of the authenticated user’s (and organization’s) issues.
Changed in version 0.9.0:
The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.
- Parameters:
filter (str) – accepted values: (‘assigned’, ‘created’, ‘mentioned’, ‘subscribed’) api-default: ‘assigned’
state (str) – accepted values: (‘all’, ‘open’, ‘closed’) api-default: ‘open’
labels (str) – comma-separated list of label names, e.g., ‘bug,ui,@high’
sort (str) – accepted values: (‘created’, ‘updated’, ‘comments’) api-default: created
direction (str) – accepted values: (‘asc’, ‘desc’) api-default: desc
since (
datetime
or str) – (optional), Only issues after this date will be returned. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Znumber (int) – (optional), number of issues to return. Default: -1 returns all issues
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of issues
- Return type:
ShortIssue
- issues_on(username, repository, milestone=None, state=None, assignee=None, mentioned=None, labels=None, sort=None, direction=None, since=None, number=-1, etag=None)
List issues on owner/repository.
Only owner and repository are required.
Changed in version 0.9.0:
The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.
- Parameters:
username (str) – login of the owner of the repository
repository (str) – name of the repository
milestone (int) – None, ‘*’, or ID of milestone
state (str) – accepted values: (‘all’, ‘open’, ‘closed’) api-default: ‘open’
assignee (str) – ‘*’ or login of the user
mentioned (str) – login of the user
labels (str) – comma-separated list of label names, e.g., ‘bug,ui,@high’
sort (str) – accepted values: (‘created’, ‘updated’, ‘comments’) api-default: created
direction (str) – accepted values: (‘asc’, ‘desc’) api-default: desc
since (
datetime
or str) – (optional), Only issues after this date will be returned. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Znumber (int) – (optional), number of issues to return. Default: -1 returns all issues
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of issues
- Return type:
ShortIssue
- key(id_num)
Get the authenticated user’s key specified by id_num.
- Parameters:
id_num (int) – (required), unique id of the key
- Returns:
created key
- Return type:
- keys(number=-1, etag=None)
Iterate over public keys for the authenticated user.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all your keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of keys
- Return type:
- license(name)
Retrieve the license specified by the name.
- Parameters:
name (string) – (required), name of license
- Returns:
the specified license
- Return type:
License
- licenses(number=-1, etag=None)
Iterate over open source licenses.
- Returns:
generator of short license objects
- Return type:
ShortLicense
- login(username=None, password=None, token=None, two_factor_callback=None)
Log the user into GitHub for protected API calls.
- Parameters:
username (str) – login name
password (str) – password for the login
token (str) – OAuth token
two_factor_callback (func) – (optional), function you implement to provide the Two-factor Authentication code to GitHub when necessary
- login_as_app(private_key_pem, app_id, expire_in=600)
Login as a GitHub Application.
New in version 1.2.0.
See also
- Authenticating as an App
GitHub’s documentation of authenticating as an application.
- Parameters:
private_key_pem (bytes) – The bytes of the private key for this GitHub Application.
app_id (int) – The integer identifier for this GitHub Application.
expire_in (int) – The length in seconds for this token to be valid for. Default: 600 seconds (10 minutes)
- login_as_app_installation(private_key_pem, app_id, installation_id, expire_in=30)
Login using your GitHub App’s installation credentials.
New in version 1.2.0.
Changed in version 3.0.0: Added
expire_in
parameter.See also
- Authenticating as an Installation
GitHub’s documentation of authenticating as an installation.
- Create a new installation token
API Documentation
Note
This method makes an API call to retrieve the token.
Warning
This method expires after 1 hour.
- Parameters:
private_key_pem (bytes) – The bytes of the private key for this GitHub Application.
app_id (int) – The integer identifier for this GitHub Application.
installation_id (int) – The integer identifier of your App’s installation.
expire_in (int) – (Optional) The number of seconds in the future that the underlying JWT expires. To prevent tokens from being valid for too long and creating a security risk, the library defaults to 30 seconds. In the event that clock drift is significant between your machine and GitHub’s servers, you can set this higher than 30. Default: 30
- markdown(text, mode='', context='', raw=False)
Render an arbitrary markdown document.
- Parameters:
text (str) – (required), the text of the document to render
mode (str) – (optional), ‘markdown’ or ‘gfm’
context (str) – (optional), only important when using mode ‘gfm’, this is the repository to use as the context for the rendering
raw (bool) – (optional), renders a document like a README.md, no gfm, no context
- Returns:
the HTML formatted markdown text
- Return type:
str
- me()
Retrieve the info for the authenticated user.
New in version 1.0: This was separated from the
user
method.- Returns:
the representation of the authenticated user.
- Return type:
- membership_in(organization)
Retrieve the user’s membership in the specified organization.
- Parameters:
organization (
Organization
) – the organization or organization login to retrieve the authorized user’s membership in- Returns:
the user’s membership
- Return type:
- meta()
Retrieve a dictionary with arrays of addresses in CIDR format.
The addresses in CIDR format specify the addresses that the incoming service hooks will originate from.
New in version 0.5.
- Returns:
CIDR addresses
- Return type:
dict
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- notifications(all=False, participating=False, number=-1, etag=None)
Iterate over the user’s notification.
- Parameters:
all (bool) – (optional), iterate over all notifications
participating (bool) – (optional), only iterate over notifications in which the user is participating
number (int) – (optional), how many notifications to return
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of threads
- Return type:
- octocat(say=None)
Return an easter egg of the API.
- Params str say:
(optional), pass in what you’d like Octocat to say
- Returns:
ascii art of Octocat
- Return type:
str
- organization(username)
Return an Organization object for the login name.
- Parameters:
username (str) – (required), login name of the org
- Returns:
the organization
- Return type:
- organization_issues(name, filter='', state='', labels='', sort='', direction='', since=None, number=-1, etag=None)
Iterate over the organization’s issues.
Note
This only works if the authenticated user belongs to it.
- Parameters:
name (str) – (required), name of the organization
filter (str) – accepted values: (‘assigned’, ‘created’, ‘mentioned’, ‘subscribed’) api-default: ‘assigned’
state (str) – accepted values: (‘open’, ‘closed’) api-default: ‘open’
labels (str) – comma-separated list of label names, e.g., ‘bug,ui,@high’
sort (str) – accepted values: (‘created’, ‘updated’, ‘comments’) api-default: created
direction (str) – accepted values: (‘asc’, ‘desc’) api-default: desc
since (
datetime
or str) – (optional), Only issues after this date will be returned. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Znumber (int) – (optional), number of issues to return. Default: -1, returns all available issues
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of issues
- Return type:
ShortIssue
- organization_memberships(state=None, number=-1, etag=None)
List organizations of which the user is a current or pending member.
- Parameters:
state (str) – (option), state of the membership, i.e., active, pending
- Returns:
iterator of memberships
- Return type:
- organizations(number=-1, etag=None)
Iterate over all organizations the authenticated user belongs to.
This will display both the private memberships and the publicized memberships.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organizations
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of organizations
- Return type:
- organizations_with(username, number=-1, etag=None)
Iterate over organizations with
username
as a public member.New in version 1.0.0: Replaces
iter_orgs('sigmavirus24')
.- Parameters:
username (str) – (optional), user whose orgs you wish to list
number (int) – (optional), number of organizations to return. Default: -1 returns all available organizations
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of organizations
- Return type:
- project(number)
Return the Project with id
number
.- Parameters:
number (int) – id of the project
- Returns:
the project
- Return type:
- project_card(number)
Return the ProjectCard with id
number
.- Parameters:
number (int) – id of the project card
- Returns:
- project_column(number)
Return the ProjectColumn with id
number
.- Parameters:
number (int) – id of the project column
- Returns:
- public_gists(number=-1, etag=None, since=None)
Retrieve all public gists and iterate over them.
New in version 1.0.
- Parameters:
number (int) – (optional), number of gists to return. Default: -1 returns all available gists
etag (str) – (optional), ETag from a previous request to the same endpoint
since (
datetime
or str) – (optional), filters out any gists updated before the given time. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Z
- Returns:
generator of short gists
- Return type:
- pubsubhubbub(mode, topic, callback, secret='')
Create or update a pubsubhubbub hook.
- Parameters:
mode (str) – (required), accepted values: (‘subscribe’, ‘unsubscribe’)
topic (str) – (required), form: https://github.com/:user/:repo/events/:event
callback (str) – (required), the URI that receives the updates
secret (str) – (optional), shared secret key that generates a SHA1 HMAC of the payload content.
- Returns:
True if successful, False otherwise
- Return type:
bool
- pull_request(owner, repository, number)
Fetch pull_request #:number: from :owner:/:repository.
- Parameters:
owner (str) – (required), owner of the repository
repository (str) – (required), name of the repository
number (int) – (required), issue number
- Returns:
PullRequest
- rate_limit()
Return a dictionary with information from /rate_limit.
The dictionary has two keys:
resources
andrate
. Inresources
you can access information aboutcore
orsearch
.Note: the
rate
key will be deprecated before version 3 of the GitHub API is finalized. Do not rely on that key. Instead, make your code future-proof by usingcore
inresources
, e.g.,rates = g.rate_limit() rates['resources']['core'] # => your normal ratelimit info rates['resources']['search'] # => your search ratelimit info
New in version 0.8.
- Returns:
ratelimit mapping
- Return type:
dict
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- repositories(type=None, sort=None, direction=None, number=-1, etag=None)
List repositories for the authenticated user filterable by
type
.Changed in version 0.6: Removed the login parameter for correctness. Use repositories_by instead
- Parameters:
type (str) – (optional), accepted values: (‘all’, ‘owner’, ‘public’, ‘private’, ‘member’) API default: ‘all’
sort (str) – (optional), accepted values: (‘created’, ‘updated’, ‘pushed’, ‘full_name’) API default: ‘created’
direction (str) – (optional), accepted values: (‘asc’, ‘desc’), API default: ‘asc’ when using ‘full_name’, ‘desc’ otherwise
number (int) – (optional), number of repositories to return. Default: -1 returns all repositories
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repositories
- Return type:
- repositories_by(username, type=None, sort=None, direction=None, number=-1, etag=None)
List public repositories for the specified
username
.New in version 0.6.
- Parameters:
username (str) – (required), username
type (str) – (optional), accepted values: (‘all’, ‘owner’, ‘member’) API default: ‘all’
sort (str) – (optional), accepted values: (‘created’, ‘updated’, ‘pushed’, ‘full_name’) API default: ‘created’
direction (str) – (optional), accepted values: (‘asc’, ‘desc’), API default: ‘asc’ when using ‘full_name’, ‘desc’ otherwise
number (int) – (optional), number of repositories to return. Default: -1 returns all repositories
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repositories
- Return type:
- repository(owner, repository)
Retrieve the desired repository.
- Parameters:
owner (str) – (required)
repository (str) – (required)
- Returns:
the repository
- Return type:
- repository_invitations(number=-1, etag=None)
Iterate over the repository invitations for the current user.
- Parameters:
number (int) – (optional), number of invitations to return. Default: -1 returns all available invitations
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repository invitation objects
- Return type:
Invitation
- repository_with_id(number)
Retrieve the repository with the globally unique id.
- Parameters:
number (int) – id of the repository
- Returns:
the repository
- Return type:
- revoke_authorization(access_token)
Revoke specified authorization for an OAuth application.
Revoke all authorization tokens created by your application. This will only work if you have already called
set_client_id
.- Parameters:
access_token (str) – (required), the access_token to revoke
- Returns:
True if successful, False otherwise
- Return type:
bool
- revoke_authorizations()
Revoke all authorizations for an OAuth application.
Revoke all authorization tokens created by your application. This will only work if you have already called
set_client_id
.- Parameters:
client_id (str) – (required), the client_id of your application
- Returns:
True if successful, False otherwise
- Return type:
bool
- search_code(query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None)
Find code via the code search API.
The query can contain any combination of the following supported qualifiers:
in
Qualifies which fields are searched. With this qualifier you can restrict the search to just the file contents, the file path, or both.language
Searches code based on the language it’s written in.fork
Specifies that code from forked repositories should be searched. Repository forks will not be searchable unless the fork has more stars than the parent repository.size
Finds files that match a certain size (in bytes).path
Specifies the path that the resulting file must be at.extension
Matches files with a certain extension.user
orrepo
Limits searches to a specific user or repository.
For more information about these qualifiers, see: http://git.io/-DvAuA
- Parameters:
query (str) – (required), a valid query as described above, e.g.,
addClass in:file language:js repo:jquery/jquery
sort (str) – (optional), how the results should be sorted; option(s):
indexed
; default: best matchorder (str) – (optional), the direction of the sorted results, options:
asc
,desc
; default:desc
per_page (int) – (optional)
text_match (bool) – (optional), if True, return matching search terms. See http://git.io/iRmJxg for more information
number (int) – (optional), number of repositories to return. Default: -1, returns all available repositories
etag (str) – (optional), previous ETag header value
- Returns:
generator of code search results
- Return type:
- search_commits(query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None)
Find commits via the commits search API.
The query can contain any combination of the following supported qualifiers:
author
Matches commits authored by the given username. Example:author:defunkt
.committer
Matches commits committed by the given username. Example:committer:defunkt
.author-name
Matches commits authored by a user with the given name. Example:author-name:wanstrath
.committer-name
Matches commits committed by a user with the given name. Example:committer-name:wanstrath
.author-email
Matches commits authored by a user with the given email. Example:author-email:chris@github.com
.committer-email
Matches commits committed by a user with the given email. Example:committer-email:chris@github.com
.author-date
Matches commits authored within the specified date range. Example:author-date:<2016-01-01
.committer-date
Matches commits committed within the specified date range. Example:committer-date:>2016-01-01
.merge
Matches merge commits when set to totrue
, excludes them when set tofalse
.hash
Matches commits with the specified hash. Example:hash:124a9a0ee1d8f1e15e833aff432fbb3b02632105
.parent
Matches commits whose parent has the specified hash. Example:parent:124a9a0ee1d8f1e15e833aff432fbb3b02632105
.tree
Matches commits with the specified tree hash. Example:tree:99ca967
.is
Matches public repositories when set topublic
, private repositories when set toprivate
.user
ororg
orrepo
Limits the search to a specific user, organization, or repository.
For more information about these qualifiers, see: https://git.io/vb7XQ
- Parameters:
query (str) – (required), a valid query as described above, e.g.,
css repo:octocat/Spoon-Knife
sort (str) – (optional), how the results should be sorted; options:
author-date
,committer-date
; default: best matchorder (str) – (optional), the direction of the sorted results, options:
asc
,desc
; default:desc
per_page (int) – (optional)
number (int) – (optional), number of commits to return. Default: -1, returns all available commits
etag (str) – (optional), previous ETag header value
- Returns:
generator of commit search results
- Return type:
CommitSearchResult
- search_issues(query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None)
Find issues by state and keyword.
The query can contain any combination of the following supported qualifers:
type
With this qualifier you can restrict the search to issues or pull request only.in
Qualifies which fields are searched. With this qualifier you can restrict the search to just the title, body, comments, or any combination of these.author
Finds issues created by a certain user.assignee
Finds issues that are assigned to a certain user.mentions
Finds issues that mention a certain user.commenter
Finds issues that a certain user commented on.involves
Finds issues that were either created by a certain user, assigned to that user, mention that user, or were commented on by that user.state
Filter issues based on whether they’re open or closed.labels
Filters issues based on their labels.language
Searches for issues within repositories that match a certain language.created
orupdated
Filters issues based on times of creation, or when they were last updated.comments
Filters issues based on the quantity of comments.user
orrepo
Limits searches to a specific user or repository.
For more information about these qualifiers, see: http://git.io/d1oELA
- Parameters:
query (str) – (required), a valid query as described above, e.g.,
windows label:bug
sort (str) – (optional), how the results should be sorted; options:
created
,comments
,updated
; default: best matchorder (str) – (optional), the direction of the sorted results, options:
asc
,desc
; default:desc
per_page (int) – (optional)
text_match (bool) – (optional), if True, return matching search terms. See http://git.io/QLQuSQ for more information
number (int) – (optional), number of issues to return. Default: -1, returns all available issues
etag (str) – (optional), previous ETag header value
- Returns:
generator of issue search results
- Return type:
- search_repositories(query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None)
Find repositories via various criteria.
The query can contain any combination of the following supported qualifers:
in
Qualifies which fields are searched. With this qualifier you can restrict the search to just the repository name, description, readme, or any combination of these.size
Finds repositories that match a certain size (in kilobytes).forks
Filters repositories based on the number of forks, and/or whether forked repositories should be included in the results at all.created
orpushed
Filters repositories based on times of creation, or when they were last updated. Format:YYYY-MM-DD
. Examples:created:<2011
,pushed:<2013-02
,pushed:>=2013-03-06
user
orrepo
Limits searches to a specific user or repository.language
Searches repositories based on the language they’re written in.stars
Searches repositories based on the number of stars.
For more information about these qualifiers, see: http://git.io/4Z8AkA
- Parameters:
query (str) – (required), a valid query as described above, e.g.,
tetris language:assembly
sort (str) – (optional), how the results should be sorted; options:
stars
,forks
,updated
; default: best matchorder (str) – (optional), the direction of the sorted results, options:
asc
,desc
; default:desc
per_page (int) – (optional)
text_match (bool) – (optional), if True, return matching search terms. See http://git.io/4ct1eQ for more information
number (int) – (optional), number of repositories to return. Default: -1, returns all available repositories
etag (str) – (optional), previous ETag header value
- Returns:
generator of repository search results
- Return type:
- search_users(query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None)
Find users via the Search API.
The query can contain any combination of the following supported qualifers:
type
With this qualifier you can restrict the search to just personal accounts or just organization accounts.in
Qualifies which fields are searched. With this qualifier you can restrict the search to just the username, public email, full name, or any combination of these.repos
Filters users based on the number of repositories they have.location
Filter users by the location indicated in their profile.language
Search for users that have repositories that match a certain language.created
Filter users based on when they joined.followers
Filter users based on the number of followers they have.
For more information about these qualifiers see: http://git.io/wjVYJw
- Parameters:
query (str) – (required), a valid query as described above, e.g.,
tom repos:>42 followers:>1000
sort (str) – (optional), how the results should be sorted; options:
followers
,repositories
, orjoined
; default: best matchorder (str) – (optional), the direction of the sorted results, options:
asc
,desc
; default:desc
per_page (int) – (optional)
text_match (bool) – (optional), if True, return matching search terms. See http://git.io/_V1zRwa for more information
number (int) – (optional), number of search results to return; Default: -1 returns all available
etag (str) – (optional), ETag header value of the last request.
- Returns:
generator of user search results
- Return type:
- set_client_id(id, secret)
Allow the developer to set their OAuth application credentials.
- Parameters:
id (str) – 20-character hexidecimal client_id provided by GitHub
secret (str) – 40-character hexidecimal client_secret provided by GitHub
- set_user_agent(user_agent)
Allow the user to set their own user agent string.
- Parameters:
user_agent (str) – string used to identify your application. Library default: “github3.py/{version}”, e.g., “github3.py/1.0.0”
- star(username, repo)
Star a repository.
- Parameters:
username (str) – (required), owner of the repo
repo (str) – (required), name of the repo
- Returns:
True if successful, False otherwise
- Return type:
bool
- starred(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by the authenticated user.
Changed in version 1.0.0: This was split from
iter_starred
and requires authentication.- Parameters:
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
number (int) – (optional), number of repositories to return. Default: -1 returns all repositories
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repositories
- Return type:
ShortRepository>
- starred_by(username, sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by
username
.New in version 1.0: This was split from
iter_starred
and requires the login parameter.- Parameters:
username (str) – name of user whose stars you want to see
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
number (int) – (optional), number of repositories to return. Default: -1 returns all repositories
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repositories
- Return type:
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by the authenticated user.
- Parameters:
number (int) – (optional), number of repositories to return. Default: -1 returns all repositories
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repositories
- Return type:
- subscriptions_for(username, number=-1, etag=None)
Iterate over repositories subscribed to by
username
.- Parameters:
username (str) – name of user whose subscriptions you want to see
number (int) – (optional), number of repositories to return. Default: -1 returns all repositories
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of subscribed repositories
- Return type:
- unblock(username: ShortUser | User | AuthenticatedUser | Collaborator | Contributor | str) bool
Unblock a specific user from an organization.
New in version 2.1.0.
- Parameters:
username (str) – Name (or user-like instance) of the user to unblock.
- Returns:
True if successful, Fales otherwise
- Return type:
bool
- unfollow(username)
Make the authenticated user stop following username.
- Parameters:
username (str) – (required)
- Returns:
True if successful, False otherwise
- Return type:
bool
- unstar(username, repo)
Unstar username/repo.
- Parameters:
username (str) – (required), owner of the repo
repo (str) – (required), name of the repo
- Returns:
True if successful, False otherwise
- Return type:
bool
- update_me(name=None, email=None, blog=None, company=None, location=None, hireable=False, bio=None)
Update the profile of the authenticated user.
- Parameters:
name (str) – e.g., ‘John Smith’, not login name
email (str) – e.g., ‘john.smith@example.com’
blog (str) – e.g., ‘http://www.example.com/jsmith/blog’
company (str) –
location (str) –
hireable (bool) – defaults to False
bio (str) – GitHub flavored markdown
- Returns:
True if successful, False otherwise
- Return type:
bool
- user(username)
Retrieve a User object for the specified user name.
- Parameters:
username (str) – name of the user
- Returns:
the user
- Return type:
- user_issues(filter='', state='', labels='', sort='', direction='', since=None, per_page=None, number=-1, etag=None)
List only the authenticated user’s issues.
Will not list organization’s issues. See
organization_issues()
.Changed in version 1.0:
per_page
parameter added beforenumber
Changed in version 0.9.0:
The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.
- Parameters:
filter (str) – accepted values: (‘assigned’, ‘created’, ‘mentioned’, ‘subscribed’) api-default: ‘assigned’
state (str) – accepted values: (‘all’, ‘open’, ‘closed’) api-default: ‘open’
labels (str) – comma-separated list of label names, e.g., ‘bug,ui,@high’
sort (str) – accepted values: (‘created’, ‘updated’, ‘comments’) api-default: created
direction (str) – accepted values: (‘asc’, ‘desc’) api-default: desc
since (
datetime
or str) – (optional), Only issues after this date will be returned. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Znumber (int) – (optional), number of issues to return. Default: -1 returns all issues
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of issues
- Return type:
ShortIssue
- user_teams(number=-1, etag=None)
Get the authenticated user’s teams across all of organizations.
List all of the teams across all of the organizations to which the authenticated user belongs. This method requires user or repo scope when authenticating via OAuth.
- Returns:
generator of teams
- Return type:
- user_with_id(number)
Get the user’s information with id
number
.- Parameters:
number (int) – the user’s id number
- Returns:
the user
- Return type:
- zen()
Return a quote from the Zen of GitHub.
Yet another API Easter Egg
- Returns:
the zen of GitHub
- Return type:
str
Examples
There are some examples of how to get started with this object here.
GitHubEnterprise Object
This has all of the same attributes as the GitHub
object so for brevity’s sake, I’m not listing all of it’s inherited members.
- class github3.github.GitHubEnterprise(url, username='', password='', token='', verify=True, session=None)
An interface to a specific GitHubEnterprise instance.
For GitHub Enterprise users, this object will act as the public API to your instance. You must provide the URL to your instance upon initialization and can provide the rest of the login details just like in the
GitHub
object.There is no need to provide the end of the url (e.g., /api/v3/), that will be taken care of by us.
If you have a self signed SSL for your local github enterprise you can override the validation by passing verify=False.
- admin_stats(option)
Retrieve statistics about this GitHub Enterprise instance.
- Parameters:
option (str) – (required), accepted values: (‘all’, ‘repos’, ‘hooks’, ‘pages’, ‘orgs’, ‘users’, ‘pulls’, ‘issues’, ‘milestones’, ‘gists’, ‘comments’)
- Returns:
the statistics
- Return type:
dict
GitHubSession Object
- class github3.session.GitHubSession(default_connect_timeout=4, default_read_timeout=10)
Our slightly specialized Session object.
Normally this is created automatically by
GitHub
. To use alternate values for network timeouts, this class can be instantiated directly and passed to the GitHub object. For example:gh = github.GitHub(session=session.GitHubSession( default_connect_timeout=T, default_read_timeout=N))
- Parameters:
default_connect_timeout (float) – the number of seconds to wait when establishing a connection to GitHub
default_read_timeout (float) – the number of seconds to wait for a response from GitHub
Issues API Objects
The following objects represent data returned by the Issues API
Issues
- class github3.issues.issue.ShortIssue(json, session: GitHubSession)
Object for the shortened representation of an Issue.
GitHub’s API returns different amounts of information about issues based upon how that information is retrieved. Often times, when iterating over several issues, GitHub will return less information. To provide a clear distinction between the types of issues, github3.py uses different classes with different sets of attributes.
New in version 1.0.0.
This object has the following attributes:
- assignee
Deprecated since version 1.0.0: While the API still returns this attribute, it’s not as useful in the context of multiple assignees.
If a user is assigned to this issue, then it will be represented as a
ShortUser
.
- assignees
If users are assigned to this issue, then they will be represented as a list of
ShortUser
.
- body
The markdown formatted text of the issue as writen by the user who opened the issue.
- closed_at
If this issue is closed, this will be a
datetime
object representing the date and time this issue was closed. Otherwise it will beNone
.
- comments_count
The number of comments on this issue.
- comments_url
The URL to retrieve the comments on this issue from the API.
- created_at
A
datetime
object representing the date and time this issue was created.
- events_url
The URL to retrieve the events related to this issue from the API.
- html_url
The URL to view this issue in a browser.
- id
The unique identifier for this issue in GitHub.
- labels_urlt
A
URITemplate
object that can expand to a URL to retrieve the labels on this issue from the API.
- locked
A boolean attribute representing whether or not this issue is locked.
- number
The number identifying this issue on its parent repository.
- original_labels
If any are assigned to this issue, the list of
ShortLabel
objects representing the labels returned by the API for this issue.
- pull_request_urls
If present, a dictionary of URLs for retrieving information about the associated pull request for this issue.
- state
The current state of this issue, e.g.,
'closed'
or'open'
.
- title
The title for this issue.
- updated_at
A
datetime
object representing the date and time when this issue was last updated.
- add_assignees(users)
Assign
users
to this issue.This is a shortcut for
edit()
.- Parameters:
users (list of str) – users or usernames to assign this issue to
- Returns:
True if successful, False otherwise
- Return type:
bool
- add_labels(*args)
Add labels to this issue.
- Parameters:
args (str) – (required), names of the labels you wish to add
- Returns:
list of labels
- Return type:
ShortLabel
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- close()
Close this issue.
- Returns:
True if successful, False otherwise
- Return type:
bool
- comment(id_num)
Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If you were to look at the comments on issue #15 in sigmavirus24/Todo.txt-python, the first comment’s id is 4150787.
- Parameters:
id_num (int) – (required), comment id, see example above
- Returns:
the comment identified by
id_num
- Return type:
- comments(number=-1, sort='', direction='', since=None)
Iterate over the comments on this issue.
- Parameters:
number (int) – (optional), number of comments to iterate over Default: -1 returns all comments
sort (str) – accepted valuees: (‘created’, ‘updated’) api-default: created
direction (str) – accepted values: (‘asc’, ‘desc’) Ignored without the sort parameter
since (datetime or string) – (optional), Only issues after this date will be returned. This can be a
datetime
or an ISO8601 formatted date string, e.g.,2012-05-20T23:10:27Z
- Returns:
iterator of comments
- Return type:
- create_comment(body)
Create a comment on this issue.
- Parameters:
body (str) – (required), comment body
- Returns:
the created comment
- Return type:
- edit(title=None, body=None, assignee=None, state=None, milestone=None, labels=None, assignees=None)
Edit this issue.
- Parameters:
title (str) – title of the issue
body (str) – markdown formatted body (description) of the issue
assignee (str) – login name of user the issue should be assigned to
state (str) – accepted values: (‘open’, ‘closed’)
milestone (int) –
the number (not title) of the milestone to assign this to, or 0 to remove the milestone
Note
This is not the milestone’s globally unique identifier, it’s value in
number
.labels (list) – list of labels to apply this to
assignees (list of strings) – (optional), login of the users to assign the issue to
- Returns:
True if successful, False otherwise
- Return type:
bool
- events(number=-1)
Iterate over events associated with this issue only.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all events available.
- Returns:
generator of events on this issues
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- is_closed()
Check if the issue is closed.
- Returns:
True if successful, False otherwise
- Return type:
bool
- labels(number=-1, etag=None)
Iterate over the labels associated with this issue.
- Parameters:
number (int) – (optional), number of labels to return. Default: -1 returns all labels applied to this issue.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of labels on this issue
- Return type:
ShortLabel
- lock()
Lock an issue.
- Returns:
True if successful, False otherwise
- Return type:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- pull_request()
Retrieve the pull request associated with this issue.
- Returns:
the pull request associated with this issue
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- remove_all_labels()
Remove all labels from this issue.
- Returns:
the list of current labels (empty) if successful
- Return type:
list
- remove_assignees(users)
Unassign
users
from this issue.This is a shortcut for
edit()
.- Parameters:
users (list of str) – users or usernames to unassign this issue from
- Returns:
True if successful, False otherwise
- Return type:
bool
- remove_label(name)
Remove label
name
from this issue.- Parameters:
name (str) – (required), name of the label to remove
- Returns:
list of removed labels
- Return type:
ShortLabel
- reopen()
Re-open a closed issue.
Note
This is a short cut to using
edit()
.- Returns:
True if successful, False otherwise
- Return type:
bool
- replace_labels(labels)
Replace all labels on this issue with
labels
.- Parameters:
labels (list) – label names
- Returns:
list of labels
- Return type:
ShortLabel
- unlock()
Unlock an issue.
- Returns:
True if successful, False otherwise
- Return type:
bool
- class github3.issues.issue.Issue(json, session: GitHubSession)
Object for the full representation of an Issue.
GitHub’s API returns different amounts of information about issues based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific issue. For example, you would receive this class when calling
issue()
. To provide a clear distinction between the types of issues, github3.py uses different classes with different sets of attributes.Changed in version 1.0.0.
This object has all of the same attributes as a
ShortIssue
as well as the following:- body_html
The HTML formatted body of this issue.
- body_text
The plain-text formatted body of this issue.
- add_assignees(users)
Assign
users
to this issue.This is a shortcut for
edit()
.- Parameters:
users (list of str) – users or usernames to assign this issue to
- Returns:
True if successful, False otherwise
- Return type:
bool
- add_labels(*args)
Add labels to this issue.
- Parameters:
args (str) – (required), names of the labels you wish to add
- Returns:
list of labels
- Return type:
ShortLabel
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- close()
Close this issue.
- Returns:
True if successful, False otherwise
- Return type:
bool
- comment(id_num)
Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If you were to look at the comments on issue #15 in sigmavirus24/Todo.txt-python, the first comment’s id is 4150787.
- Parameters:
id_num (int) – (required), comment id, see example above
- Returns:
the comment identified by
id_num
- Return type:
- comments(number=-1, sort='', direction='', since=None)
Iterate over the comments on this issue.
- Parameters:
number (int) – (optional), number of comments to iterate over Default: -1 returns all comments
sort (str) – accepted valuees: (‘created’, ‘updated’) api-default: created
direction (str) – accepted values: (‘asc’, ‘desc’) Ignored without the sort parameter
since (datetime or string) – (optional), Only issues after this date will be returned. This can be a
datetime
or an ISO8601 formatted date string, e.g.,2012-05-20T23:10:27Z
- Returns:
iterator of comments
- Return type:
- create_comment(body)
Create a comment on this issue.
- Parameters:
body (str) – (required), comment body
- Returns:
the created comment
- Return type:
- edit(title=None, body=None, assignee=None, state=None, milestone=None, labels=None, assignees=None)
Edit this issue.
- Parameters:
title (str) – title of the issue
body (str) – markdown formatted body (description) of the issue
assignee (str) – login name of user the issue should be assigned to
state (str) – accepted values: (‘open’, ‘closed’)
milestone (int) –
the number (not title) of the milestone to assign this to, or 0 to remove the milestone
Note
This is not the milestone’s globally unique identifier, it’s value in
number
.labels (list) – list of labels to apply this to
assignees (list of strings) – (optional), login of the users to assign the issue to
- Returns:
True if successful, False otherwise
- Return type:
bool
- events(number=-1)
Iterate over events associated with this issue only.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all events available.
- Returns:
generator of events on this issues
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- is_closed()
Check if the issue is closed.
- Returns:
True if successful, False otherwise
- Return type:
bool
- labels(number=-1, etag=None)
Iterate over the labels associated with this issue.
- Parameters:
number (int) – (optional), number of labels to return. Default: -1 returns all labels applied to this issue.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of labels on this issue
- Return type:
ShortLabel
- lock()
Lock an issue.
- Returns:
True if successful, False otherwise
- Return type:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- pull_request()
Retrieve the pull request associated with this issue.
- Returns:
the pull request associated with this issue
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- remove_all_labels()
Remove all labels from this issue.
- Returns:
the list of current labels (empty) if successful
- Return type:
list
- remove_assignees(users)
Unassign
users
from this issue.This is a shortcut for
edit()
.- Parameters:
users (list of str) – users or usernames to unassign this issue from
- Returns:
True if successful, False otherwise
- Return type:
bool
- remove_label(name)
Remove label
name
from this issue.- Parameters:
name (str) – (required), name of the label to remove
- Returns:
list of removed labels
- Return type:
ShortLabel
- reopen()
Re-open a closed issue.
Note
This is a short cut to using
edit()
.- Returns:
True if successful, False otherwise
- Return type:
bool
- replace_labels(labels)
Replace all labels on this issue with
labels
.- Parameters:
labels (list) – label names
- Returns:
list of labels
- Return type:
ShortLabel
- unlock()
Unlock an issue.
- Returns:
True if successful, False otherwise
- Return type:
bool
Issue Comments
- class github3.issues.comment.IssueComment(json, session: GitHubSession)
Representation of a comment left on an issue.
See also: http://developer.github.com/v3/issues/comments/
This object has the following attributes:
- body
The markdown formatted original text written by the author.
- body_html
The HTML formatted comment body.
- body_text
The plain-text formatted comment body.
- created_at
A
datetime
object representing the date and time when this comment was created.
- html_url
The URL to view this comment in a browser.
- id
The unique identifier for this comment.
- issue_url
The URL of the parent issue in the API.
- updated_at
A
datetime
object representing the date and time when this comment was most recently updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this comment.
- Returns:
bool
- edit(body)
Edit this comment.
- Parameters:
body (str) – (required), new body of the comment, Markdown formatted
- Returns:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
Issue Events
- class github3.issues.event.IssueEvent(json, session: GitHubSession)
Representation of an event from a specific issue.
This object will be instantiated from calling
events()
which calls https://developer.github.com/v3/issues/events/#list-events-for-an-issueSee also: http://developer.github.com/v3/issues/events
This object has the following attributes:
- commit_id
The string SHA of a commit that referenced the parent issue. If there was no commit referencing this issue, then this will be
None
.
- commit_url
The URL to retrieve commit information from the API for the commit that references the parent issue. If there was no commit, this will be
None
.
- created_at
A
datetime
object representing the date and time this event occurred.
- event
The issue-specific action that generated this event. Some examples are:
closed
reopened
subscribed
merged
referenced
mentioned
assigned
See this list of events for a full listing.
- id
The unique identifier for this event.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- class github3.issues.event.RepositoryIssueEvent(json, session: GitHubSession)
Representation of an issue event on the repository level.
This object will be instantiated from calling
issue_events()
orissue_events()
which call https://developer.github.com/v3/issues/events/#list-events-for-a-repositorySee also: http://developer.github.com/v3/issues/events
This object has all of the attributes of
IssueEvent
and the following:- issue
A
ShortIssue
representing the issue where this event originated from.
Issue Labels
- class github3.issues.label.Label(json, session: GitHubSession)
A representation of a label object defined on a repository.
See also: http://developer.github.com/v3/issues/labels/
This object has the following attributes:
.. attribute:: color
The hexadecimeal representation of the background color of this label.
- description
The description for this label.
- name
The name (display label) for this label.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this label.
- Returns:
True if successfully deleted, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- update(name, color, description=None)
Update this label.
- Parameters:
name (str) – (required), new name of the label
color (str) – (required), color code, e.g., 626262, no leading ‘#’
description (str) – (optional), new description of the label
- Returns:
True if successfully updated, False otherwise
- Return type:
bool
Milestone Objects
- class github3.issues.milestone.Milestone(json, session: GitHubSession)
Representation of milestones on a repository.
See also: http://developer.github.com/v3/issues/milestones/
This object has the following attributes:
- closed_issues_count
The number of closed issues in this milestone.
- created_at
A
datetime
object representing the date and time when this milestone was created.
- description
The written description of this milestone and its purpose.
- due_on
If set, a
datetime
object representing the date and time when this milestone is due.
- id
The unique identifier of this milestone in GitHub.
- number
The repository-local numeric identifier of this milestone. This starts at 1 like issues.
- open_issues_count
The number of open issues still in this milestone.
- state
The state of this milestone, e.g.,
'open'
or'closed'
.
- title
The title of this milestone.
- updated_at
A
datetime
object representing the date and time when this milestone was last updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this milestone.
- Returns:
True if successful, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- labels(number=-1, etag=None)
Iterate over the labels of every associated issue.
Changed in version 0.9: Add etag parameter.
- Parameters:
number (int) – (optional), number of labels to return. Default: -1 returns all available labels.
etag (str) – (optional), ETag header from a previous response
- Returns:
generator of labels
- Return type:
ShortLabel
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- update(title=None, state=None, description=None, due_on=None)
Update this milestone.
All parameters are optional, but it makes no sense to omit all of them at once.
- Parameters:
title (str) – (optional), new title of the milestone
state (str) – (optional), (‘open’, ‘closed’)
description (str) – (optional)
due_on (str) – (optional), ISO 8601 time format: YYYY-MM-DDTHH:MM:SSZ
- Returns:
True if successful, False otherwise
- Return type:
bool
Notifications
This part of the documentation covers the notifications module which contains all of the classes used to represent notification objects in github3.py.
Notification Objects
- class github3.notifications.Thread(json, session: GitHubSession)
Object representing a notification thread.
Changed in version 1.0.0: The
comment
,thread
, andurl
attributes are no longer present because GitHub stopped returning the comment that caused the notification.The
is_unread
method was removed since it just returned theunread
attribute.This object has the following attributes:
- id
The unique identifier for this notification across all GitHub notifications.
- last_read_at
A
datetime
object representing the date and time when the authenticated user last read this thread.
- reason
The reason the authenticated user is receiving this notification.
- repository
A
ShortRepository
this thread originated on.
- subject
A dictionary with the subject of the notification, for example, which issue, pull request, or diff this is in relation to.
- unread
A boolean attribute indicating whether this thread has been read or not.
- updated_at
A
datetime
representing the date and time when this thread was last updated.
See also: http://developer.github.com/v3/activity/notifications/
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete_subscription()
Delete subscription for this thread.
- Returns:
True if successful, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- mark()
Mark the thread as read.
- Returns:
True if successful, False otherwise
- Return type:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- set_subscription(subscribed, ignored)
Set the user’s subscription for this thread.
- Parameters:
subscribed (bool) – (required), determines if notifications should be received from this thread.
ignored (bool) – (required), determines if notifications should be ignored from this thread.
- Returns:
new subscription
- Return type:
- subscription()
Check the status of the user’s subscription to this thread.
- Returns:
the subscription for this thread
- Return type:
- class github3.notifications.ThreadSubscription(json, session: GitHubSession)
This object provides a representation of a thread subscription.
See also: developer.github.com/v3/activity/notifications/#get-a-thread-subscription
Changed in version 1.0.0: The
is_ignored
andis_subscribed
methods were removed. Use the :attr`ignored` andsubscribed
attributes instead.This object has the following attributes:
- created_at
A
datetime
object representing the date and time the user was subscribed to the thread.
- ignored
A boolean attribute indicating whether the user ignored this.
- reason
The reason the user is subscribed to the thread.
- subscribed
A boolean attribute indicating whether the user is subscribed or not.
- thread_url
The URL of the thread resource in the GitHub API.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this subscription.
- Returns:
True if successful, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- set(subscribed, ignored)
Set the user’s subscription for this subscription.
- Parameters:
subscribed (bool) – (required), determines if notifications should be received from this thread.
ignored (bool) – (required), determines if notifications should be ignored from this thread.
- class github3.notifications.RepositorySubscription(json, session: GitHubSession)
This object provides a representation of a thread subscription.
See also: developer.github.com/v3/activity/notifications/#get-a-thread-subscription
Changed in version 1.0.0: The
is_ignored
andis_subscribed
methods were removed. Use the :attr`ignored` andsubscribed
attributes instead.This object has the following attributes:
- created_at
A
datetime
object representing the date and time the user was subscribed to the thread.
- ignored
A boolean attribute indicating whether the user ignored this.
- reason
The reason the user is subscribed to the thread.
- repository_url
The URL of the repository resource in the GitHub API.
- subscribed
A boolean attribute indicating whether the user is subscribed or not.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this subscription.
- Returns:
True if successful, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- set(subscribed, ignored)
Set the user’s subscription for this subscription.
- Parameters:
subscribed (bool) – (required), determines if notifications should be received from this thread.
ignored (bool) – (required), determines if notifications should be ignored from this thread.
Projects and their Associated Objects
This section of the documentation covers the representations of various objects related to the Projects API.
Project Objects
- class github3.projects.Project(json, session: GitHubSession)
Object representing a single project from the API.
See http://developer.github.com/v3/projects/ for more details.
- body
The Markdown formatted text describing the project.
- created_at
A
datetime
representing the date and time when this project was created.
- id
The unique identifier for this project on GitHub.
- name
The name given to this project.
- number
The repository-local identifier of this project.
- owner_url
The URL of the resource in the API of the owning resource - either a repository or an organization.
- updated_at
A
datetime
representing the date and time when this project was last updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- column(id)
Get a project column with the given ID.
- Parameters:
id (int) – (required), the column ID
- Returns:
the desired column in the project
- Return type:
- columns(number=-1, etag=None)
Iterate over the columns in this project.
- Parameters:
number (int) – (optional), number of columns to return. Default: -1 returns all available columns.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of columns
- Return type:
ProjectColumn
- create_column(name)
Create a column in this project.
- Parameters:
name (str) – (required), name of the column
- Returns:
the created project column
- Return type:
- delete()
Delete this project.
- Returns:
True if successfully deleted, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- update(name=None, body=None)
Update this project.
- Parameters:
name (str) – (optional), new name of the project
body (str) – (optional), new body of the project
- Returns:
True if successfully updated, False otherwise
- Return type:
bool
- class github3.projects.ProjectColumn(json, session: GitHubSession)
Object representing a column in a project.
See http://developer.github.com/v3/projects/columns/
- created_at
A
datetime
object representing the date and time when the column was created.
- id
The unique identifier for this column across GitHub.
- name
The name given to this column.
- project_url
The URL used to retrieve the project that owns this column via the API.
- updated_at
A
datetime
object representing the date and time when the column was last updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- card(id)
Get a project card with the given ID.
- Parameters:
id (int) – (required), the card ID
- Returns:
the card identified by the provided id
- Return type:
- cards(number=-1, etag=None)
Iterate over the cards in this column.
- Parameters:
number (int) – (optional), number of cards to return. Default: -1 returns all available cards.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of cards
- Return type:
ProjectCard
- create_card_with_content_id(content_id, content_type)
Create a content card in this project column.
- Parameters:
content_id (int) – (required), the ID of the content
content_type (str) – (required), the type of the content
- Returns:
the created card
- Return type:
- create_card_with_issue(issue)
Create a card in this project column linked with an Issue.
- Parameters:
issue (
Issue
) – (required), an issue with which to link the card. Can also beShortIssue
.- Returns:
the created card
- Return type:
- create_card_with_note(note)
Create a note card in this project column.
- Parameters:
note (str) – (required), the note content
- Returns:
the created card
- Return type:
- delete()
Delete this column.
- Returns:
True if successful, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- move(position)
Move this column.
- Parameters:
position (str) – (required), can be one of first, last, or after:<column-id>, where <column-id> is the id value of a column in the same project.
- Returns:
True if successful, False otherwise
- Return type:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- update(name=None)
Update this column.
- Parameters:
name (str) – (optional), name of the column
- Returns:
True if successful, False otherwise
- Return type:
bool
- class github3.projects.ProjectCard(json, session: GitHubSession)
Object representing a “card” on a project.
See http://developer.github.com/v3/projects/cards/
- column_url
The URL to retrieve this card’s column via the API.
- content_url
The URl to retrieve this card’s body content via the API.
- created_at
A
datetime
object representing the date and time when the column was created.
- id
The globally unique identifier for this card.
- note
The body of the note attached to this card.
- updated_at
A
datetime
object representing the date and time when the column was last updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this card.
- Returns:
True if successfully deleted, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- move(position, column_id)
Move this card.
- Parameters:
position (str) – (required), can be one of top, bottom, or after:<card-id>, where <card-id> is the id value of a card in the same column, or in the new column specified by column_id.
column_id (int) – (required), the id value of a column in the same project.
- Returns:
True if successfully moved, False
- Return type:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- retrieve_issue_from_content()
Attempt to retrieve an Issue from the content url.
- Returns:
The issue that backs up this particular project card if the card has a content_url.
Note
Cards can be created from Issues and Pull Requests. Pull Requests are also technically Issues so this method is always safe to call.
- Return type:
- Raises:
CardHasNoContentUrl
- retrieve_pull_request_from_content()
Attempt to retrieve an PullRequest from the content url.
- Returns:
The pull request that backs this particular project card if the card has a content_url.
Note
Cards can be created from Issues and Pull Requests.
- Return type:
- Raises:
CardHasNoContentUrl
- update(note=None)
Update this card.
- Parameters:
note (str) – (optional), the card’s note content. Only valid for cards without another type of content, so this cannot be specified if the card already has a content_id and content_type.
- Returns:
True if successfully updated, False otherwise
- Return type:
bool
Pull Requests and their Associated Objects
This section of the documentation covers the representations of various objects related to the Pull Requests API.
Pull Request Objects
- class github3.pulls.ShortPullRequest(json, session: GitHubSession)
Object for the shortened representation of a PullRequest.
GitHub’s API returns different amounts of information about prs based upon how that information is retrieved. Often times, when iterating over several prs, GitHub will return less information. To provide a clear distinction between the types of Pull Requests, github3.py uses different classes with different sets of attributes.
New in version 1.0.0.
The attributes available on this object are:
- url
The URL that describes this exact pull request.
- assignee
Deprecated since version 1.0.0: Use
assignees
instead.The assignee of the pull request, if present, represented as an instance of
ShortUser
- assignees
New in version 1.0.0.
A list of the assignees of the pull request. If not empty, a list of instances of
ShortUser
.
- body
The Markdown formatted body of the pull request message.
- body_html
The HTML formatted body of the pull request mesage.
- body_text
The plain-text formatted body of the pull request message.
- closed_at
A
datetime
object representing the date and time when this pull request was closed.
- comments_url
The URL to retrieve the comments on this pull request from the API.
- commits_url
The URL to retrieve the commits in this pull request from the API.
- created_at
A
datetime
object representing the date and time when this pull request was created.
- diff_url
The URL to retrieve the diff for this pull request via the API.
- html_url
The URL one would use to view this pull request in the browser.
- id
The unique ID of this pull request across all of GitHub.
- issue_url
The URL of the resource that represents this pull request as an issue.
- links
A dictionary provided by
_links
in the API response.New in version 1.0.0.
- merge_commit_sha
If unmerged, holds the sha of the commit to test mergability. If merged, holds commit sha of the merge commit, squashed commit on the base branch or the commit that the base branch was updated to after rebasing the PR.
- merged_at
A
datetime
object representing the date and time this pull request was merged. If this pull request has not been merged then this attribute will beNone
.
- number
The number of the pull request on the repository.
- patch_url
The URL to retrieve the patch for this pull request via the API.
- rebaseable
A boolean attribute indicating whether GitHub deems this pull request is rebaseable. None if not set.
- repository
A
ShortRepository
from thebase
instance.
- review_comment_urlt
A URITemplate instance that expands to provide the review comment URL provided a number.
- review_comments_url
The URl to retrieve all review comments on this pull request from the API.
- state
The current state of this pull request.
- title
The title of this pull request.
- updated_at
A
datetime
instance representing the date and time when this pull request was last updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- close()
Close this Pull Request without merging.
- Returns:
True if successful, False otherwise
- Return type:
bool
- commits(number=-1, etag=None)
Iterate over the commits on this pull request.
- Parameters:
number (int) – (optional), number of commits to return. Default: -1 returns all available commits.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repository commit objects
- Return type:
- create_comment(body)
Create a comment on this pull request’s issue.
- Parameters:
body (str) – (required), comment body
- Returns:
the comment that was created on the pull request
- Return type:
- create_review(body, commit_id=None, event=None, comments=None)
Create a review comment on this pull request.
Warning
If you do not specify
event
, GitHub will default it toPENDING
which means that your review will need to be submitted after creation. (See alsosubmit()
.)- Parameters:
body (str) – The comment text itself, required when using COMMENT or REQUEST_CHANGES.
commit_id (str) – The SHA of the commit to comment on
event (str) – The review action you want to perform. Actions include APPROVE, REQUEST_CHANGES or COMMENT. By leaving this blank you set the action to PENDING and will need to submit the review. Leaving blank may result in a 422 error response which will need to be handled.
comments (list) –
Array of draft review comment objects. Please see Github’s Create a pull request review documentation for details on review comment objects. At the time of writing these were a dictionary with 3 keys: path, position and body.
- Returns:
The created review.
- Return type:
PullReview
- create_review_comment(body, commit_id, path, position)
Create a review comment on this pull request.
Note
All parameters are required by the GitHub API.
- Parameters:
body (str) – The comment text itself
commit_id (str) – The SHA of the commit to comment on
path (str) – The relative path of the file to comment on
position (int) – The line index in the diff to comment on.
- Returns:
The created review comment.
- Return type:
- create_review_requests(reviewers=None, team_reviewers=None)
Ask for reviews on this pull request.
- Parameters:
reviewers (list) – The users to which request a review
team_reviewers (list) – The teams to which request a review
- Returns:
The pull request on which the reviews were requested
- Return type:
- delete_review_requests(reviewers=None, team_reviewers=None)
Cancel review requests on this pull request.
- Parameters:
reviewers (list) – The users whose review is no longer requested
team_reviewers (list) – The teams whose review is no longer requested
- Returns:
True if successful, False otherwise
- Return type:
bool
- diff()
Return the diff.
- Returns:
representation of the diff
- Return type:
bytes
- files(number=-1, etag=None)
Iterate over the files associated with this pull request.
- Parameters:
number (int) – (optional), number of files to return. Default: -1 returns all available files.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of pull request files
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- is_merged()
Check to see if the pull request was merged.
Changed in version 1.0.0: This now always makes a call to the GitHub API. To avoid that, check
merged
before making this call.- Returns:
True if merged, False otherwise
- Return type:
bool
- issue()
Retrieve the issue associated with this pull request.
- Returns:
the issue object that this pull request builds upon
- Return type:
Issue
- issue_comments(number=-1, etag=None)
Iterate over the issue comments on this pull request.
In this case, GitHub leaks implementation details. Pull Requests are really just Issues with a diff. As such, comments on a pull request that are not in-line with code, are technically issue comments.
- Parameters:
number (int) – (optional), number of comments to return. Default: -1 returns all available comments.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of non-review comments on this pull request
- Return type:
- merge(commit_message=None, sha=None, merge_method='merge', commit_title=None)
Merge this pull request.
Changed in version 1.3.0: The
commit_title
parameter has been added to allow users to set the merge commit title.Changed in version 1.0.0: The boolean
squash
parameter has been replaced withmerge_method
which requires a string.- Parameters:
commit_message (str) – (optional), message to be used for the merge commit
commit_title (str) – (optional), message to be used for the merge commit title
sha (str) – (optional), SHA that pull request head must match to merge.
merge_method (str) – (optional), Change the merge method. Either ‘merge’, ‘squash’ or ‘rebase’. Default is ‘merge’.
- Returns:
True if successful, False otherwise
- Return type:
bool
- Returns:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- patch()
Return the patch.
- Returns:
bytestring representation of the patch
- Return type:
bytes
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- reopen()
Re-open a closed Pull Request.
- Returns:
True if successful, False otherwise
- Return type:
bool
- review_comments(number=-1, etag=None)
Iterate over the review comments on this pull request.
- Parameters:
number (int) – (optional), number of comments to return. Default: -1 returns all available comments.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of review comments
- Return type:
- review_requests()
Retrieve the review requests associated with this pull request.
- Returns:
review requests associated with this pull request
- Return type:
ReviewRequests
- reviews(number=-1, etag=None)
Iterate over the reviews associated with this pull request.
- Parameters:
number (int) – (optional), number of reviews to return. Default: -1 returns all available files.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of reviews for this pull request
- Return type:
PullReview
- update(title=None, body=None, state=None, base=None, maintainer_can_modify=None)
Update this pull request.
- Parameters:
title (str) – (optional), title of the pull
body (str) – (optional), body of the pull request
state (str) – (optional), one of (‘open’, ‘closed’)
base (str) – (optional), Name of the branch on the current repository that the changes should be pulled into.
maintainer_can_modify (bool) – (optional), Indicates whether a maintainer is allowed to modify the pull request or not.
- Returns:
True if successful, False otherwise
- Return type:
bool
- class github3.pulls.PullRequest(json, session: GitHubSession)
Object for the full representation of a PullRequest.
GitHub’s API returns different amounts of information about prs based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific pr. For example, you would receive this class when calling
pull_request()
. To provide a clear distinction between the types of prs, github3.py uses different classes with different sets of attributes.Changed in version 1.0.0.
This object has all of the same attributes as
ShortPullRequest
as well as the following:- additions_count
The number of lines of code added in this pull request.
- deletions_count
The number of lines of code deleted in this pull request.
- comments_count
The number of comments left on this pull request.
- commits_count
The number of commits included in this pull request.
- mergeable
A boolean attribute indicating whether GitHub deems this pull request is mergeable.
- mergeable_state
A string indicating whether this would be a ‘clean’ or ‘dirty’ merge.
- merged
A boolean attribute indicating whether the pull request has been merged or not.
- merged_by
An instance of
ShortUser
to indicate the user who merged this pull request. If this hasn’t been merged or ifmergeable
is still being decided by GitHub this will beNone
.
- review_comments_count
The number of review comments on this pull request.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- close()
Close this Pull Request without merging.
- Returns:
True if successful, False otherwise
- Return type:
bool
- commits(number=-1, etag=None)
Iterate over the commits on this pull request.
- Parameters:
number (int) – (optional), number of commits to return. Default: -1 returns all available commits.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repository commit objects
- Return type:
- create_comment(body)
Create a comment on this pull request’s issue.
- Parameters:
body (str) – (required), comment body
- Returns:
the comment that was created on the pull request
- Return type:
- create_review(body, commit_id=None, event=None, comments=None)
Create a review comment on this pull request.
Warning
If you do not specify
event
, GitHub will default it toPENDING
which means that your review will need to be submitted after creation. (See alsosubmit()
.)- Parameters:
body (str) – The comment text itself, required when using COMMENT or REQUEST_CHANGES.
commit_id (str) – The SHA of the commit to comment on
event (str) – The review action you want to perform. Actions include APPROVE, REQUEST_CHANGES or COMMENT. By leaving this blank you set the action to PENDING and will need to submit the review. Leaving blank may result in a 422 error response which will need to be handled.
comments (list) –
Array of draft review comment objects. Please see Github’s Create a pull request review documentation for details on review comment objects. At the time of writing these were a dictionary with 3 keys: path, position and body.
- Returns:
The created review.
- Return type:
PullReview
- create_review_comment(body, commit_id, path, position)
Create a review comment on this pull request.
Note
All parameters are required by the GitHub API.
- Parameters:
body (str) – The comment text itself
commit_id (str) – The SHA of the commit to comment on
path (str) – The relative path of the file to comment on
position (int) – The line index in the diff to comment on.
- Returns:
The created review comment.
- Return type:
- create_review_requests(reviewers=None, team_reviewers=None)
Ask for reviews on this pull request.
- Parameters:
reviewers (list) – The users to which request a review
team_reviewers (list) – The teams to which request a review
- Returns:
The pull request on which the reviews were requested
- Return type:
- delete_review_requests(reviewers=None, team_reviewers=None)
Cancel review requests on this pull request.
- Parameters:
reviewers (list) – The users whose review is no longer requested
team_reviewers (list) – The teams whose review is no longer requested
- Returns:
True if successful, False otherwise
- Return type:
bool
- diff()
Return the diff.
- Returns:
representation of the diff
- Return type:
bytes
- files(number=-1, etag=None)
Iterate over the files associated with this pull request.
- Parameters:
number (int) – (optional), number of files to return. Default: -1 returns all available files.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of pull request files
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- is_merged()
Check to see if the pull request was merged.
Changed in version 1.0.0: This now always makes a call to the GitHub API. To avoid that, check
merged
before making this call.- Returns:
True if merged, False otherwise
- Return type:
bool
- issue()
Retrieve the issue associated with this pull request.
- Returns:
the issue object that this pull request builds upon
- Return type:
Issue
- issue_comments(number=-1, etag=None)
Iterate over the issue comments on this pull request.
In this case, GitHub leaks implementation details. Pull Requests are really just Issues with a diff. As such, comments on a pull request that are not in-line with code, are technically issue comments.
- Parameters:
number (int) – (optional), number of comments to return. Default: -1 returns all available comments.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of non-review comments on this pull request
- Return type:
- merge(commit_message=None, sha=None, merge_method='merge', commit_title=None)
Merge this pull request.
Changed in version 1.3.0: The
commit_title
parameter has been added to allow users to set the merge commit title.Changed in version 1.0.0: The boolean
squash
parameter has been replaced withmerge_method
which requires a string.- Parameters:
commit_message (str) – (optional), message to be used for the merge commit
commit_title (str) – (optional), message to be used for the merge commit title
sha (str) – (optional), SHA that pull request head must match to merge.
merge_method (str) – (optional), Change the merge method. Either ‘merge’, ‘squash’ or ‘rebase’. Default is ‘merge’.
- Returns:
True if successful, False otherwise
- Return type:
bool
- Returns:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- patch()
Return the patch.
- Returns:
bytestring representation of the patch
- Return type:
bytes
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- reopen()
Re-open a closed Pull Request.
- Returns:
True if successful, False otherwise
- Return type:
bool
- review_comments(number=-1, etag=None)
Iterate over the review comments on this pull request.
- Parameters:
number (int) – (optional), number of comments to return. Default: -1 returns all available comments.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of review comments
- Return type:
- review_requests()
Retrieve the review requests associated with this pull request.
- Returns:
review requests associated with this pull request
- Return type:
ReviewRequests
- reviews(number=-1, etag=None)
Iterate over the reviews associated with this pull request.
- Parameters:
number (int) – (optional), number of reviews to return. Default: -1 returns all available files.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of reviews for this pull request
- Return type:
PullReview
- update(title=None, body=None, state=None, base=None, maintainer_can_modify=None)
Update this pull request.
- Parameters:
title (str) – (optional), title of the pull
body (str) – (optional), body of the pull request
state (str) – (optional), one of (‘open’, ‘closed’)
base (str) – (optional), Name of the branch on the current repository that the changes should be pulled into.
maintainer_can_modify (bool) – (optional), Indicates whether a maintainer is allowed to modify the pull request or not.
- Returns:
True if successful, False otherwise
- Return type:
bool
- class github3.pulls.PullDestination(json, session: GitHubSession)
The object that represents a pull request destination.
This is the base class for the
Head
andBase
objects. Each has identical attributes to this object.Please see GitHub’s Pull Request Documentation for more information.
- ref
The full reference string for the git object
- label
The label for the destination (e.g., ‘master’, ‘mybranch’)
- sha
The SHA of the commit at the head of the destination
- repository
A
ShortRepository
representing the repository containing this destination
- repo
A tuple containing the login and repository name, e.g., (‘sigmavirus24’, ‘github3.py’)
This attribute is generated by github3.py and may be deprecated in the future.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- class github3.pulls.Head(json, session: GitHubSession)
An object representing the Head destination of a pull request.
See
PullDestination
for more details.
- class github3.pulls.Base(json, session: GitHubSession)
An object representing the Base destination of a pull request.
See
PullDestination
for more details.
- class github3.pulls.PullFile(json, session: GitHubSession)
The object that represents a file in a pull request.
Please see GitHub’s Pull Request Files Documentation for more information.
- additions_count
The number of additions made to this file
- blob_url
The API resource used to retrieve the blob for this file
- changes_count
The number of changes made to this file
- contents_url
The API resource to view the raw contents of this file
- deletions_count
The number of deletions made to this file
- filename
The name of this file
- patch
The patch generated by this
Note
If the patch is larger than a specific size it may be missing from GitHub’s response. The attribute will be set to
None
in this case.
- raw_url
The API resource to view the raw diff of this file
- sha
The SHA of the commit that this file belongs to
- status
The string with the status of the file, e.g., ‘added’
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- contents()
Return the contents of the file.
- Returns:
An object representing the contents of this file
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
Review Objects
- class github3.pulls.ReviewComment(json, session: GitHubSession)
Object representing review comments left on a pull request.
Please see GitHub’s Pull Comments Documentation for more information.
- id
The unique identifier for this comment across all GitHub review comments.
- author_association
The role of the author of this comment on the repository.
- body
The Markdown formatted body of this comment.
- body_html
The HTML formatted body of this comment.
- body_text
The plain text formatted body of this comment.
- commit_id
The SHA of current commit this comment was left on.
- created_at
A
datetime
instance representing the date and time this comment was created.
- diff_hunk
A string representation of the hunk of the diff where the comment was left.
- html_url
The URL to view this comment in the webbrowser.
- links
A dictionary of relevant URLs usually returned in the
_links
attribute.
- original_commit_id
The SHA of the original commit this comment was left on.
- original_position
The original position within the diff that this comment was left on.
- pull_request_url
The URL to retrieve the pull request via the API.
- updated_at
A
datetime
instance representing the date and time this comment was updated.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this comment.
- Returns:
True if successful, False otherwise
- Return type:
bool
- edit(body)
Edit this comment.
- Parameters:
body (str) – (required), new body of the comment, Markdown formatted
- Returns:
True if successful, False otherwise
- Return type:
bool
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- reply(body)
Reply to this review comment with a new review comment.
- Parameters:
body (str) – The text of the comment.
- Returns:
The created review comment.
- Return type:
Repository API Objects
This section of the documentation covers the representations of various objects related to the Repositories API.
Repository Objects
- class github3.repos.repo.Repository(json, session: GitHubSession)
This organizes the full representation of a single Repository.
The full representation of a Repository is not returned in collections but instead in individual requests, e.g.,
repository()
.This object has all the same attributes as
ShortRepository
as well as:- allow_merge_commit
Note
This attribute is not guaranteed to be present.
Whether the repository allows creating a merge commit when merging when a pull request.
- allow_rebase_merge
Note
This attribute is not guaranteed to be present.
Whether the repository allows rebasing when merging a pull request.
- allow_squash_merge
Note
This attribute is not guaranteed to be present.
Whether the repository allows squashing commits when merging a pull request.
- archived
A boolean attribute that describes whether the current repository has been archived or not.
- clone_url
This is the URL that can be used to clone the repository via HTTPS, e.g.,
https://github.com/sigmavirus24/github3.py.git
.
- created_at
A parsed
datetime
object representing the date the repository was created.
- default_branch
This is the default branch of the repository as configured by its administrator(s).
- forks_count
This is the number of forks of the repository.
- git_url
This is the URL that can be used to clone the repository via the Git protocol, e.g.,
git://github.com/sigmavirus24/github3.py
.
- has_downloads
This is a boolean attribute that conveys whether or not the repository has downloads.
- has_issues
This is a boolean attribute that conveys whether or not the repository has issues.
- has_pages
This is a boolean attribute that conveys whether or not the repository has pages.
- has_wiki
This is a boolean attribute that conveys whether or not the repository has a wiki.
- homepage
This is the administrator set homepage URL for the project. This may not be provided.
- language
This is the language GitHub has detected for the repository.
- original_license
Note
When used with a Github Enterprise instance <= 2.12.7, this attribute will not be returned. To handle these situations sensitively, the attribute will be set to
None
. Repositories may still have a license associated with them in these cases.This is the
ShortLicense
returned as part of the repository. To retrieve the most recent license, see thelicense()
method.
- mirror_url
The URL that GitHub is mirroring the repository from.
- network_count
The size of the repository’s “network”.
- open_issues_count
The number of issues currently open on the repository.
- parent
A representation of the parent repository as
ShortRepository
. If this Repository has no parent then this will beNone
.
- pushed_at
A parsed
datetime
object representing the date a push was last made to the repository.
- size
The size of the repository.
- source
A representation of the source repository as
ShortRepository
. If this Repository has no source then this will beNone
.
- ssh_url
This is the URL that can be used to clone the repository via the SSH protocol, e.g.,
ssh@github.com:sigmavirus24/github3.py.git
.
- stargazers_count
The number of people who have starred this repository.
- subscribers_count
The number of people watching (or who have subscribed to notifications about) this repository.
- svn_url
This is the URL that can be used to clone the repository via SVN, e.g.,
ssh@github.com:sigmavirus24/github3.py.git
.
- updated_at
A parsed
datetime
object representing the date a the repository was last updated by its administrator(s).
- watchers_count
The number of people watching this repository.
See also: http://developer.github.com/v3/repos/
- add_collaborator(username, permission=None)
Add
username
as a collaborator to a repository.- Parameters:
username (str or
User
) – (required), username of the userpermission (str) – (optional), permission to grant the collaborator, valid on organization repositories only. Can be ‘pull’, ‘triage’, ‘push’, ‘maintain’, ‘admin’ or an organization-defined custom role name.
- Returns:
True if successful, False otherwise
- Return type:
- archive(format, path='', ref='master')
Get the tarball or zipball archive for this repo at ref.
See: http://developer.github.com/v3/repos/contents/#get-archive-link
- Parameters:
format (str) – (required), accepted values: (‘tarball’, ‘zipball’)
path (str, file) – (optional), path where the file should be saved to, default is the filename provided in the headers and will be written in the current directory. it can take a file-like object as well
ref (str) – (optional)
- Returns:
True if successful, False otherwise
- Return type:
bool
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- asset(id)
Return a single asset.
- Parameters:
id (int) – (required), id of the asset
- Returns:
the asset
- Return type:
- assignees(number=-1, etag=None)
Iterate over all assignees to which an issue may be assigned.
- Parameters:
number (int) – (optional), number of assignees to return. Default: -1 returns all available assignees
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users
- Return type:
- auto_trigger_checks(app_id, enabled=True)
Change preferences for automatic creation of check suites.
New in version 1.3.0.
Enable/disable the automatic flow when creating check suites. By default, the check suite is automatically created each time code is pushed. When the automatic creation is disable they can be created manually.
- Parameters:
app_id (int) – (required), the id of the GitHub App
enabled (bool) – (optional), enable automatic creation of check suites Default: True
- Returns:
the check suite settings for this repository
- Return type:
dict
- blob(sha)
Get the blob indicated by
sha
.- Parameters:
sha (str) – (required), sha of the blob
- Returns:
the git blob
- Return type:
- branch(name)
Get the branch
name
of this repository.- Parameters:
name (str) – (required), branch name
- Returns:
the branch
- Return type:
- branches(number=-1, protected=False, etag=None)
Iterate over the branches in this repository.
- Parameters:
number (int) – (optional), number of branches to return. Default: -1 returns all branches
protected (bool) – (optional), True lists only protected branches. Default: False
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of branches
- Return type:
- check_run(id)
Return a single check run.
New in version 1.3.0.
- Parameters:
id (int) – (required), id of the check run
- Returns:
the check run
- Return type:
CheckRun
- check_suite(id)
Return a single check suite.
New in version 1.3.0.
- Parameters:
id (int) – (required), id of the check suite
- Returns:
the check suite
- Return type:
CheckSuite
- clones(per='day')
Get the total number of repository clones and breakdown per day or week for the last 14 days.
New in version 1.4.0.
See also: https://developer.github.com/v3/repos/traffic/
- Parameters:
per (str) – (optional), (‘day’, ‘week’), clones reporting period. Default ‘day’ will return clones per day for the last 14 days.
- Returns:
clones data
- Return type:
ClonesStats
- Raises:
ValueError if per is not a valid choice
- code_frequency(number=-1, etag=None)
Iterate over the code frequency per week.
New in version 0.7.
Returns a weekly aggregate of the number of additions and deletions pushed to this repository.
Note
All statistics methods may return a 202. On those occasions, you will not receive any objects. You should store your iterator and check the new
last_status
attribute. If it is a 202 you should wait before re-requesting.- Parameters:
number (int) – (optional), number of weeks to return. Default: -1 returns all weeks
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of lists
[seconds_from_epoch, additions, deletions]
- Return type:
list
- collaborators(affiliation='all', number=-1, etag=None)
Iterate over the collaborators of this repository.
- Parameters:
affiliation (str) – (optional), affiliation of the collaborator to the repository. Default: “all” returns contributors with all affiliations
number (int) – (optional), number of collaborators to return. Default: -1 returns all comments
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of collaborators
- Return type:
- comments(number=-1, etag=None)
Iterate over comments on all commits in the repository.
- Parameters:
number (int) – (optional), number of comments to return. Default: -1 returns all comments
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of comments on commits
- Return type:
- commit(sha)
Get a single (repo) commit.
See
git_commit()
for the Git Data Commit.- Parameters:
sha (str) – (required), sha of the commit
- Returns:
the commit
- Return type:
- commit_activity(number=-1, etag=None)
Iterate over last year of commit activity by week.
New in version 0.7.
See: http://developer.github.com/v3/repos/statistics/
Note
All statistics methods may return a 202. On those occasions, you will not receive any objects. You should store your iterator and check the new
last_status
attribute. If it is a 202 you should wait before re-requesting.- Parameters:
number (int) – (optional), number of weeks to return. Default -1 will return all of the weeks.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of dictionaries
- Return type:
dict
- commit_comment(comment_id)
Get a single commit comment.
- Parameters:
comment_id (int) – (required), id of the comment used by GitHub
- Returns:
the comment on the commit
- Return type:
- commits(sha=None, path=None, author=None, number=-1, etag=None, since=None, until=None, per_page=None)
Iterate over commits in this repository.
- Parameters:
sha (str) – (optional), sha or branch to start listing commits from
path (str) – (optional), commits containing this path will be listed
author (str) – (optional), GitHub login, real name, or email to filter commits by (using commit author)
number (int) – (optional), number of commits to return. Default: -1 returns all commits
etag (str) – (optional), ETag from a previous request to the same endpoint
since (
datetime
or str) – (optional), Only commits after this date will be returned. This can be adatetime
or anISO8601
formatted date string.until (
datetime
or str) – (optional), Only commits before this date will be returned. This can be adatetime
or anISO8601
formatted date string.per_page (int) – (optional), commits listing page size
- Returns:
generator of commits
- Return type:
- compare_commits(base, head)
Compare two commits.
- Parameters:
base (str) – (required), base for the comparison
head (str) – (required), compare this against base
- Returns:
the comparison of the commits
- Return type:
- contributor_statistics(number=-1, etag=None)
Iterate over the contributors list.
New in version 0.7.
See also: http://developer.github.com/v3/repos/statistics/
Note
All statistics methods may return a 202. On those occasions, you will not receive any objects. You should store your iterator and check the new
last_status
attribute. If it is a 202 you should wait before re-requesting.- Parameters:
number (int) – (optional), number of weeks to return. Default -1 will return all of the weeks.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of contributor statistics for each contributor
- Return type:
- contributors(anon=False, number=-1, etag=None)
Iterate over the contributors to this repository.
- Parameters:
anon (bool) – (optional), True lists anonymous contributors as well
number (int) – (optional), number of contributors to return. Default: -1 returns all contributors
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of contributor users
- Return type:
- create_blob(content, encoding)
Create a blob with
content
.- Parameters:
content (str) – (required), content of the blob
encoding (str) – (required), (‘base64’, ‘utf-8’)
- Returns:
string of the SHA returned
- Returns:
str
- create_branch_ref(name, sha=None)
Create a branch git reference.
This is a shortcut for calling
github3.repos.repo.Repository.create_ref()
.- Parameters:
branch (str) – (required), the branch to create
sha (str) – the commit to base the branch from
- Returns:
a reference object representing the branch
- Return type:
- create_check_run(name, head_sha, details_url=None, external_id=None, started_at=None, status=None, conclusion=None, completed_at=None, output=None, actions=None)
Create a check run object on a commit
New in version 1.3.0.
- Parameters:
name (str) – (required), The name of the check
head_sha (str) – (required), The SHA of the commit
details_url (str) – (optional), The URL of the integrator’s site that has the full details of the check
external_id (str) – (optional), A reference for the run on the integrator’s system
started_at (str) – (optional), ISO 8601 time format: YYYY-MM-DDTHH:MM:SSZ
status (str) – (optional), (‘queued’, ‘in_progress’, ‘completed’)
conclusion (str) – (optional), Required if you provide ‘completed_at’, or a ‘status’ of ‘completed’. The final conclusion of the check. (‘success’, ‘failure’, ‘neutral’, ‘cancelled’, ‘timed_out’, ‘action_required’)
completed_at (str) – (optional), Required if you provide ‘conclusion’. ISO 8601 time format: YYYY-MM-DDTHH:MM:SSZ
output (dict) – (optional), key-value pairs representing the output. Format:
{'title': 'string', 'summary': 'text, can be markdown', 'text': 'text, can be markdown', 'annotations': [{}], 'images': [{}]}
actions (list) – (optional), list of action objects. Format is:
[{'label': 'text', 'description', 'text', 'identifier', 'text'}, ...]
- Returns:
the created check run
- Return type:
CheckRun
- create_check_suite(head_sha)
Create a check suite object on a commit
New in version 1.3.0.
- Parameters:
head_sha (str) – The sha of the head commit.
- Returns:
the created check suite
- Return type:
CheckSuite
- create_comment(body, sha, path=None, position=None, line=1)
Create a comment on a commit.
- Parameters:
body (str) – (required), body of the message
sha (str) – (required), commit id
path (str) – (optional), relative path of the file to comment on
position (str) – (optional), line index in the diff to comment on
line (int) – (optional), line number of the file to comment on, default: 1
- Returns:
the created comment
- Return type:
- create_commit(message, tree, parents, author=None, committer=None)
Create a commit on this repository.
- Parameters:
message (str) – (required), commit message
tree (str) – (required), SHA of the tree object this commit points to
parents (list) – (required), SHAs of the commits that were parents of this commit. If empty, the commit will be written as the root commit. Even if there is only one parent, this should be an array.
author (dict) – (optional), if omitted, GitHub will use the authenticated user’s credentials and the current time. Format: {‘name’: ‘Committer Name’, ‘email’: ‘name@example.com’, ‘date’: ‘YYYY-MM-DDTHH:MM:SS+HH:00’}
committer (dict) – (optional), if ommitted, GitHub will use the author parameters. Should be the same format as the author parameter.
- Returns:
the created commit
- Return type:
- create_deployment(ref, required_contexts=None, payload='', auto_merge=False, description='', environment=None)
Create a deployment.
- Parameters:
ref (str) – (required), The ref to deploy. This can be a branch, tag, or sha.
required_contexts (list) – Optional array of status contexts verified against commit status checks. To bypass checking entirely pass an empty array. Default: []
payload (str) – Optional JSON payload with extra information about the deployment. Default: “”
auto_merge (bool) – Optional parameter to merge the default branch into the requested deployment branch if necessary. Default: False
description (str) – Optional short description. Default: “”
environment (str) – Optional name for the target deployment environment (e.g., production, staging, qa). Default: “production”
- Returns:
the created deployment
- Return type:
- create_file(path, message, content, branch=None, committer=None, author=None)
Create a file in this repository.
See also: http://developer.github.com/v3/repos/contents/#create-a-file
- Parameters:
path (str) – (required), path of the file in the repository
message (str) – (required), commit message
content (bytes) – (required), the actual data in the file
branch (str) – (optional), branch to create the commit on. Defaults to the default branch of the repository
committer (dict) – (optional), if no information is given the authenticated user’s information will be used. You must specify both a name and email.
author (dict) – (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
- Returns:
dictionary of contents and commit for created file
- Return type:
- create_fork(organization=None)
Create a fork of this repository.
- Parameters:
organization (str) – (required), login for organization to create the fork under
- Returns:
the fork of this repository
- Return type:
- create_hook(name, config, events=['push'], active=True)
Create a hook on this repository.
- Parameters:
name (str) – (required), name of the hook
config (dict) – (required), key-value pairs which act as settings for this hook
events (list) – (optional), events the hook is triggered for
active (bool) – (optional), whether the hook is actually triggered
- Returns:
the created hook
- Return type:
- create_issue(title, body=None, assignee=None, milestone=None, labels=None, assignees=None)
Create an issue on this repository.
- Parameters:
title (str) – (required), title of the issue
body (str) – (optional), body of the issue
assignee (str) – (optional), login of the user to assign the issue to
milestone (int) – (optional), id number of the milestone to attribute this issue to (e.g.
m
is aMilestone
object,m.number
is what you pass here.)labels ([str]) – (optional), labels to apply to this issue
assignees ([str]) – (optional), login of the users to assign the issue to
- Returns:
the created issue
- Return type:
- create_key(title, key, read_only=False)
Create a deploy key.
- Parameters:
title (str) – (required), title of key
key (str) – (required), key text
read_only (bool) – (optional), restrict key access to read-only, default is False
- Returns:
the created key
- Return type:
- create_label(name, color, description=None)
Create a label for this repository.
- Parameters:
name (str) – (required), name to give to the label
color (str) – (required), value of the color to assign to the label, e.g., ‘#fafafa’ or ‘fafafa’ (the latter is what is sent)
description (str) – (optional), description to give to the label
- Returns:
the created label
- Return type:
- create_milestone(title, state=None, description=None, due_on=None)
Create a milestone for this repository.
- Parameters:
title (str) – (required), title of the milestone
state (str) – (optional), state of the milestone, accepted values: (‘open’, ‘closed’), default: ‘open’
description (str) – (optional), description of the milestone
due_on (str) – (optional), ISO 8601 formatted due date
- Returns:
the created milestone
- Return type:
- create_project(name, body=None)
Create a project for this repository.
- Parameters:
name (str) – (required), name of the project
body (str) – (optional), body of the project
- Returns:
the created project
- Return type:
- create_pull(title, base, head, body=None, maintainer_can_modify=None)
Create a pull request of
head
ontobase
branch in this repo.- Parameters:
title (str) – (required)
base (str) – (required), e.g., ‘master’
head (str) – (required), e.g., ‘username:branch’
body (str) – (optional), markdown formatted description
maintainer_can_modify (bool) – (optional), Indicates whether a maintainer is allowed to modify the pull request or not.
- Returns:
the created pull request
- Return type:
- create_pull_from_issue(issue, base, head)
Create a pull request from issue #``issue``.
- Parameters:
issue (int) – (required), issue number
base (str) – (required), e.g., ‘master’
head (str) – (required), e.g., ‘username:branch’
- Returns:
the created pull request
- Return type:
- create_ref(ref, sha)
Create a reference in this repository.
- Parameters:
ref (str) – (required), fully qualified name of the reference, e.g.
refs/heads/master
. If it doesn’t start withrefs
and contain at least two slashes, GitHub’s API will reject it.sha (str) – (required), SHA1 value to set the reference to
- Returns:
the created ref
- Return type:
- create_release(tag_name, target_commitish=None, name=None, body=None, draft=False, prerelease=False)
Create a release for this repository.
- Parameters:
tag_name (str) – (required), name to give to the tag
target_commitish (str) – (optional), vague concept of a target, either a SHA or a branch name.
name (str) – (optional), name of the release
body (str) – (optional), description of the release
draft (bool) – (optional), whether this release is a draft or not
prerelease (bool) – (optional), whether this is a prerelease or not
- Returns:
the created release
- Return type:
- create_status(sha, state, target_url=None, description=None, context='default')
Create a status object on a commit.
- Parameters:
sha (str) – (required), SHA of the commit to create the status on
state (str) – (required), state of the test; only the following are accepted: ‘pending’, ‘success’, ‘error’, ‘failure’
target_url (str) – (optional), URL to associate with this status.
description (str) – (optional), short description of the status
context (str) – (optional), A string label to differentiate this status from the status of other systems
- Returns:
the created status
- Return type:
- create_tag(tag, message, sha, obj_type, tagger, lightweight=False)
Create a tag in this repository.
By default, this method creates an annotated tag. If you wish to create a lightweight tag instead, pass
lightweight=True
.If you are creating an annotated tag, this method makes 2 calls to the API:
Creates the tag object
Creates the reference for the tag
This behaviour is required by the GitHub API.
- Parameters:
tag (str) – (required), name of the tag
message (str) – (required), tag message
sha (str) – (required), SHA of the git object this is tagging
obj_type (str) – (required), type of object being tagged, e.g., ‘commit’, ‘tree’, ‘blob’
tagger (dict) – (required), containing the name, email of the tagger and optionally the date it was tagged
lightweight (bool) – (optional), if False, create an annotated tag, otherwise create a lightweight tag (a Reference).
- Returns:
if creating a lightweight tag, this will return a
Reference
, otherwise it will return aTag
- Return type:
- create_tree(tree, base_tree=None)
Create a tree on this repository.
- Parameters:
tree (list) – (required), specifies the tree structure. Format: [{‘path’: ‘path/file’, ‘mode’: ‘filemode’, ‘type’: ‘blob or tree’, ‘sha’: ‘44bfc6d…’}]
base_tree (str) – (optional), SHA1 of the tree you want to update with new data
- Returns:
the created tree
- Return type:
- delete()
Delete this repository.
- Returns:
True if successful, False otherwise
- Return type:
bool
- delete_key(key_id)
Delete the key with the specified id from your deploy keys list.
- Returns:
True if successful, False otherwise
- Return type:
bool
- delete_subscription()
Delete the user’s subscription to this repository.
- Returns:
True if successful, False otherwise
- Return type:
bool
- deployment(id)
Retrieve the deployment identified by
id
.- Parameters:
id (int) – (required), id for deployments.
- Returns:
the deployment
- Return type:
- deployments(number=-1, etag=None)
Iterate over deployments for this repository.
- Parameters:
number (int) – (optional), number of deployments to return. Default: -1, returns all available deployments
etag (str) – (optional), ETag from a previous request for all deployments
- Returns:
generator of deployments
- Return type:
- directory_contents(directory_path, ref=None, return_as=<class 'list'>)
Get the contents of each file in
directory_path
.If the path provided is actually a directory, you will receive a list back of the form:
[('filename.md', Contents(...)), ('github.py', Contents(...)), # ... ('fiz.py', Contents(...))]
You can either then transform it into a dictionary:
contents = dict(repo.directory_contents('path/to/dir/'))
Or you can use the
return_as
parameter to have it return a dictionary for you:contents = repo.directory_contents('path/to/dir/', return_as=dict)
- Parameters:
path (str) – (required), path to file, e.g. github3/repos/repo.py
ref (str) – (optional), the string name of a commit/branch/tag. Default: master
return_as – (optional), how to return the directory’s contents. Default:
list
- Returns:
list of tuples of the filename and the Contents returned
- Return type:
[(str,
Contents
)]- Raises:
github3.exceptions.UnprocessableResponseBody – When the requested directory is not actually a directory
- edit(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, default_branch=None, archived=None, allow_merge_commit=None, allow_squash_merge=None, allow_rebase_merge=None, has_projects=None)
Edit this repository.
- Parameters:
name (str) – (required), name of the repository
description (str) – (optional), If not
None
, change the description for this repository. API default:None
- leave value unchanged.homepage (str) – (optional), If not
None
, change the homepage for this repository. API default:None
- leave value unchanged.private (bool) – (optional), If
True
, make the repository private. IfFalse
, make the repository public. API default:None
- leave value unchanged.has_issues (bool) – (optional), If
True
, enable issues for this repository. IfFalse
, disable issues for this repository. API default:None
- leave value unchanged.has_wiki (bool) – (optional), If
True
, enable the wiki for this repository. IfFalse
, disable the wiki for this repository. API default:None
- leave value unchanged.has_downloads (bool) – (optional), If
True
, enable downloads for this repository. IfFalse
, disable downloads for this repository. API default:None
- leave value unchanged.default_branch (str) – (optional), If not
None
, change the default branch for this repository. API default:None
- leave value unchanged.archived (bool) – (optional), If not
None
, toggle the archived attribute on the repository to control whether it is archived or not.allow_rebase_merge (bool) – (optional), If not
None
, change whether the merge strategy that allows adding all commits from the head branch onto the base branch individually is enabled for this repository. API default:None
- leave value unchanged.allow_squash_merge (bool) – (optional), If not
None
, change whether combining all commits from the head branch into a single commit in the base branch is allowed. API default:None
- leave value unchanged.allow_merge_commit (bool) – (optional), If not
None
, change whether adding all commits from the head branch to the base branch with a merge commit is allowed. API default:None
- leave value unchanged.has_projects (bool) – (optional), If
True
, enable projects for this repository. IfFalse
, disable projects projects for this repository. API default:None
- leave value unchanged.
- Returns:
True if successful, False otherwise
- Return type:
bool
- events(number=-1, etag=None)
Iterate over events on this repository.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events
- Return type:
- file_contents(path, ref=None)
Get the contents of the file pointed to by
path
.- Parameters:
path (str) – (required), path to file, e.g. github3/repos/repo.py
ref (str) – (optional), the string name of a commit/branch/tag. Default: master
- Returns:
the contents of the file requested
- Return type:
- forks(sort='', number=-1, etag=None)
Iterate over forks of this repository.
- Parameters:
sort (str) – (optional), accepted values: (‘newest’, ‘oldest’, ‘stargazers’), API default: ‘newest’
number (int) – (optional), number of forks to return. Default: -1 returns all forks
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of forks of this repository
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- git_commit(sha)
Get a single (git) commit.
- Parameters:
sha (str) – (required), sha of the commit
- Returns:
the single commit data from git
- Return type:
- hook(hook_id)
Get a single hook.
- Parameters:
hook_id (int) – (required), id of the hook
- Returns:
the hook
- Return type:
- hooks(number=-1, etag=None)
Iterate over hooks registered on this repository.
- Parameters:
number (int) – (optional), number of hoks to return. Default: -1 returns all hooks
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of hooks
- Return type:
- ignore()
Ignore notifications from this repository for the user.
New in version 1.0.
This replaces
Repository#set_subscription
.- Returns:
the new repository subscription
- Return type:
:class:~github3.notifications.RepositorySubscription`
- import_issue(title, body, created_at, assignee=None, milestone=None, closed=None, labels=None, comments=None)
Import an issue into the repository.
See also: https://gist.github.com/jonmagic/5282384165e0f86ef105
- Parameters:
title (string) – (required) Title of issue
body (string) – (required) Body of issue
created_at (
datetime
or str) – (required) Creation timestampassignee (string) – (optional) Username to assign issue to
milestone (int) – (optional) Milestone ID
closed (boolean) – (optional) Status of issue is Closed if True
labels (list) – (optional) List of labels containing string names
comments (list) – (optional) List of dictionaries which contain created_at and body attributes
- Returns:
the imported issue
- Return type:
- imported_issue(imported_issue_id)
Retrieve imported issue specified by imported issue id.
- Parameters:
imported_issue_id (int) – (required) id of imported issue
- Returns:
the imported issue
- Return type:
- imported_issues(number=-1, since=None, etag=None)
Retrieve the collection of imported issues via the API.
See also: https://gist.github.com/jonmagic/5282384165e0f86ef105
- Parameters:
number (int) – (optional), number of imported issues to return. Default: -1 returns all branches
since – (optional), Only imported issues after this date will be returned. This can be a
datetime
instance, ISO8601 formatted date string, or a string formatted like so:2016-02-04
i.e.%Y-%m-%d
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of imported issues
- Return type:
- invitations(number=-1, etag=None)
Iterate over the invitations to this repository.
- Parameters:
number (int) – (optional), number of invitations to return. Default: -1 returns all available invitations
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repository invitation objects
- Return type:
Invitation
- is_assignee(username)
Check if the user can be assigned an issue on this repository.
- Parameters:
username (str or
User
) – name of the user to check- Returns:
bool
- is_collaborator(username)
Check to see if
username
is a collaborator on this repository.- Parameters:
username (str or
User
) – (required), login for the user- Returns:
True if successful, False otherwise
- Return type:
bool
- issue(number)
Get the issue specified by
number
.- Parameters:
number (int) – (required), number of the issue on this repository
- Returns:
the issue
- Return type:
- issue_events(number=-1, etag=None)
Iterate over issue events on this repository.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events on issues
- Return type:
- issues(milestone=None, state=None, assignee=None, mentioned=None, labels=None, sort=None, direction=None, since=None, number=-1, etag=None)
Iterate over issues on this repo based upon parameters passed.
Changed in version 0.9.0: The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.- Parameters:
milestone (int) – (optional), ‘none’, or ‘*’
state (str) – (optional), accepted values: (‘all’, ‘open’, ‘closed’)
assignee (str) – (optional), ‘none’, ‘*’, or login name
mentioned (str) – (optional), user’s login name
labels (str) – (optional), comma-separated list of labels, e.g. ‘bug,ui,@high’
sort – (optional), accepted values: (‘created’, ‘updated’, ‘comments’, ‘created’)
direction (str) – (optional), accepted values: (‘asc’, ‘desc’)
since (
datetime
or str) – (optional), Only issues after this date will be returned. This can be adatetime
or anISO8601
formatted date string, e.g., 2012-05-20T23:10:27Znumber (int) – (optional), Number of issues to return. By default all issues are returned
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of issues
- Return type:
ShortIssue
- key(id_num)
Get the specified deploy key.
- Parameters:
id_num (int) – (required), id of the key
- Returns:
the deploy key
- Return type:
- keys(number=-1, etag=None)
Iterate over deploy keys on this repository.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of keys
- Return type:
- label(name)
Get the label specified by
name
.- Parameters:
name (str) – (required), name of the label
- Returns:
the label
- Return type:
- labels(number=-1, etag=None)
Iterate over labels on this repository.
- Parameters:
number (int) – (optional), number of labels to return. Default: -1 returns all available labels
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of labels
- Return type:
- languages(number=-1, etag=None)
Iterate over the programming languages used in the repository.
- Parameters:
number (int) – (optional), number of languages to return. Default: -1 returns all used languages
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of tuples
- Return type:
tuple
- latest_pages_build()
Get the build information for the most recent Pages build.
- Returns:
the information for the most recent build
- Return type:
- latest_release()
Get the latest release.
Draft releases and prereleases are not returned by this endpoint.
- Returns:
the release
- Return type:
- license()
Get the contents of a license for the repo.
- Returns:
the license
- Return type:
RepositoryLicense
- mark_notifications(last_read='')
Mark all notifications in this repository as read.
- Parameters:
last_read (str) – (optional), Describes the last point that notifications were checked. Anything updated since this time will not be updated. Default: Now. Expected in ISO 8601 format:
YYYY-MM-DDTHH:MM:SSZ
. Example: “2012-10-09T23:39:01Z”.- Returns:
True if successful, False otherwise
- Return type:
bool
- merge(base, head, message='')
Perform a merge from
head
intobase
.- Parameters:
base (str) – (required), where you’re merging into
head (str) – (required), where you’re merging from
message (str) – (optional), message to be used for the commit
- Returns:
the commit resulting from the merge
- Return type:
- milestone(number)
Get the milestone indicated by
number
.- Parameters:
number (int) – (required), unique id number of the milestone
- Returns:
the milestone
- Return type:
- milestones(state=None, sort=None, direction=None, number=-1, etag=None)
Iterate over the milestones on this repository.
- Parameters:
state (str) – (optional), state of the milestones, accepted values: (‘open’, ‘closed’)
sort (str) – (optional), how to sort the milestones, accepted values: (‘due_date’, ‘completeness’)
direction (str) – (optional), direction to sort the milestones, accepted values: (‘asc’, ‘desc’)
number (int) – (optional), number of milestones to return. Default: -1 returns all milestones
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of milestones
- Return type:
- network_events(number=-1, etag=None)
Iterate over events on a network of repositories.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events
- Return type:
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- notifications(all=False, participating=False, since=None, number=-1, etag=None)
Iterate over the notifications for this repository.
- Parameters:
all (bool) – (optional), show all notifications, including ones marked as read
participating (bool) – (optional), show only the notifications the user is participating in directly
since (
datetime
or str) – (optional), filters out any notifications updated before the given time. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Zetag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of notification threads
- Return type:
- pages()
Get information about this repository’s pages site.
- Returns:
information about this repository’s GitHub pages site
- Return type:
- pages_builds(number=-1, etag=None)
Iterate over pages builds of this repository.
- Parameters:
number (int) – (optional) the number of builds to return
etag (str) – (optional), ETag value from a previous request
- Returns:
generator of builds
- Return type:
- project(id, etag=None)
Return the organization project with the given ID.
- Parameters:
id (int) – (required), ID number of the project
- Returns:
the project
- Return type:
- projects(number=-1, etag=None)
Iterate over projects for this organization.
- Parameters:
number (int) – (optional), number of members to return. Default: -1 will return all available.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of projects
- Return type:
- pull_request(number)
Get the pull request indicated by
number
.- Parameters:
number (int) – (required), number of the pull request.
- Returns:
the pull request
- Return type:
- pull_requests(state=None, head=None, base=None, sort='created', direction='desc', number=-1, etag=None)
List pull requests on repository.
Changed in version 0.9.0:
The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.The
sort
parameter was added.The
direction
parameter was added.
- Parameters:
state (str) – (optional), accepted values: (‘all’, ‘open’, ‘closed’)
head (str) – (optional), filters pulls by head user and branch name in the format
user:ref-name
, e.g.,seveas:debian
base (str) – (optional), filter pulls by base branch name. Example:
develop
.sort (str) – (optional), Sort pull requests by
created
,updated
,popularity
,long-running
. Default: ‘created’direction (str) – (optional), Choose the direction to list pull requests. Accepted values: (‘desc’, ‘asc’). Default: ‘desc’
number (int) – (optional), number of pulls to return. Default: -1 returns all available pull requests
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of pull requests
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- readme()
Get the README for this repository.
- Returns:
this repository’s readme
- Return type:
- ref(ref)
Get a reference pointed to by
ref
.The most common will be branches and tags. For a branch, you must specify ‘heads/branchname’ and for a tag, ‘tags/tagname’. Essentially, the system should return any reference you provide it in the namespace, including notes and stashes (provided they exist on the server).
- Parameters:
ref (str) – (required)
- Returns:
the reference
- Return type:
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- refs(subspace='', number=-1, etag=None)
Iterate over references for this repository.
- Parameters:
subspace (str) – (optional), e.g. ‘tags’, ‘stashes’, ‘notes’
number (int) – (optional), number of refs to return. Default: -1 returns all available refs
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of references
- Return type:
- release(id)
Get a single release.
- Parameters:
id (int) – (required), id of release
- Returns:
the release
- Return type:
- release_from_tag(tag_name)
Get a release by tag name.
release_from_tag() returns a release with specified tag while release() returns a release with specified release id
- Parameters:
tag_name (str) – (required) name of tag
- Returns:
the release
- Return type:
- releases(number=-1, etag=None)
Iterate over releases for this repository.
- Parameters:
number (int) – (optional), number of refs to return. Default: -1 returns all available refs
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of releases
- Return type:
- remove_collaborator(username)
Remove collaborator
username
from the repository.- Parameters:
username (str or
User
) – (required), login name of the collaborator- Returns:
True if successful, False otherwise
- Return type:
bool
- replace_topics(new_topics)
Replace the repository topics with
new_topics
.- Parameters:
topics (list) – (required), new topics of the repository
- Returns:
new topics of the repository
- Return type:
Topics
- stargazers(number=-1, etag=None)
List users who have starred this repository.
- Parameters:
number (int) – (optional), number of stargazers to return. Default: -1 returns all subscribers available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users
- Return type:
- statuses(sha, number=-1, etag=None)
Iterate over the statuses for a specific SHA.
Warning
Deprecated in v1.0. Also deprecated upstream https://developer.github.com/v3/repos/statuses/
- Parameters:
sha (str) – SHA of the commit to list the statuses of
number (int) – (optional), return up to number statuses. Default: -1 returns all available statuses.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of statuses
- Return type:
- subscribe()
Subscribe the user to this repository’s notifications.
New in version 1.0.
This replaces
Repository#set_subscription
- Returns:
the new repository subscription
- Return type:
- subscribers(number=-1, etag=None)
Iterate over users subscribed to this repository.
- Parameters:
number (int) – (optional), number of subscribers to return. Default: -1 returns all subscribers available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users subscribed to this repository
- Return type:
- subscription()
Return subscription for this Repository.
- Returns:
the user’s subscription to this repository
- Return type:
- tag(sha)
Get an annotated tag.
http://learn.github.com/p/tagging.html
- Parameters:
sha (str) – (required), sha of the object for this tag
- Returns:
the annotated tag
- Return type:
- tags(number=-1, etag=None)
Iterate over tags on this repository.
- Parameters:
number (int) – (optional), return up to at most number tags. Default: -1 returns all available tags.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of tags with GitHub repository specific information
- Return type:
- teams(number=-1, etag=None)
Iterate over teams with access to this repository.
- Parameters:
number (int) – (optional), return up to number Teams. Default: -1 returns all Teams.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of teams
- Return type:
- topics()
Get the topics of this repository.
- Returns:
this repository’s topics
- Return type:
Topics
- tree(sha, recursive=False)
Get a tree.
- Parameters:
sha (str) – (required), sha of the object for this tree
recursive (bool) – (optional), whether to fetch the tree recursively
- Returns:
the tree
- Return type:
- unignore()
Unignore notifications from this repository for the user.
New in version 1.3.
This replaces
Repository#set_subscription
.- Returns:
the new repository subscription
- Return type:
:class:~github3.notifications.RepositorySubscription`
- unsubscribe()
Unsubscribe the user to this repository’s notifications.
New in version 1.3.
This replaces
Repository#set_subscription
- Returns:
the new repository subscription
- Return type:
- views(per='day')
Get the total number of repository views and breakdown per day or week for the last 14 days.
New in version 1.4.0.
See also: https://developer.github.com/v3/repos/traffic/
- Parameters:
per (str) – (optional), (‘day’, ‘week’), views reporting period. Default ‘day’ will return views per day for the last 14 days.
- Returns:
views data
- Return type:
ViewsStats
- Raises:
ValueError if per is not a valid choice
- weekly_commit_count()
Retrieve the total commit counts.
Note
All statistics methods may return a 202. If github3.py receives a 202 in this case, it will return an emtpy dictionary. You should give the API a moment to compose the data and then re -request it via this method.
..versionadded:: 0.7
The dictionary returned has two entries:
all
andowner
. Each has a fifty-two element long list of commit counts. (Note:all
includes the owner.)d['all'][0]
will be the oldest week,d['all'][51]
will be the most recent.- Returns:
the commit count as a dictionary
- Return type:
dict
- class github3.repos.repo.ShortRepository(json, session: GitHubSession)
This represents a Repository object returned in collections.
GitHub’s API returns different amounts of information about repositories based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific repository. For example, you would receive this class when calling
repository()
. To provide a clear distinction between the types of repositories, github3.py uses different classes with different sets of attributes.This object only has the following attributes:
- url
The GitHub API URL for this repository, e.g.,
https://api.github.com/repos/sigmavirus24/github3.py
.
- archive_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkarchive_urlt.variables
for the list of variables that can be passed toarchive_urlt.expand()
.
- assignees_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkassignees_urlt.variables
for the list of variables that can be passed toassignees_urlt.expand()
.
- blobs_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkblobs_urlt.variables
for the list of variables that can be passed toblobs_urlt.expand()
.
- branches_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkbranches_urlt.variables
for the list of variables that can be passed tobranches_urlt.expand()
.
- collaborators_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkcollaborators_urlt.variables
for the list of variables that can be passed tocollaborators_urlt.expand()
.
- comments_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkcomments_urlt.variables
for the list of variables that can be passed tocomments_urlt.expand()
.
- commits_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkcommits_urlt.variables
for the list of variables that can be passed tocommits_urlt.expand()
.
- compare_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkcompare_urlt.variables
for the list of variables that can be passed tocompare_urlt.expand()
.
- contents_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkcontents_urlt.variables
for the list of variables that can be passed tocontents_urlt.expand()
.
- contributors_url
The URL to retrieve this repository’s list of contributors.
- deployments_url
The URL to retrieve this repository’s list of deployments.
- description
The administrator created description of the repository.
- downloads_url
The URL to retrieve this repository’s list of downloads.
- events_url
The URL to retrieve this repository’s list of events.
- fork
Whether or not this repository is a fork of another.
- forks_url
The URL to retrieve this repository’s list of forks.
- full_name
The full name of this repository, e.g.,
sigmavirus24/github3.py
.
- git_commits_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkgit_commits_urlt.variables
for the list of variables that can be passed togit_commits_urlt.expand()
.
- git_refs_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkgit_refs_urlt.variables
for the list of variables that can be passed togit_refs_urlt.expand()
.
- git_tags_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkgit_tags_urlt.variables
for the list of variables that can be passed togit_tags_urlt.expand()
.
- hooks_url
The URL to retrieve this repository’s list of hooks.
- html_url
The HTML URL of this repository, e.g.,
https://github.com/sigmavirus24/github3.py
.
- id
The unique GitHub assigned numerical id of this repository.
- issue_comment_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkissue_comment_urlt.variables
for the list of variables that can be passed toissue_comment_urlt.expand()
.
- issue_events_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkissue_events_urlt.variables
for the list of variables that can be passed toissue_events_urlt.expand()
.
- issues_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkissues_urlt.variables
for the list of variables that can be passed toissues_urlt.expand()
.
- keys_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkkeys_urlt.variables
for the list of variables that can be passed tokeys_urlt.expand()
.
- labels_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checklabels_urlt.variables
for the list of variables that can be passed tolabels_urlt.expand()
.
- languages_url
The URL to retrieve this repository’s list of languages.
- merges_url
The URL to retrieve this repository’s list of merges.
- milestones_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkmilestones_urlt.variables
for the list of variables that can be passed tomilestones_urlt.expand()
.
- name
The name of the repository, e.g.,
github3.py
.
- notifications_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checknotifications_urlt.variables
for the list of variables that can be passed tonotifications_urlt.expand()
.
- private
Whether the repository is private or public.
- pulls_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkpulls_urlt.variables
for the list of variables that can be passed topulls_urlt.expand()
.
- releases_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkreleases_urlt.variables
for the list of variables that can be passed toreleases_urlt.expand()
.
- stargazers_url
The URL to retrieve this repository’s list of stargazers.
- statuses_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checkstatuses_urlt.variables
for the list of variables that can be passed tostatuses_urlt.expand()
.
- subscribers_url
The URL to retrieve this repository’s list of subscribers.
- subscription_url
The URL to modify subscription to this repository.
- tags_url
The URL to retrieve this repository’s list of tags.
- teams_url
The URL to retrieve this repository’s list of teams.
- trees_urlt
The
URITemplate
object representing the URI template returned by GitHub’s API. Checktrees_urlt.variables
for the list of variables that can be passed totrees_urlt.expand()
.
New in version 1.0.0.
- add_collaborator(username, permission=None)
Add
username
as a collaborator to a repository.- Parameters:
username (str or
User
) – (required), username of the userpermission (str) – (optional), permission to grant the collaborator, valid on organization repositories only. Can be ‘pull’, ‘triage’, ‘push’, ‘maintain’, ‘admin’ or an organization-defined custom role name.
- Returns:
True if successful, False otherwise
- Return type:
- archive(format, path='', ref='master')
Get the tarball or zipball archive for this repo at ref.
See: http://developer.github.com/v3/repos/contents/#get-archive-link
- Parameters:
format (str) – (required), accepted values: (‘tarball’, ‘zipball’)
path (str, file) – (optional), path where the file should be saved to, default is the filename provided in the headers and will be written in the current directory. it can take a file-like object as well
ref (str) – (optional)
- Returns:
True if successful, False otherwise
- Return type:
bool
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- asset(id)
Return a single asset.
- Parameters:
id (int) – (required), id of the asset
- Returns:
the asset
- Return type:
- assignees(number=-1, etag=None)
Iterate over all assignees to which an issue may be assigned.
- Parameters:
number (int) – (optional), number of assignees to return. Default: -1 returns all available assignees
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users
- Return type:
- auto_trigger_checks(app_id, enabled=True)
Change preferences for automatic creation of check suites.
New in version 1.3.0.
Enable/disable the automatic flow when creating check suites. By default, the check suite is automatically created each time code is pushed. When the automatic creation is disable they can be created manually.
- Parameters:
app_id (int) – (required), the id of the GitHub App
enabled (bool) – (optional), enable automatic creation of check suites Default: True
- Returns:
the check suite settings for this repository
- Return type:
dict
- blob(sha)
Get the blob indicated by
sha
.- Parameters:
sha (str) – (required), sha of the blob
- Returns:
the git blob
- Return type:
- branch(name)
Get the branch
name
of this repository.- Parameters:
name (str) – (required), branch name
- Returns:
the branch
- Return type:
- branches(number=-1, protected=False, etag=None)
Iterate over the branches in this repository.
- Parameters:
number (int) – (optional), number of branches to return. Default: -1 returns all branches
protected (bool) – (optional), True lists only protected branches. Default: False
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of branches
- Return type:
- check_run(id)
Return a single check run.
New in version 1.3.0.
- Parameters:
id (int) – (required), id of the check run
- Returns:
the check run
- Return type:
CheckRun
- check_suite(id)
Return a single check suite.
New in version 1.3.0.
- Parameters:
id (int) – (required), id of the check suite
- Returns:
the check suite
- Return type:
CheckSuite
- clones(per='day')
Get the total number of repository clones and breakdown per day or week for the last 14 days.
New in version 1.4.0.
See also: https://developer.github.com/v3/repos/traffic/
- Parameters:
per (str) – (optional), (‘day’, ‘week’), clones reporting period. Default ‘day’ will return clones per day for the last 14 days.
- Returns:
clones data
- Return type:
ClonesStats
- Raises:
ValueError if per is not a valid choice
- code_frequency(number=-1, etag=None)
Iterate over the code frequency per week.
New in version 0.7.
Returns a weekly aggregate of the number of additions and deletions pushed to this repository.
Note
All statistics methods may return a 202. On those occasions, you will not receive any objects. You should store your iterator and check the new
last_status
attribute. If it is a 202 you should wait before re-requesting.- Parameters:
number (int) – (optional), number of weeks to return. Default: -1 returns all weeks
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of lists
[seconds_from_epoch, additions, deletions]
- Return type:
list
- collaborators(affiliation='all', number=-1, etag=None)
Iterate over the collaborators of this repository.
- Parameters:
affiliation (str) – (optional), affiliation of the collaborator to the repository. Default: “all” returns contributors with all affiliations
number (int) – (optional), number of collaborators to return. Default: -1 returns all comments
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of collaborators
- Return type:
- comments(number=-1, etag=None)
Iterate over comments on all commits in the repository.
- Parameters:
number (int) – (optional), number of comments to return. Default: -1 returns all comments
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of comments on commits
- Return type:
- commit(sha)
Get a single (repo) commit.
See
git_commit()
for the Git Data Commit.- Parameters:
sha (str) – (required), sha of the commit
- Returns:
the commit
- Return type:
- commit_activity(number=-1, etag=None)
Iterate over last year of commit activity by week.
New in version 0.7.
See: http://developer.github.com/v3/repos/statistics/
Note
All statistics methods may return a 202. On those occasions, you will not receive any objects. You should store your iterator and check the new
last_status
attribute. If it is a 202 you should wait before re-requesting.- Parameters:
number (int) – (optional), number of weeks to return. Default -1 will return all of the weeks.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of dictionaries
- Return type:
dict
- commit_comment(comment_id)
Get a single commit comment.
- Parameters:
comment_id (int) – (required), id of the comment used by GitHub
- Returns:
the comment on the commit
- Return type:
- commits(sha=None, path=None, author=None, number=-1, etag=None, since=None, until=None, per_page=None)
Iterate over commits in this repository.
- Parameters:
sha (str) – (optional), sha or branch to start listing commits from
path (str) – (optional), commits containing this path will be listed
author (str) – (optional), GitHub login, real name, or email to filter commits by (using commit author)
number (int) – (optional), number of commits to return. Default: -1 returns all commits
etag (str) – (optional), ETag from a previous request to the same endpoint
since (
datetime
or str) – (optional), Only commits after this date will be returned. This can be adatetime
or anISO8601
formatted date string.until (
datetime
or str) – (optional), Only commits before this date will be returned. This can be adatetime
or anISO8601
formatted date string.per_page (int) – (optional), commits listing page size
- Returns:
generator of commits
- Return type:
- compare_commits(base, head)
Compare two commits.
- Parameters:
base (str) – (required), base for the comparison
head (str) – (required), compare this against base
- Returns:
the comparison of the commits
- Return type:
- contributor_statistics(number=-1, etag=None)
Iterate over the contributors list.
New in version 0.7.
See also: http://developer.github.com/v3/repos/statistics/
Note
All statistics methods may return a 202. On those occasions, you will not receive any objects. You should store your iterator and check the new
last_status
attribute. If it is a 202 you should wait before re-requesting.- Parameters:
number (int) – (optional), number of weeks to return. Default -1 will return all of the weeks.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of contributor statistics for each contributor
- Return type:
- contributors(anon=False, number=-1, etag=None)
Iterate over the contributors to this repository.
- Parameters:
anon (bool) – (optional), True lists anonymous contributors as well
number (int) – (optional), number of contributors to return. Default: -1 returns all contributors
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of contributor users
- Return type:
- create_blob(content, encoding)
Create a blob with
content
.- Parameters:
content (str) – (required), content of the blob
encoding (str) – (required), (‘base64’, ‘utf-8’)
- Returns:
string of the SHA returned
- Returns:
str
- create_branch_ref(name, sha=None)
Create a branch git reference.
This is a shortcut for calling
github3.repos.repo.Repository.create_ref()
.- Parameters:
branch (str) – (required), the branch to create
sha (str) – the commit to base the branch from
- Returns:
a reference object representing the branch
- Return type:
- create_check_run(name, head_sha, details_url=None, external_id=None, started_at=None, status=None, conclusion=None, completed_at=None, output=None, actions=None)
Create a check run object on a commit
New in version 1.3.0.
- Parameters:
name (str) – (required), The name of the check
head_sha (str) – (required), The SHA of the commit
details_url (str) – (optional), The URL of the integrator’s site that has the full details of the check
external_id (str) – (optional), A reference for the run on the integrator’s system
started_at (str) – (optional), ISO 8601 time format: YYYY-MM-DDTHH:MM:SSZ
status (str) – (optional), (‘queued’, ‘in_progress’, ‘completed’)
conclusion (str) – (optional), Required if you provide ‘completed_at’, or a ‘status’ of ‘completed’. The final conclusion of the check. (‘success’, ‘failure’, ‘neutral’, ‘cancelled’, ‘timed_out’, ‘action_required’)
completed_at (str) – (optional), Required if you provide ‘conclusion’. ISO 8601 time format: YYYY-MM-DDTHH:MM:SSZ
output (dict) – (optional), key-value pairs representing the output. Format:
{'title': 'string', 'summary': 'text, can be markdown', 'text': 'text, can be markdown', 'annotations': [{}], 'images': [{}]}
actions (list) – (optional), list of action objects. Format is:
[{'label': 'text', 'description', 'text', 'identifier', 'text'}, ...]
- Returns:
the created check run
- Return type:
CheckRun
- create_check_suite(head_sha)
Create a check suite object on a commit
New in version 1.3.0.
- Parameters:
head_sha (str) – The sha of the head commit.
- Returns:
the created check suite
- Return type:
CheckSuite
- create_comment(body, sha, path=None, position=None, line=1)
Create a comment on a commit.
- Parameters:
body (str) – (required), body of the message
sha (str) – (required), commit id
path (str) – (optional), relative path of the file to comment on
position (str) – (optional), line index in the diff to comment on
line (int) – (optional), line number of the file to comment on, default: 1
- Returns:
the created comment
- Return type:
- create_commit(message, tree, parents, author=None, committer=None)
Create a commit on this repository.
- Parameters:
message (str) – (required), commit message
tree (str) – (required), SHA of the tree object this commit points to
parents (list) – (required), SHAs of the commits that were parents of this commit. If empty, the commit will be written as the root commit. Even if there is only one parent, this should be an array.
author (dict) – (optional), if omitted, GitHub will use the authenticated user’s credentials and the current time. Format: {‘name’: ‘Committer Name’, ‘email’: ‘name@example.com’, ‘date’: ‘YYYY-MM-DDTHH:MM:SS+HH:00’}
committer (dict) – (optional), if ommitted, GitHub will use the author parameters. Should be the same format as the author parameter.
- Returns:
the created commit
- Return type:
- create_deployment(ref, required_contexts=None, payload='', auto_merge=False, description='', environment=None)
Create a deployment.
- Parameters:
ref (str) – (required), The ref to deploy. This can be a branch, tag, or sha.
required_contexts (list) – Optional array of status contexts verified against commit status checks. To bypass checking entirely pass an empty array. Default: []
payload (str) – Optional JSON payload with extra information about the deployment. Default: “”
auto_merge (bool) – Optional parameter to merge the default branch into the requested deployment branch if necessary. Default: False
description (str) – Optional short description. Default: “”
environment (str) – Optional name for the target deployment environment (e.g., production, staging, qa). Default: “production”
- Returns:
the created deployment
- Return type:
- create_file(path, message, content, branch=None, committer=None, author=None)
Create a file in this repository.
See also: http://developer.github.com/v3/repos/contents/#create-a-file
- Parameters:
path (str) – (required), path of the file in the repository
message (str) – (required), commit message
content (bytes) – (required), the actual data in the file
branch (str) – (optional), branch to create the commit on. Defaults to the default branch of the repository
committer (dict) – (optional), if no information is given the authenticated user’s information will be used. You must specify both a name and email.
author (dict) – (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
- Returns:
dictionary of contents and commit for created file
- Return type:
- create_fork(organization=None)
Create a fork of this repository.
- Parameters:
organization (str) – (required), login for organization to create the fork under
- Returns:
the fork of this repository
- Return type:
- create_hook(name, config, events=['push'], active=True)
Create a hook on this repository.
- Parameters:
name (str) – (required), name of the hook
config (dict) – (required), key-value pairs which act as settings for this hook
events (list) – (optional), events the hook is triggered for
active (bool) – (optional), whether the hook is actually triggered
- Returns:
the created hook
- Return type:
- create_issue(title, body=None, assignee=None, milestone=None, labels=None, assignees=None)
Create an issue on this repository.
- Parameters:
title (str) – (required), title of the issue
body (str) – (optional), body of the issue
assignee (str) – (optional), login of the user to assign the issue to
milestone (int) – (optional), id number of the milestone to attribute this issue to (e.g.
m
is aMilestone
object,m.number
is what you pass here.)labels ([str]) – (optional), labels to apply to this issue
assignees ([str]) – (optional), login of the users to assign the issue to
- Returns:
the created issue
- Return type:
- create_key(title, key, read_only=False)
Create a deploy key.
- Parameters:
title (str) – (required), title of key
key (str) – (required), key text
read_only (bool) – (optional), restrict key access to read-only, default is False
- Returns:
the created key
- Return type:
- create_label(name, color, description=None)
Create a label for this repository.
- Parameters:
name (str) – (required), name to give to the label
color (str) – (required), value of the color to assign to the label, e.g., ‘#fafafa’ or ‘fafafa’ (the latter is what is sent)
description (str) – (optional), description to give to the label
- Returns:
the created label
- Return type:
- create_milestone(title, state=None, description=None, due_on=None)
Create a milestone for this repository.
- Parameters:
title (str) – (required), title of the milestone
state (str) – (optional), state of the milestone, accepted values: (‘open’, ‘closed’), default: ‘open’
description (str) – (optional), description of the milestone
due_on (str) – (optional), ISO 8601 formatted due date
- Returns:
the created milestone
- Return type:
- create_project(name, body=None)
Create a project for this repository.
- Parameters:
name (str) – (required), name of the project
body (str) – (optional), body of the project
- Returns:
the created project
- Return type:
- create_pull(title, base, head, body=None, maintainer_can_modify=None)
Create a pull request of
head
ontobase
branch in this repo.- Parameters:
title (str) – (required)
base (str) – (required), e.g., ‘master’
head (str) – (required), e.g., ‘username:branch’
body (str) – (optional), markdown formatted description
maintainer_can_modify (bool) – (optional), Indicates whether a maintainer is allowed to modify the pull request or not.
- Returns:
the created pull request
- Return type:
- create_pull_from_issue(issue, base, head)
Create a pull request from issue #``issue``.
- Parameters:
issue (int) – (required), issue number
base (str) – (required), e.g., ‘master’
head (str) – (required), e.g., ‘username:branch’
- Returns:
the created pull request
- Return type:
- create_ref(ref, sha)
Create a reference in this repository.
- Parameters:
ref (str) – (required), fully qualified name of the reference, e.g.
refs/heads/master
. If it doesn’t start withrefs
and contain at least two slashes, GitHub’s API will reject it.sha (str) – (required), SHA1 value to set the reference to
- Returns:
the created ref
- Return type:
- create_release(tag_name, target_commitish=None, name=None, body=None, draft=False, prerelease=False)
Create a release for this repository.
- Parameters:
tag_name (str) – (required), name to give to the tag
target_commitish (str) – (optional), vague concept of a target, either a SHA or a branch name.
name (str) – (optional), name of the release
body (str) – (optional), description of the release
draft (bool) – (optional), whether this release is a draft or not
prerelease (bool) – (optional), whether this is a prerelease or not
- Returns:
the created release
- Return type:
- create_status(sha, state, target_url=None, description=None, context='default')
Create a status object on a commit.
- Parameters:
sha (str) – (required), SHA of the commit to create the status on
state (str) – (required), state of the test; only the following are accepted: ‘pending’, ‘success’, ‘error’, ‘failure’
target_url (str) – (optional), URL to associate with this status.
description (str) – (optional), short description of the status
context (str) – (optional), A string label to differentiate this status from the status of other systems
- Returns:
the created status
- Return type:
- create_tag(tag, message, sha, obj_type, tagger, lightweight=False)
Create a tag in this repository.
By default, this method creates an annotated tag. If you wish to create a lightweight tag instead, pass
lightweight=True
.If you are creating an annotated tag, this method makes 2 calls to the API:
Creates the tag object
Creates the reference for the tag
This behaviour is required by the GitHub API.
- Parameters:
tag (str) – (required), name of the tag
message (str) – (required), tag message
sha (str) – (required), SHA of the git object this is tagging
obj_type (str) – (required), type of object being tagged, e.g., ‘commit’, ‘tree’, ‘blob’
tagger (dict) – (required), containing the name, email of the tagger and optionally the date it was tagged
lightweight (bool) – (optional), if False, create an annotated tag, otherwise create a lightweight tag (a Reference).
- Returns:
if creating a lightweight tag, this will return a
Reference
, otherwise it will return aTag
- Return type:
- create_tree(tree, base_tree=None)
Create a tree on this repository.
- Parameters:
tree (list) – (required), specifies the tree structure. Format: [{‘path’: ‘path/file’, ‘mode’: ‘filemode’, ‘type’: ‘blob or tree’, ‘sha’: ‘44bfc6d…’}]
base_tree (str) – (optional), SHA1 of the tree you want to update with new data
- Returns:
the created tree
- Return type:
- delete()
Delete this repository.
- Returns:
True if successful, False otherwise
- Return type:
bool
- delete_key(key_id)
Delete the key with the specified id from your deploy keys list.
- Returns:
True if successful, False otherwise
- Return type:
bool
- delete_subscription()
Delete the user’s subscription to this repository.
- Returns:
True if successful, False otherwise
- Return type:
bool
- deployment(id)
Retrieve the deployment identified by
id
.- Parameters:
id (int) – (required), id for deployments.
- Returns:
the deployment
- Return type:
- deployments(number=-1, etag=None)
Iterate over deployments for this repository.
- Parameters:
number (int) – (optional), number of deployments to return. Default: -1, returns all available deployments
etag (str) – (optional), ETag from a previous request for all deployments
- Returns:
generator of deployments
- Return type:
- directory_contents(directory_path, ref=None, return_as=<class 'list'>)
Get the contents of each file in
directory_path
.If the path provided is actually a directory, you will receive a list back of the form:
[('filename.md', Contents(...)), ('github.py', Contents(...)), # ... ('fiz.py', Contents(...))]
You can either then transform it into a dictionary:
contents = dict(repo.directory_contents('path/to/dir/'))
Or you can use the
return_as
parameter to have it return a dictionary for you:contents = repo.directory_contents('path/to/dir/', return_as=dict)
- Parameters:
path (str) – (required), path to file, e.g. github3/repos/repo.py
ref (str) – (optional), the string name of a commit/branch/tag. Default: master
return_as – (optional), how to return the directory’s contents. Default:
list
- Returns:
list of tuples of the filename and the Contents returned
- Return type:
[(str,
Contents
)]- Raises:
github3.exceptions.UnprocessableResponseBody – When the requested directory is not actually a directory
- edit(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, default_branch=None, archived=None, allow_merge_commit=None, allow_squash_merge=None, allow_rebase_merge=None, has_projects=None)
Edit this repository.
- Parameters:
name (str) – (required), name of the repository
description (str) – (optional), If not
None
, change the description for this repository. API default:None
- leave value unchanged.homepage (str) – (optional), If not
None
, change the homepage for this repository. API default:None
- leave value unchanged.private (bool) – (optional), If
True
, make the repository private. IfFalse
, make the repository public. API default:None
- leave value unchanged.has_issues (bool) – (optional), If
True
, enable issues for this repository. IfFalse
, disable issues for this repository. API default:None
- leave value unchanged.has_wiki (bool) – (optional), If
True
, enable the wiki for this repository. IfFalse
, disable the wiki for this repository. API default:None
- leave value unchanged.has_downloads (bool) – (optional), If
True
, enable downloads for this repository. IfFalse
, disable downloads for this repository. API default:None
- leave value unchanged.default_branch (str) – (optional), If not
None
, change the default branch for this repository. API default:None
- leave value unchanged.archived (bool) – (optional), If not
None
, toggle the archived attribute on the repository to control whether it is archived or not.allow_rebase_merge (bool) – (optional), If not
None
, change whether the merge strategy that allows adding all commits from the head branch onto the base branch individually is enabled for this repository. API default:None
- leave value unchanged.allow_squash_merge (bool) – (optional), If not
None
, change whether combining all commits from the head branch into a single commit in the base branch is allowed. API default:None
- leave value unchanged.allow_merge_commit (bool) – (optional), If not
None
, change whether adding all commits from the head branch to the base branch with a merge commit is allowed. API default:None
- leave value unchanged.has_projects (bool) – (optional), If
True
, enable projects for this repository. IfFalse
, disable projects projects for this repository. API default:None
- leave value unchanged.
- Returns:
True if successful, False otherwise
- Return type:
bool
- events(number=-1, etag=None)
Iterate over events on this repository.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events
- Return type:
- file_contents(path, ref=None)
Get the contents of the file pointed to by
path
.- Parameters:
path (str) – (required), path to file, e.g. github3/repos/repo.py
ref (str) – (optional), the string name of a commit/branch/tag. Default: master
- Returns:
the contents of the file requested
- Return type:
- forks(sort='', number=-1, etag=None)
Iterate over forks of this repository.
- Parameters:
sort (str) – (optional), accepted values: (‘newest’, ‘oldest’, ‘stargazers’), API default: ‘newest’
number (int) – (optional), number of forks to return. Default: -1 returns all forks
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of forks of this repository
- Return type:
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- git_commit(sha)
Get a single (git) commit.
- Parameters:
sha (str) – (required), sha of the commit
- Returns:
the single commit data from git
- Return type:
- hook(hook_id)
Get a single hook.
- Parameters:
hook_id (int) – (required), id of the hook
- Returns:
the hook
- Return type:
- hooks(number=-1, etag=None)
Iterate over hooks registered on this repository.
- Parameters:
number (int) – (optional), number of hoks to return. Default: -1 returns all hooks
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of hooks
- Return type:
- ignore()
Ignore notifications from this repository for the user.
New in version 1.0.
This replaces
Repository#set_subscription
.- Returns:
the new repository subscription
- Return type:
:class:~github3.notifications.RepositorySubscription`
- import_issue(title, body, created_at, assignee=None, milestone=None, closed=None, labels=None, comments=None)
Import an issue into the repository.
See also: https://gist.github.com/jonmagic/5282384165e0f86ef105
- Parameters:
title (string) – (required) Title of issue
body (string) – (required) Body of issue
created_at (
datetime
or str) – (required) Creation timestampassignee (string) – (optional) Username to assign issue to
milestone (int) – (optional) Milestone ID
closed (boolean) – (optional) Status of issue is Closed if True
labels (list) – (optional) List of labels containing string names
comments (list) – (optional) List of dictionaries which contain created_at and body attributes
- Returns:
the imported issue
- Return type:
- imported_issue(imported_issue_id)
Retrieve imported issue specified by imported issue id.
- Parameters:
imported_issue_id (int) – (required) id of imported issue
- Returns:
the imported issue
- Return type:
- imported_issues(number=-1, since=None, etag=None)
Retrieve the collection of imported issues via the API.
See also: https://gist.github.com/jonmagic/5282384165e0f86ef105
- Parameters:
number (int) – (optional), number of imported issues to return. Default: -1 returns all branches
since – (optional), Only imported issues after this date will be returned. This can be a
datetime
instance, ISO8601 formatted date string, or a string formatted like so:2016-02-04
i.e.%Y-%m-%d
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of imported issues
- Return type:
- invitations(number=-1, etag=None)
Iterate over the invitations to this repository.
- Parameters:
number (int) – (optional), number of invitations to return. Default: -1 returns all available invitations
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of repository invitation objects
- Return type:
Invitation
- is_assignee(username)
Check if the user can be assigned an issue on this repository.
- Parameters:
username (str or
User
) – name of the user to check- Returns:
bool
- is_collaborator(username)
Check to see if
username
is a collaborator on this repository.- Parameters:
username (str or
User
) – (required), login for the user- Returns:
True if successful, False otherwise
- Return type:
bool
- issue(number)
Get the issue specified by
number
.- Parameters:
number (int) – (required), number of the issue on this repository
- Returns:
the issue
- Return type:
- issue_events(number=-1, etag=None)
Iterate over issue events on this repository.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events on issues
- Return type:
- issues(milestone=None, state=None, assignee=None, mentioned=None, labels=None, sort=None, direction=None, since=None, number=-1, etag=None)
Iterate over issues on this repo based upon parameters passed.
Changed in version 0.9.0: The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.- Parameters:
milestone (int) – (optional), ‘none’, or ‘*’
state (str) – (optional), accepted values: (‘all’, ‘open’, ‘closed’)
assignee (str) – (optional), ‘none’, ‘*’, or login name
mentioned (str) – (optional), user’s login name
labels (str) – (optional), comma-separated list of labels, e.g. ‘bug,ui,@high’
sort – (optional), accepted values: (‘created’, ‘updated’, ‘comments’, ‘created’)
direction (str) – (optional), accepted values: (‘asc’, ‘desc’)
since (
datetime
or str) – (optional), Only issues after this date will be returned. This can be adatetime
or anISO8601
formatted date string, e.g., 2012-05-20T23:10:27Znumber (int) – (optional), Number of issues to return. By default all issues are returned
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of issues
- Return type:
ShortIssue
- key(id_num)
Get the specified deploy key.
- Parameters:
id_num (int) – (required), id of the key
- Returns:
the deploy key
- Return type:
- keys(number=-1, etag=None)
Iterate over deploy keys on this repository.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of keys
- Return type:
- label(name)
Get the label specified by
name
.- Parameters:
name (str) – (required), name of the label
- Returns:
the label
- Return type:
- labels(number=-1, etag=None)
Iterate over labels on this repository.
- Parameters:
number (int) – (optional), number of labels to return. Default: -1 returns all available labels
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of labels
- Return type:
- languages(number=-1, etag=None)
Iterate over the programming languages used in the repository.
- Parameters:
number (int) – (optional), number of languages to return. Default: -1 returns all used languages
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of tuples
- Return type:
tuple
- latest_pages_build()
Get the build information for the most recent Pages build.
- Returns:
the information for the most recent build
- Return type:
- latest_release()
Get the latest release.
Draft releases and prereleases are not returned by this endpoint.
- Returns:
the release
- Return type:
- license()
Get the contents of a license for the repo.
- Returns:
the license
- Return type:
RepositoryLicense
- mark_notifications(last_read='')
Mark all notifications in this repository as read.
- Parameters:
last_read (str) – (optional), Describes the last point that notifications were checked. Anything updated since this time will not be updated. Default: Now. Expected in ISO 8601 format:
YYYY-MM-DDTHH:MM:SSZ
. Example: “2012-10-09T23:39:01Z”.- Returns:
True if successful, False otherwise
- Return type:
bool
- merge(base, head, message='')
Perform a merge from
head
intobase
.- Parameters:
base (str) – (required), where you’re merging into
head (str) – (required), where you’re merging from
message (str) – (optional), message to be used for the commit
- Returns:
the commit resulting from the merge
- Return type:
- milestone(number)
Get the milestone indicated by
number
.- Parameters:
number (int) – (required), unique id number of the milestone
- Returns:
the milestone
- Return type:
- milestones(state=None, sort=None, direction=None, number=-1, etag=None)
Iterate over the milestones on this repository.
- Parameters:
state (str) – (optional), state of the milestones, accepted values: (‘open’, ‘closed’)
sort (str) – (optional), how to sort the milestones, accepted values: (‘due_date’, ‘completeness’)
direction (str) – (optional), direction to sort the milestones, accepted values: (‘asc’, ‘desc’)
number (int) – (optional), number of milestones to return. Default: -1 returns all milestones
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of milestones
- Return type:
- network_events(number=-1, etag=None)
Iterate over events on a network of repositories.
- Parameters:
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of events
- Return type:
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- notifications(all=False, participating=False, since=None, number=-1, etag=None)
Iterate over the notifications for this repository.
- Parameters:
all (bool) – (optional), show all notifications, including ones marked as read
participating (bool) – (optional), show only the notifications the user is participating in directly
since (
datetime
or str) – (optional), filters out any notifications updated before the given time. This can be a datetime or an ISO8601 formatted date string, e.g., 2012-05-20T23:10:27Zetag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of notification threads
- Return type:
- pages()
Get information about this repository’s pages site.
- Returns:
information about this repository’s GitHub pages site
- Return type:
- pages_builds(number=-1, etag=None)
Iterate over pages builds of this repository.
- Parameters:
number (int) – (optional) the number of builds to return
etag (str) – (optional), ETag value from a previous request
- Returns:
generator of builds
- Return type:
- project(id, etag=None)
Return the organization project with the given ID.
- Parameters:
id (int) – (required), ID number of the project
- Returns:
the project
- Return type:
- projects(number=-1, etag=None)
Iterate over projects for this organization.
- Parameters:
number (int) – (optional), number of members to return. Default: -1 will return all available.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of projects
- Return type:
- pull_request(number)
Get the pull request indicated by
number
.- Parameters:
number (int) – (required), number of the pull request.
- Returns:
the pull request
- Return type:
- pull_requests(state=None, head=None, base=None, sort='created', direction='desc', number=-1, etag=None)
List pull requests on repository.
Changed in version 0.9.0:
The
state
parameter now accepts ‘all’ in addition to ‘open’ and ‘closed’.The
sort
parameter was added.The
direction
parameter was added.
- Parameters:
state (str) – (optional), accepted values: (‘all’, ‘open’, ‘closed’)
head (str) – (optional), filters pulls by head user and branch name in the format
user:ref-name
, e.g.,seveas:debian
base (str) – (optional), filter pulls by base branch name. Example:
develop
.sort (str) – (optional), Sort pull requests by
created
,updated
,popularity
,long-running
. Default: ‘created’direction (str) – (optional), Choose the direction to list pull requests. Accepted values: (‘desc’, ‘asc’). Default: ‘desc’
number (int) – (optional), number of pulls to return. Default: -1 returns all available pull requests
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of pull requests
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- readme()
Get the README for this repository.
- Returns:
this repository’s readme
- Return type:
- ref(ref)
Get a reference pointed to by
ref
.The most common will be branches and tags. For a branch, you must specify ‘heads/branchname’ and for a tag, ‘tags/tagname’. Essentially, the system should return any reference you provide it in the namespace, including notes and stashes (provided they exist on the server).
- Parameters:
ref (str) – (required)
- Returns:
the reference
- Return type:
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- refs(subspace='', number=-1, etag=None)
Iterate over references for this repository.
- Parameters:
subspace (str) – (optional), e.g. ‘tags’, ‘stashes’, ‘notes’
number (int) – (optional), number of refs to return. Default: -1 returns all available refs
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of references
- Return type:
- release(id)
Get a single release.
- Parameters:
id (int) – (required), id of release
- Returns:
the release
- Return type:
- release_from_tag(tag_name)
Get a release by tag name.
release_from_tag() returns a release with specified tag while release() returns a release with specified release id
- Parameters:
tag_name (str) – (required) name of tag
- Returns:
the release
- Return type:
- releases(number=-1, etag=None)
Iterate over releases for this repository.
- Parameters:
number (int) – (optional), number of refs to return. Default: -1 returns all available refs
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of releases
- Return type:
- remove_collaborator(username)
Remove collaborator
username
from the repository.- Parameters:
username (str or
User
) – (required), login name of the collaborator- Returns:
True if successful, False otherwise
- Return type:
bool
- replace_topics(new_topics)
Replace the repository topics with
new_topics
.- Parameters:
topics (list) – (required), new topics of the repository
- Returns:
new topics of the repository
- Return type:
Topics
- stargazers(number=-1, etag=None)
List users who have starred this repository.
- Parameters:
number (int) – (optional), number of stargazers to return. Default: -1 returns all subscribers available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users
- Return type:
- statuses(sha, number=-1, etag=None)
Iterate over the statuses for a specific SHA.
Warning
Deprecated in v1.0. Also deprecated upstream https://developer.github.com/v3/repos/statuses/
- Parameters:
sha (str) – SHA of the commit to list the statuses of
number (int) – (optional), return up to number statuses. Default: -1 returns all available statuses.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of statuses
- Return type:
- subscribe()
Subscribe the user to this repository’s notifications.
New in version 1.0.
This replaces
Repository#set_subscription
- Returns:
the new repository subscription
- Return type:
- subscribers(number=-1, etag=None)
Iterate over users subscribed to this repository.
- Parameters:
number (int) – (optional), number of subscribers to return. Default: -1 returns all subscribers available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of users subscribed to this repository
- Return type:
- subscription()
Return subscription for this Repository.
- Returns:
the user’s subscription to this repository
- Return type:
- tag(sha)
Get an annotated tag.
http://learn.github.com/p/tagging.html
- Parameters:
sha (str) – (required), sha of the object for this tag
- Returns:
the annotated tag
- Return type:
- tags(number=-1, etag=None)
Iterate over tags on this repository.
- Parameters:
number (int) – (optional), return up to at most number tags. Default: -1 returns all available tags.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of tags with GitHub repository specific information
- Return type:
- teams(number=-1, etag=None)
Iterate over teams with access to this repository.
- Parameters:
number (int) – (optional), return up to number Teams. Default: -1 returns all Teams.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of teams
- Return type:
- topics()
Get the topics of this repository.
- Returns:
this repository’s topics
- Return type:
Topics
- tree(sha, recursive=False)
Get a tree.
- Parameters:
sha (str) – (required), sha of the object for this tree
recursive (bool) – (optional), whether to fetch the tree recursively
- Returns:
the tree
- Return type:
- unignore()
Unignore notifications from this repository for the user.
New in version 1.3.
This replaces
Repository#set_subscription
.- Returns:
the new repository subscription
- Return type:
:class:~github3.notifications.RepositorySubscription`
- unsubscribe()
Unsubscribe the user to this repository’s notifications.
New in version 1.3.
This replaces
Repository#set_subscription
- Returns:
the new repository subscription
- Return type:
- views(per='day')
Get the total number of repository views and breakdown per day or week for the last 14 days.
New in version 1.4.0.
See also: https://developer.github.com/v3/repos/traffic/
- Parameters:
per (str) – (optional), (‘day’, ‘week’), views reporting period. Default ‘day’ will return views per day for the last 14 days.
- Returns:
views data
- Return type:
ViewsStats
- Raises:
ValueError if per is not a valid choice
- weekly_commit_count()
Retrieve the total commit counts.
Note
All statistics methods may return a 202. If github3.py receives a 202 in this case, it will return an emtpy dictionary. You should give the API a moment to compose the data and then re -request it via this method.
..versionadded:: 0.7
The dictionary returned has two entries:
all
andowner
. Each has a fifty-two element long list of commit counts. (Note:all
includes the owner.)d['all'][0]
will be the oldest week,d['all'][51]
will be the most recent.- Returns:
the commit count as a dictionary
- Return type:
dict
- class github3.repos.repo.StarredRepository(json, session: GitHubSession)
This object represents the data returned about a user’s starred repos.
GitHub used to send back the
starred_at
attribute on Repositories but then changed the structure to a new object that separates that from the Repository representation. This consolidates the two.Attributes:
- starred_at
A parsed
datetime
object representing the date a the repository was starred.
- repository
The
Repository
that was starred by the user.
See also: https://developer.github.com/v3/activity/starring/#list-repositories-being-starred
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- class github3.repos.contents.Contents(json, session: GitHubSession)
A representation of file contents returned via the API.
See also: http://developer.github.com/v3/repos/contents/
This object has the following attributes:
- content
The body of the file. If this is present, it may be base64 encoded.
- encoding
The encoding used on the
content
when returning the data from the API, e.g.,base64
. Ifcontent
is not present this will not be present either.
- decoded
Note
This is a computed attribute which isn’t returned by the API.
Changed in version 0.5.2.
Decoded content of the file as a bytes object. If we try to decode to character set for you, we might encounter an exception which will prevent the object from being created. On python2 this is the same as a string, but on python3 you should call the decode method with the character set you wish to use, e.g.,
content.decoded.decode('utf-8')
.
- git_url
The URL for the Git API pertaining to this file.
- html_url
The URL to open this file in a browser.
- links
A dictionary of links returned about the contents and related resources.
- name
The name of the file.
- path
The path to this file.
- sha
The SHA1 of the contents of this file.
- size
The size of file in bytes.
- submodule_git_url
The URL of the git submodule (if this is a git submodule).
- target
If the file is a symlink, this will be present and provides the type of file that the symlink points to.
- type
Type of content, e.g.,
'file'
,'symlink'
, or'submodule'
.
- delete(message, branch=None, committer=None, author=None)
Delete this file.
- Parameters:
message (str) – (required), commit message to describe the removal
branch (str) – (optional), branch where the file exists. Defaults to the default branch of the repository.
committer (dict) – (optional), if no information is given the authenticated user’s information will be used. You must specify both a name and email.
author (dict) – (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
- Returns:
dictionary of new content and associated commit
- Return type:
- update(message, content, branch=None, committer=None, author=None)
Update this file.
- Parameters:
message (str) – (required), commit message to describe the update
content (str) – (required), content to update the file with
branch (str) – (optional), branch where the file exists. Defaults to the default branch of the repository.
committer (dict) – (optional), if no information is given the authenticated user’s information will be used. You must specify both a name and email.
author (dict) – (optional), if omitted this will be filled in with committer information. If passed, you must specify both a name and email.
- Returns:
dictionary containing the updated contents object and the commit in which it was changed.
- Return type:
- class github3.repos.hook.Hook(json, session: GitHubSession)
The representation of a hook on a repository.
See also: http://developer.github.com/v3/repos/hooks/
This object has the following attributes:
- active
A boolean attribute describing whether the hook is active or not.
- config
A dictionary containing the configuration for this hook.
- created_at
A
datetime
object representing the date and time when this hook was created.
- events
The list of events which trigger this hook.
- id
The unique identifier for this hook.
- name
The name provided to this hook.
- updated_at
A
datetime
object representing the date and time when this hook was updated.
- delete()
Delete this hook.
- Returns:
True if successful, False otherwise
- Return type:
bool
- edit(config={}, events=[], add_events=[], rm_events=[], active=True)
Edit this hook.
- Parameters:
config (dict) – (optional), key-value pairs of settings for this hook
events (list) – (optional), which events should this be triggered for
add_events (list) – (optional), events to be added to the list of events that this hook triggers for
rm_events (list) – (optional), events to be removed from the list of events that this hook triggers for
active (bool) – (optional), should this event be active
- Returns:
True if successful, False otherwise
- Return type:
bool
- ping()
Ping this hook.
- Returns:
True if successful, False otherwise
- Return type:
bool
- test()
Test this hook.
- Returns:
True if successful, False otherwise
- Return type:
bool
- class github3.repos.issue_import.ImportedIssue(json, session: GitHubSession)
Represents an issue imported via the unofficial API.
See also: https://gist.github.com/jonmagic/5282384165e0f86ef105
This object has the following attributes:
- created_at
A
datetime
object representing the date and time when this imported issue was created.
- id
The globally unique identifier for this imported issue.
- import_issues_url
The URL used to import more issues via the API.
- repository_url
The URL used to retrieve the repository via the API.
- status
The status of this imported issue.
- updated_at
A
datetime
object representing te date and time when this imported issue was last updated.
Release Objects
- class github3.repos.release.Asset(json, session: GitHubSession)
Representation of an asset in a release.
See also
- List Assets,
assets()
Documentation around listing assets of a release
- Upload Assets,
upload_asset()
Documentation around uploading assets to a release
- Get a Single Asset,
asset()
Documentation around retrieving an asset
- Edit an Asset,
edit()
Documentation around editing an asset
- Delete an Asset,
delete()
Documentation around deleting an asset
This object has the following attributes:
- browser_download_url
The user-friendly URL to download this asset via a browser.
- content_type
The Content-Type provided by the uploader when this asset was created.
- created_at
A
datetime
object representing the date and time when this asset was created.
- download_count
The number of times this asset has been downloaded.
- download_url
The URL to retrieve this uploaded asset via the API, e.g., tarball, zipball, etc.
- id
The unique identifier of this asset.
- label
The short description of this asset.
- name
The name provided to this asset.
- size
The file size of this asset.
- state
The state of this asset, e.g.,
'uploaded'
.
- updated_at
A
datetime
object representing the date and time when this asset was most recently updated.
- delete()
Delete this asset if the user has push access.
- Returns:
True if successful; False if not successful
- Return type:
bool
- download(path='')
Download the data for this asset.
- Parameters:
path (str, file) – (optional), path where the file should be saved to, default is the filename provided in the headers and will be written in the current directory. It can take a file-like object as well
- Returns:
name of the file, if successful otherwise
None
- Return type:
str
- edit(name, label=None)
Edit this asset.
- Parameters:
name (str) – (required), The file name of the asset
label (str) – (optional), An alternate description of the asset
- Returns:
True if successful, False otherwise
- Return type:
bool
- List Assets,
- class github3.repos.release.Release(json, session: GitHubSession)
Representation of a GitHub release.
It holds the information GitHub returns about a release from a
Repository
.Please see GitHub’s Releases Documentation for more information.
This object has the following attributes:
- assets_url
The URL to retrieve the assets from the API.
- body
The description of this release as written by the release creator.
- created_at
A
datetime
object representing the date and time when this release was created.
- draft
A boolean attribute describing whether this release is a draft.
- html_url
The URL to view this release in a browser.
- id
The unique identifier of this release.
- prerelease
A boolean attribute indicating whether the release is a pre-release.
- published_at
A
datetime
object representing the date and time when this release was publisehd.
- tag_name
The name of the tag associated with this release.
- tarball_url
The URL to retrieve a GitHub generated tarball for this release from the API.
- target_commitish
The reference (usually a commit) that is targetted by this release.
- upload_urlt
A
URITemplate
object that expands to form the URL to upload assets to.
- zipball_url
The URL to retrieve a GitHub generated zipball for this release from the API.
- archive(format, path='')
Get the tarball or zipball archive for this release.
- Parameters:
format (str) – (required), accepted values: (‘tarball’, ‘zipball’)
path (str, file) – (optional), path where the file should be saved to, default is the filename provided in the headers and will be written in the current directory. It can take a file-like object as well
- Returns:
True if successful, False otherwise
- Return type:
bool
- asset(asset_id)
Retrieve the asset from this release with
asset_id
.- Parameters:
asset_id (int) – ID of the Asset to retrieve
- Returns:
the specified asset, if it exists
- Return type:
- assets(number=-1, etag=None)
Iterate over the assets available for this release.
- Parameters:
number (int) – (optional), Number of assets to return
etag (str) – (optional), last ETag header sent
- Returns:
generator of asset objects
- Return type:
- delete()
Delete this release.
Only users with push access to the repository can delete a release.
- Returns:
True if successful; False if not successful
- Return type:
bool
- edit(tag_name=None, target_commitish=None, name=None, body=None, draft=None, prerelease=None)
Edit this release.
Only users with push access to the repository can edit a release.
If the edit is successful, this object will update itself.
- Parameters:
tag_name (str) – (optional), Name of the tag to use
target_commitish (str) – (optional), The “commitish” value that determines where the Git tag is created from. Defaults to the repository’s default branch.
name (str) – (optional), Name of the release
body (str) – (optional), Description of the release
draft (boolean) – (optional), True => Release is a draft
prerelease (boolean) – (optional), True => Release is a prerelease
- Returns:
True if successful; False if not successful
- Return type:
bool
- upload_asset(content_type, name, asset, label=None)
Upload an asset to this release.
Note
All parameters are required.
- Parameters:
content_type (str) – The content type of the asset. Wikipedia has a list of common media types
name (str) – The name of the file
asset – The file or bytes object to upload.
label – (optional), An alternate short description of the asset.
- Returns:
the created asset
- Return type:
Pages Objects
- class github3.repos.pages.PagesInfo(json, session: GitHubSession)
Representation of the information about a GitHub pages website.
- cname
The cname in use for the pages site, if one is set.
- custom_404
A boolean attribute indicating whether the user configured a custom 404 page for this site.
- status
The current status of the pages site, e.g.,
built
.
- class github3.repos.pages.PagesBuild(json, session: GitHubSession)
Representation of a single build of a GitHub pages website.
- commit
The SHA of the commit that triggered this build.
- created_at
A
datetime
object representing the date and time when this build was created.
- duration
The time it spent processing this build.
- error
If this build errored, a dictionary containing the error message and details about the error.
- status
The current statues of the build, e.g.,
building
.
- updated_at
A
datetime
object representing the date and time when this build was last updated.
Deployment and Status Objects
- class github3.repos.deployment.Deployment(json, session: GitHubSession)
Representation of a deployment of a repository at a point in time.
See also: https://developer.github.com/v3/repos/deployments/
This object has the following attributes:
- created_at
A
datetime
representing the date and time when this deployment was created.
- environment
The environment targeted for this deployment, e.g.,
'production'
,'staging'
.
- id
The unique identifier of this deployment.
- payload
The JSON payload string sent as part to trigger this deployment.
- ref
The reference used to create this deployment, e.g.,
'deploy-20140526'
.
- sha
The SHA1 of the branch on GitHub when it was deployed.
- statuses_url
The URL to retrieve the statuses of this deployment from the API.
- updated_at
A
datetime
object representing the date and time when this deployment was most recently updated.
- create_status(state, target_url=None, description=None)
Create a new deployment status for this deployment.
- Parameters:
state (str) – (required), The state of the status. Can be one of
pending
,success
,error
,inactive
,in_progress
,queued
, orfailure
.target_url (str) – The target URL to associate with this status. This URL should contain output to keep the user updated while the task is running or serve as historical information for what happened in the deployment. Default: ‘’.
description (str) – A short description of the status. Default: ‘’.
- Returns:
the incomplete deployment status
- Return type:
- statuses(number=-1, etag=None)
Iterate over the deployment statuses for this deployment.
- Parameters:
number (int) – (optional), the number of statuses to return. Default: -1, returns all statuses.
etag (str) – (optional), the ETag header value from the last time you iterated over the statuses.
- Returns:
generator of the statuses of this deployment
- Return type:
- class github3.repos.deployment.DeploymentStatus(json, session: GitHubSession)
Representation of the status of a deployment of a repository.
See also https://developer.github.com/v3/repos/deployments/#get-a-single-deployment-status
This object has the following attributes:
- created_at
A
datetime
representing the date and time when this deployment status was created.
- deployment_url
The URL to retrieve the information about the deployment from the API.
- id
The unique identifier of this deployment.
- state
The state of the deployment, e.g.,
'success'
.
- target_url
The URL to associate with this status. This should link to the output of the deployment.
- class github3.repos.status.ShortStatus(json, session: GitHubSession)
Representation of a short status on a repository.
New in version 1.0.0.
This is the representation found in a
CombinedStatus
object.See also: http://developer.github.com/v3/repos/statuses/
This object has the following attributes:
- context
This is a string that explains the context of this status object. For example,
'continuous-integration/travis-ci/pr'
.
- created_at
A
datetime
object representing the date and time when this status was created.
- description
A short description of the status.
- id
The unique identifier of this status object.
- state
The state of this status, e.g.,
'success'
,'pending'
,'failure'
.
- target_url
The URL to retrieve more information about this status.
- updated_at
A
datetime
object representing the date and time when this status was most recently updated.
- class github3.repos.status.CombinedStatus(json, session: GitHubSession)
A representation of the combined statuses in a repository.
See also: http://developer.github.com/v3/repos/statuses/
This object has the following attributes:
- commit_url
The URL of the commit this combined status is present on.
- repository
A
ShortRepository
representing the repository on which this combined status exists.
- sha
The SHA1 of the commit this status exists on.
- state
The state of the combined status, e.g.,
'success'
,'pending'
,'failure'
.
- statuses
The list of
ShortStatus
objects representing the individual statuses that is combined in this object.
- total_count
The total number of sub-statuses.
- class github3.repos.status.Status(json, session: GitHubSession)
Representation of a full status on a repository.
See also: http://developer.github.com/v3/repos/statuses/
This object has the same attributes as a
ShortStatus
as well as the following attributes:
Contributor Statistics Objects
- class github3.repos.stats.ContributorStats(json, session: GitHubSession)
Representation of a user’s contributor statistics to a repository.
See also http://developer.github.com/v3/repos/statistics/
This object has the following attributes:
- weeks
A list of dictionaries containing weekly statistical data.
- alternate_weeks
-
A list of dictionaries that provide an easier to remember set of keys as well as a
datetime
object representing the start of the week. The dictionary looks vaguely like:{ 'start of week': datetime(2013, 5, 5, 5, 0, tzinfo=tzutc()) 'additions': 100, 'deletions': 150, 'commits': 5, }
Search Results
These classes are meant to expose the entirety of an item returned as a search result by GitHub’s Search API.
- class github3.search.CodeSearchResult(json, session: GitHubSession)
A representation of a code search result from the API.
This object has the following attributes:
- git_url
The URL to retrieve the blob via Git
- html_url
The URL to view the blob found in a browser.
- name
The name of the file where the search result was found.
- path
The path in the repository to the file containing the result.
- repository
A
ShortRepository
representing the repository in which the result was found.
- score
The confidence score assigned to the result.
- sha
The SHA1 of the blob in which the code can be found.
- text_matches
A list of the text matches in the blob that generated this result.
Note
To receive these, you must pass
text_match=True
tosearch_code()
.
- class github3.search.IssueSearchResult(json, session: GitHubSession)
A representation of a search result containing an issue.
This object has the following attributes:
- issue
A
ShortIssue
representing the issue found in this search result.
- score
The confidence score of this search result.
- text_matches
A list of matches in the issue for this search result.
Note
To receive these, you must pass
text_match=True
tosearch_issues()
.
- class github3.search.RepositorySearchResult(json, session: GitHubSession)
A representation of a search result containing a repository.
This object has the following attributes:
.. attribute:: repository
A
ShortRepository
representing the repository found by the search.- score
The confidence score of this search result.
- text_matches
A list of the text matches in the repository that generated this result.
Note
To receive these, you must pass
text_match=True
tosearch_code()
.
- class github3.search.UserSearchResult(json, session: GitHubSession)
Representation of a search result for a user.
This object has the following attributes:
- score
The confidence score of this result.
- text_matches
If present, a list of text strings that match the search string.
Custom Iterator Structures
Many of the methods in github3.py that return iterators of another object are actually returning one of the iterators below. These iterators effectively allow users to ignore GitHub’s API pagination of large sets of data. In all senses, they behave like a normal Python iterator. Their difference is that they have extra logic around making API requests and coercing the JSON into predefined objects.
- class github3.structs.GitHubIterator(count: int, url: str, cls: Type[GitHubCore], session: session.GitHubSession, params: MutableMapping[str, str | int | None] | None = None, etag: str | None = None, headers: Mapping[str, str] | None = None, list_key: str | None = None)
The
GitHubIterator
class powers all of the iter_* methods.- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- cls: t.Type[models.GitHubCore]
Class for constructing an item to return
- count: int
Number of items left in the iterator
- etag: t.Optional[str]
The ETag Header value returned by GitHub
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- headers: t.Dict[str, str]
Headers generated for the GET request
- last_response: t.Optional['requests.models.Response']
The last response seen
- last_status: int
Last status code received
- last_url: t.Optional[str]
Last URL that was requested
- list_key: Final[t.Optional[str]]
Key to get the list of items in case a dict is returned
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- original: Final[int]
Original number of items requested
- params: t.MutableMapping[str, t.Optional[t.Union[str, int]]]
Parameters of the query string
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubIterator
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- url: str
URL the class used to make it’s first GET
- class github3.structs.SearchIterator(count: int, url: str, cls: Type[GitHubCore], session: session.GitHubSession, params: MutableMapping[str, str | int | None] | None = None, etag: str | None = None, headers: Mapping[str, str] | None = None)
This is a special-cased class for returning iterable search results.
It inherits from
GitHubIterator
. All members and methods documented here are unique to instances of this class. For other members and methods, check its parent class.- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- cls: t.Type[models.GitHubCore]
Class for constructing an item to return
- count: int
Number of items left in the iterator
- etag: t.Optional[str]
The ETag Header value returned by GitHub
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- headers: t.Dict[str, str]
Headers generated for the GET request
- items: t.List[t.Mapping[str, t.Any]]
Items array returned in the last request
- last_response: t.Optional['requests.models.Response']
The last response seen
- last_status: int
Last status code received
- last_url: t.Optional[str]
Last URL that was requested
- list_key: Final[t.Optional[str]]
Key to get the list of items in case a dict is returned
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- original: Final[int]
Original number of items requested
- params: t.MutableMapping[str, t.Optional[t.Union[str, int]]]
Parameters of the query string
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubIterator
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- total_count: int
Total count returned by GitHub
- url: str
URL the class used to make it’s first GET
Users and their Associated Objects
This section of the documentation covers the representations of various objects related to the Users API.
User Objects
- class github3.users.ShortUser(json, session: GitHubSession)
Object for the shortened representation of a User.
GitHub’s API returns different amounts of information about users based upon how that information is retrieved. Often times, when iterating over several users, GitHub will return less information. To provide a clear distinction between the types of users, github3.py uses different classes with different sets of attributes.
New in version 1.0.0.
- avatar_url
The URL of the avatar (possibly from Gravatar)
- events_urlt
A URITemplate object from
uritemplate
that can be used to generate an events URL
- followers_url
A string representing the resource to retrieve a User’s followers
- following_urlt
A URITemplate object from
uritemplate
that can be used to generate the URL to check if this user is followingother_user
- gists_urlt
A URITemplate object from
uritemplate
that can be used to generate the URL to retrieve a Gist by its id
- gravatar_id
The identifier for the user’s gravatar
- html_url
The URL of the user’s publicly visible profile. For example,
https://github.com/sigmavirus24
- id
The unique ID of the account
- login
The username of the user, e.g.,
sigmavirus24
- organizations_url
A string representing the resource to retrieve the organizations to which a user belongs
- received_events_url
A string representing the resource to retrieve the events a user received
- repos_url
A string representing the resource to list a user’s repositories
- site_admin
A boolean attribute indicating whether the user is a member of GitHub’s staff
- starred_urlt
A URITemplate object from
uritemplate
that can be used to generate a URL to retrieve whether the user has starred a repository.
- subscriptions_url
A string representing the resource to list a user’s subscriptions
- type
A string representing the type of User account this. In all cases should be “User”
- url
A string of this exact resource retrievable from GitHub’s API
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete the user.
Per GitHub API documentation, it is often preferable to suspend the user.
Note
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- demote()
Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- events(public=False, number=-1, etag=None)
Iterate over events performed by this user.
- Parameters:
public (bool) – (optional), only list public events for the authenticated user
number (int) – (optional), number of events to return. Default: -1 returns all available events.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- followers(number=-1, etag=None)
Iterate over the followers of this user.
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- following(number=-1, etag=None)
Iterate over the users being followed by this user.
- Parameters:
number (int) – (optional), number of users to return. Default: -1 returns all available users
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of this user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
GPGKey
s
- impersonate(scopes=None)
Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user. This is only available for admins of a GitHub Enterprise instance.
- Parameters:
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
- Returns:
Authorization
- is_assignee_on(username, repository)
Check if this user can be assigned to issues on username/repository.
- Parameters:
username (str) – owner’s username of the repository
repository (str) – name of the repository
- Returns:
True if the use can be assigned, False otherwise
- Return type:
bool
- is_following(username)
Check if this user is following
username
.- Parameters:
username (str) – (required)
- Returns:
bool
- keys(number=-1, etag=None)
Iterate over the public keys of this user.
New in version 0.5.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Key
s
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- organization_events(org, number=-1, etag=None)
Iterate over events from the user’s organization dashboard.
Note
You must be authenticated to view this.
- Parameters:
org (str) – (required), name of the organization
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- organizations(number=-1, etag=None)
Iterate over organizations the user is member of.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organization
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
ShortOrganization
s
- promote()
Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- received_events(public=False, number=-1, etag=None)
Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public events, otherwise you will only see public events.
- Parameters:
public (bool) – (optional), determines if the authenticated user sees both private and public or just public
number (int) – (optional), number of events to return. Default: -1 returns all events available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- rename(login)
Rename the user.
Note
This is only available for administrators of a GitHub Enterprise instance.
- Parameters:
login (str) – (required), new name of the user
- Returns:
bool
- revoke_impersonation()
Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- starred_repositories(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by this user.
Changed in version 0.5: Added sort and direction parameters (optional) as per the change in GitHub’s API.
- Parameters:
number (int) – (optional), number of starred repos to return. Default: -1, returns all available repos
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
StarredRepository
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by this user.
- Parameters:
number (int) – (optional), number of subscriptions to return. Default: -1, returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Repository
- suspend()
Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- unsuspend()
Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- class github3.users.Stargazer(json, session: GitHubSession)
Object representing a user that has starred a repository.
New in version 3.0.0.
This object contains all of the attributes available on
ShortUser
as well as the following:- starred_at
The time and date that the user starred the repository this was queried from.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete the user.
Per GitHub API documentation, it is often preferable to suspend the user.
Note
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- demote()
Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- events(public=False, number=-1, etag=None)
Iterate over events performed by this user.
- Parameters:
public (bool) – (optional), only list public events for the authenticated user
number (int) – (optional), number of events to return. Default: -1 returns all available events.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- followers(number=-1, etag=None)
Iterate over the followers of this user.
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- following(number=-1, etag=None)
Iterate over the users being followed by this user.
- Parameters:
number (int) – (optional), number of users to return. Default: -1 returns all available users
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of this user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
GPGKey
s
- impersonate(scopes=None)
Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user. This is only available for admins of a GitHub Enterprise instance.
- Parameters:
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
- Returns:
Authorization
- is_assignee_on(username, repository)
Check if this user can be assigned to issues on username/repository.
- Parameters:
username (str) – owner’s username of the repository
repository (str) – name of the repository
- Returns:
True if the use can be assigned, False otherwise
- Return type:
bool
- is_following(username)
Check if this user is following
username
.- Parameters:
username (str) – (required)
- Returns:
bool
- keys(number=-1, etag=None)
Iterate over the public keys of this user.
New in version 0.5.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Key
s
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- organization_events(org, number=-1, etag=None)
Iterate over events from the user’s organization dashboard.
Note
You must be authenticated to view this.
- Parameters:
org (str) – (required), name of the organization
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- organizations(number=-1, etag=None)
Iterate over organizations the user is member of.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organization
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
ShortOrganization
s
- promote()
Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- received_events(public=False, number=-1, etag=None)
Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public events, otherwise you will only see public events.
- Parameters:
public (bool) – (optional), determines if the authenticated user sees both private and public or just public
number (int) – (optional), number of events to return. Default: -1 returns all events available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- rename(login)
Rename the user.
Note
This is only available for administrators of a GitHub Enterprise instance.
- Parameters:
login (str) – (required), new name of the user
- Returns:
bool
- revoke_impersonation()
Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- starred_repositories(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by this user.
Changed in version 0.5: Added sort and direction parameters (optional) as per the change in GitHub’s API.
- Parameters:
number (int) – (optional), number of starred repos to return. Default: -1, returns all available repos
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
StarredRepository
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by this user.
- Parameters:
number (int) – (optional), number of subscriptions to return. Default: -1, returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Repository
- suspend()
Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- unsuspend()
Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- class github3.users.User(json, session: GitHubSession)
Object for the full representation of a User.
GitHub’s API returns different amounts of information about users based upon how that information is retrieved. This object exists to represent the full amount of information returned for a specific user. For example, you would receive this class when calling
user()
. To provide a clear distinction between the types of users, github3.py uses different classes with different sets of attributes.This object no longer contains information about the currently authenticated user (e.g.,
me()
).Changed in version 1.0.0.
This object contains all of the attributes available on
ShortUser
as well as the following:- bio
The markdown formatted User’s biography
- blog
The URL of the user’s blog
- company
The name or GitHub handle of the user’s company
- created_at
A parsed
datetime
object representing the date the user was created
- email
The email address the user has on their public profile page
- followers_count
The number of followers of this user
- following_count
The number of users this user follows
- hireable
Whether or not the user has opted into GitHub jobs advertising
- location
The location specified by the user on their public profile
- name
The name specified by their user on their public profile
- public_gists_count
The number of public gists owned by this user
- updated_at
A parsed
datetime
object representing the date the user was last updated
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete the user.
Per GitHub API documentation, it is often preferable to suspend the user.
Note
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- demote()
Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- events(public=False, number=-1, etag=None)
Iterate over events performed by this user.
- Parameters:
public (bool) – (optional), only list public events for the authenticated user
number (int) – (optional), number of events to return. Default: -1 returns all available events.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- followers(number=-1, etag=None)
Iterate over the followers of this user.
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- following(number=-1, etag=None)
Iterate over the users being followed by this user.
- Parameters:
number (int) – (optional), number of users to return. Default: -1 returns all available users
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of this user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
GPGKey
s
- impersonate(scopes=None)
Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user. This is only available for admins of a GitHub Enterprise instance.
- Parameters:
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
- Returns:
Authorization
- is_assignee_on(username, repository)
Check if this user can be assigned to issues on username/repository.
- Parameters:
username (str) – owner’s username of the repository
repository (str) – name of the repository
- Returns:
True if the use can be assigned, False otherwise
- Return type:
bool
- is_following(username)
Check if this user is following
username
.- Parameters:
username (str) – (required)
- Returns:
bool
- keys(number=-1, etag=None)
Iterate over the public keys of this user.
New in version 0.5.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Key
s
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- organization_events(org, number=-1, etag=None)
Iterate over events from the user’s organization dashboard.
Note
You must be authenticated to view this.
- Parameters:
org (str) – (required), name of the organization
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- organizations(number=-1, etag=None)
Iterate over organizations the user is member of.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organization
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
ShortOrganization
s
- promote()
Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- received_events(public=False, number=-1, etag=None)
Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public events, otherwise you will only see public events.
- Parameters:
public (bool) – (optional), determines if the authenticated user sees both private and public or just public
number (int) – (optional), number of events to return. Default: -1 returns all events available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- rename(login)
Rename the user.
Note
This is only available for administrators of a GitHub Enterprise instance.
- Parameters:
login (str) – (required), new name of the user
- Returns:
bool
- revoke_impersonation()
Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- starred_repositories(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by this user.
Changed in version 0.5: Added sort and direction parameters (optional) as per the change in GitHub’s API.
- Parameters:
number (int) – (optional), number of starred repos to return. Default: -1, returns all available repos
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
StarredRepository
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by this user.
- Parameters:
number (int) – (optional), number of subscriptions to return. Default: -1, returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Repository
- suspend()
Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- unsuspend()
Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- class github3.users.AuthenticatedUser(json, session: GitHubSession)
Object to represent the currently authenticated user.
This is returned by
me()
. It contains the extra informtation that is not returned for other users such as the currently authenticated user’s plan and private email information.New in version 1.0.0.
Changed in version 1.0.0: The
total_private_gists
attribute is no longer returned by GitHub’s API and so is removed.This object has all of the same attribute as the
ShortUser
andUser
objects as well as:- disk_usage
The amount of repository space that has been used by you, the user
- owned_private_repos_count
The number of private repositories owned by you, the user
- plan
Note
When used with a Github Enterprise instance <= 2.12.7, this attribute will not be returned. To handle these situations sensitively, the attribute will be set to
None
. Repositories may still have a license associated with them in these cases.The name of the plan that you, the user, have purchased
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete the user.
Per GitHub API documentation, it is often preferable to suspend the user.
Note
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- demote()
Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- events(public=False, number=-1, etag=None)
Iterate over events performed by this user.
- Parameters:
public (bool) – (optional), only list public events for the authenticated user
number (int) – (optional), number of events to return. Default: -1 returns all available events.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- followers(number=-1, etag=None)
Iterate over the followers of this user.
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- following(number=-1, etag=None)
Iterate over the users being followed by this user.
- Parameters:
number (int) – (optional), number of users to return. Default: -1 returns all available users
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of this user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
GPGKey
s
- impersonate(scopes=None)
Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user. This is only available for admins of a GitHub Enterprise instance.
- Parameters:
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
- Returns:
Authorization
- is_assignee_on(username, repository)
Check if this user can be assigned to issues on username/repository.
- Parameters:
username (str) – owner’s username of the repository
repository (str) – name of the repository
- Returns:
True if the use can be assigned, False otherwise
- Return type:
bool
- is_following(username)
Check if this user is following
username
.- Parameters:
username (str) – (required)
- Returns:
bool
- keys(number=-1, etag=None)
Iterate over the public keys of this user.
New in version 0.5.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Key
s
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- organization_events(org, number=-1, etag=None)
Iterate over events from the user’s organization dashboard.
Note
You must be authenticated to view this.
- Parameters:
org (str) – (required), name of the organization
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- organizations(number=-1, etag=None)
Iterate over organizations the user is member of.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organization
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
ShortOrganization
s
- promote()
Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- received_events(public=False, number=-1, etag=None)
Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public events, otherwise you will only see public events.
- Parameters:
public (bool) – (optional), determines if the authenticated user sees both private and public or just public
number (int) – (optional), number of events to return. Default: -1 returns all events available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- rename(login)
Rename the user.
Note
This is only available for administrators of a GitHub Enterprise instance.
- Parameters:
login (str) – (required), new name of the user
- Returns:
bool
- revoke_impersonation()
Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- starred_repositories(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by this user.
Changed in version 0.5: Added sort and direction parameters (optional) as per the change in GitHub’s API.
- Parameters:
number (int) – (optional), number of starred repos to return. Default: -1, returns all available repos
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
StarredRepository
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by this user.
- Parameters:
number (int) – (optional), number of subscriptions to return. Default: -1, returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Repository
- suspend()
Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- unsuspend()
Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- class github3.users.Collaborator(json, session: GitHubSession)
Object for the representation of a collaborator.
New in version 1.1.0.
When retrieving a repository’s contributors, GitHub returns the same information as a
ShortUser
with an additional attribute:- permissions
Admin, push, and pull permissions of a collaborator
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete the user.
Per GitHub API documentation, it is often preferable to suspend the user.
Note
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- demote()
Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- events(public=False, number=-1, etag=None)
Iterate over events performed by this user.
- Parameters:
public (bool) – (optional), only list public events for the authenticated user
number (int) – (optional), number of events to return. Default: -1 returns all available events.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- followers(number=-1, etag=None)
Iterate over the followers of this user.
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- following(number=-1, etag=None)
Iterate over the users being followed by this user.
- Parameters:
number (int) – (optional), number of users to return. Default: -1 returns all available users
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of this user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
GPGKey
s
- impersonate(scopes=None)
Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user. This is only available for admins of a GitHub Enterprise instance.
- Parameters:
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
- Returns:
Authorization
- is_assignee_on(username, repository)
Check if this user can be assigned to issues on username/repository.
- Parameters:
username (str) – owner’s username of the repository
repository (str) – name of the repository
- Returns:
True if the use can be assigned, False otherwise
- Return type:
bool
- is_following(username)
Check if this user is following
username
.- Parameters:
username (str) – (required)
- Returns:
bool
- keys(number=-1, etag=None)
Iterate over the public keys of this user.
New in version 0.5.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Key
s
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- organization_events(org, number=-1, etag=None)
Iterate over events from the user’s organization dashboard.
Note
You must be authenticated to view this.
- Parameters:
org (str) – (required), name of the organization
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- organizations(number=-1, etag=None)
Iterate over organizations the user is member of.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organization
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
ShortOrganization
s
- promote()
Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- received_events(public=False, number=-1, etag=None)
Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public events, otherwise you will only see public events.
- Parameters:
public (bool) – (optional), determines if the authenticated user sees both private and public or just public
number (int) – (optional), number of events to return. Default: -1 returns all events available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- rename(login)
Rename the user.
Note
This is only available for administrators of a GitHub Enterprise instance.
- Parameters:
login (str) – (required), new name of the user
- Returns:
bool
- revoke_impersonation()
Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- starred_repositories(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by this user.
Changed in version 0.5: Added sort and direction parameters (optional) as per the change in GitHub’s API.
- Parameters:
number (int) – (optional), number of starred repos to return. Default: -1, returns all available repos
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
StarredRepository
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by this user.
- Parameters:
number (int) – (optional), number of subscriptions to return. Default: -1, returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Repository
- suspend()
Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- unsuspend()
Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- class github3.users.Contributor(json, session: GitHubSession)
Object for the specialized representation of a contributor.
New in version 1.0.0.
Changed in version 1.1.0: This class now refreshes to a
User
.The attribute
contributions
was renamed tocontributions_count
, the documentation already declared it ascontributions_count
, it was the implementation now reflects this as well.When retrieving a repository’s contributors, GitHub returns the same information as a
ShortUser
with an additional attribute:- contributions_count
The number of contributions a contributor has made to the repository
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete the user.
Per GitHub API documentation, it is often preferable to suspend the user.
Note
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- demote()
Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- events(public=False, number=-1, etag=None)
Iterate over events performed by this user.
- Parameters:
public (bool) – (optional), only list public events for the authenticated user
number (int) – (optional), number of events to return. Default: -1 returns all available events.
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- followers(number=-1, etag=None)
Iterate over the followers of this user.
- Parameters:
number (int) – (optional), number of followers to return. Default: -1 returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- following(number=-1, etag=None)
Iterate over the users being followed by this user.
- Parameters:
number (int) – (optional), number of users to return. Default: -1 returns all available users
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
User
s
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- gpg_keys(number=-1, etag=None)
Iterate over the GPG keys of this user.
New in version 1.2.0.
- Parameters:
number (int) – (optional), number of GPG keys to return. Default: -1 returns all available GPG keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
GPGKey
s
- impersonate(scopes=None)
Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user. This is only available for admins of a GitHub Enterprise instance.
- Parameters:
scopes (list) – (optional), areas you want this token to apply to, i.e., ‘gist’, ‘user’
- Returns:
Authorization
- is_assignee_on(username, repository)
Check if this user can be assigned to issues on username/repository.
- Parameters:
username (str) – owner’s username of the repository
repository (str) – name of the repository
- Returns:
True if the use can be assigned, False otherwise
- Return type:
bool
- is_following(username)
Check if this user is following
username
.- Parameters:
username (str) – (required)
- Returns:
bool
- keys(number=-1, etag=None)
Iterate over the public keys of this user.
New in version 0.5.
- Parameters:
number (int) – (optional), number of keys to return. Default: -1 returns all available keys
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Key
s
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- organization_events(org, number=-1, etag=None)
Iterate over events from the user’s organization dashboard.
Note
You must be authenticated to view this.
- Parameters:
org (str) – (required), name of the organization
number (int) – (optional), number of events to return. Default: -1 returns all available events
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- organizations(number=-1, etag=None)
Iterate over organizations the user is member of.
- Parameters:
number (int) – (optional), number of organizations to return. Default: -1 returns all available organization
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
ShortOrganization
s
- promote()
Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- received_events(public=False, number=-1, etag=None)
Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public events, otherwise you will only see public events.
- Parameters:
public (bool) – (optional), determines if the authenticated user sees both private and public or just public
number (int) – (optional), number of events to return. Default: -1 returns all events available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Event
s
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- rename(login)
Rename the user.
Note
This is only available for administrators of a GitHub Enterprise instance.
- Parameters:
login (str) – (required), new name of the user
- Returns:
bool
- revoke_impersonation()
Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
- Returns:
bool – True if successful, False otherwise
- starred_repositories(sort=None, direction=None, number=-1, etag=None)
Iterate over repositories starred by this user.
Changed in version 0.5: Added sort and direction parameters (optional) as per the change in GitHub’s API.
- Parameters:
number (int) – (optional), number of starred repos to return. Default: -1, returns all available repos
sort (str) – (optional), either ‘created’ (when the star was created) or ‘updated’ (when the repository was last pushed to)
direction (str) – (optional), either ‘asc’ or ‘desc’. Default: ‘desc’
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
StarredRepository
- subscriptions(number=-1, etag=None)
Iterate over repositories subscribed to by this user.
- Parameters:
number (int) – (optional), number of subscriptions to return. Default: -1, returns all available
etag (str) – (optional), ETag from a previous request to the same endpoint
- Returns:
generator of
Repository
- suspend()
Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
- unsuspend()
Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more information.
- Returns:
bool – True if successful, False otherwise
AuthenticatedUser Peripherals
- class github3.users.Key(json, session: GitHubSession)
The object representing a user’s SSH key.
Please see GitHub’s Key Documentation for more information.
Changed in version 1.0.0: Removed
title
attribute- key
A string containing the actual text of the SSH Key
- id
GitHub’s unique ID for this key
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- delete()
Delete this key.
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- update(title, key)
Update this key.
Warning
As of 20 June 2014, the API considers keys to be immutable. This will soon begin to return MethodNotAllowed errors.
- Parameters:
title (str) – (required), title of the key
key (str) – (required), text of the key file
- Returns:
bool
- class github3.users.Plan(json, session: GitHubSession)
The
Plan
object.Please see GitHub’s Authenticated User documentation for more details.
- collaborators_count
Changed in version 1.0.0.
The number of collaborators allowed on this plan
- name
The name of the plan on GitHub
- private_repos_count
Changed in version 1.0.0.
The number of allowed private repositories
- space
The amount of space allotted by this plan
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- is_free()
Check if this is a free plan.
- Returns:
bool
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
- class github3.users.Email(json, session: GitHubSession)
The object used to represent an AuthenticatedUser’s email.
Please see GitHub’s Emails documentation for more information.
This object has all of the attributes of
ShortEmail
as well as the following attributes:- primary
A boolean value representing whether the address is the primary address for the user or not
- visibility
A string value representing whether an authenticated user can view the email address. Use
public
to allow it,private
to disallow it.
- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
Internals
Decorators
This part of the documentation covers the decorators module which contains all of the decorators used in github3.py.
Warning
These decorators are only to be used internally in development of this library.
Decorator Functions
- github3.decorators.requires_auth(x)
- github3.decorators.requires_basic_auth(x)
- github3.decorators.requires_app_credentials(func)
Require client_id and client_secret to be associated.
This is used to note and enforce which methods require a client_id and client_secret to be used.
Models
This part of the documentation covers a lot of lower-level objects that are never directly seen or used by the user (developer). They are documented for future developers of this library.
Warning
These classes are only to be used internally in development of this library.
- class github3.models.GitHubCore(json, session: GitHubSession)
The base object for all objects that require a session.
The
GitHubCore
object provides some basic attributes and methods to other sub-classes that are very useful to have.- as_dict()
Return the attributes for this object as a dictionary.
This is equivalent to calling:
json.loads(obj.as_json())
- Returns:
this object’s attributes serialized to a dictionary
- Return type:
dict
- as_json()
Return the json data for this object.
This is equivalent to calling:
json.dumps(obj.as_dict())
- Returns:
this object’s attributes as a JSON string
- Return type:
str
- classmethod from_dict(json_dict, session)
Return an instance of this class formed from
json_dict
.
- classmethod from_json(json, session)
Return an instance of this class formed from
json
.
- new_session()
Generate a new session.
- Returns:
A brand new session
- Return type:
- property ratelimit_remaining
Number of requests before GitHub imposes a ratelimit.
- Returns:
int
- refresh(conditional: bool = False) GitHubCore
Re-retrieve the information for this object.
The reasoning for the return value is the following example:
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of
None
’s and you would otherwise have to do:repos = [r for i in g.repositories_by('kennethreitz')] [r.refresh() for r in repos]
Which is really an anti-pattern.
Changed in version 0.5.
- Parameters:
conditional (bool) – If True, then we will search for a stored header (‘Last-Modified’, or ‘ETag’) on the object and send that as described in the Conditional Requests section of the docs
- Returns:
self
Version History
Release Notes and History
All of the release notes that have been recorded for github3.py are organized here with the newest releases first.
4.x Release Series
4.0.0: 2023-04-23
Backwards Incompatible Changes
Features Added
Removal
Remove support to EOL Python 3.6 (@staticdev). See also gh-1103
Bug Fixes
Missing set permission for collaborators (@NargiT). See also gh-954
CI/CD
4.0.1: 2023-04-25
CI/CD
Disable hatch strict naming for packaing (@staticdev). See also gh-1145
3.x Release Series
3.2.0: 2022-03-02
Bug Fixes
Migrate to GitHub’s supported Teams endpoints for select methods that were relying on the deprecated endpoints. See also gh-1080
3.1.1: 2022-02-22
Bugs Fixed
Always specify our
PyJWT
dependency with thecrypto
extra so that users will getcryptography
installed for them. Previously,jwcrypto
had an explicit dependency on this but forPyJWT
it is optional.
3.1.1: 2022-02-21
Features Added
Support editing parent team and team visibility via
github3.orgs.Team.edit()
Added more allowed statuses to Deployments for
github3.repos.deployment.Deployment.create_status()
3.1.0: 2022-02-14
Dependency Change
Swapped LGPL jwcrypto dependency for non-GPL PyJWT
Features Added
Add
ShortRepositoryWithPermissions
to include the permissions dictionary returned by the GitHub API when listing repositories a team has access to.Add
github3.orgs.Team.permissions_for("<org>/<repo>")()
to retrieve a full permissions listing for a given repository in an organization.
Bug Fixes
Previously, if a file was empty
Contents.decoded
might return text instead of bytes, this is now fixed.Fix
Repository#ref
using the wrong endpoint
3.0.0: 2021-10-31
Backwards Incompatible Changes
protect()
has been updated to reflect the GitHub API
Features Added
Add
maintainer_can_modify
parameter tocreate_pull()
Add
required_linear_history
,allow_force_pushes
,allow_deletions
, andrequired_conversation_resolution
.Add support for blocking users to
GitHub
andOrganization
.Add support for beta branch synchronization endpoint
sync_with_upstream()
Stargazer
was added to give access to thestarred_at
value when listing stargazers on a Repository object.
2.x Release Series
2.0.0: 2021-02-21
Features Added
Add support to Python 3.8 and 3.9.
Remove support to Python versions that reached end-of-life (2, 3.4 and 3.5).
Update CI/CD to thoroughly test all supported version.
Remove compatibility imports for Python 2.
Remove dev-dependency for mock.
Bugs Fixed
Key errors on Gist.history.
Removals
Removal of legacy unicode future imports.
Removal of already deprecated code on version 1.x:
github3.api.all_events
usegithub.GitHub.all_events
github3.api.all_repositories
usegithub.GitHub.all_repositories
github3.api.all_users
usegithub.GitHub.all_users
github3.api.authorize
usegithub.GitHub.authorize
github3.api.create_gist
usegithub.GitHub.create_gist
github3.api.emojis
github3.api.followed_by
usegithub.GitHub.followed_by
github3.api.followers_of
usegithub.GitHub.followers_of
github3.api.gist
usegithub.GitHub.gist
github3.api.gists_by
usegithub.GitHub.gists_by
github3.api.gitignore_template
usegithub.GitHub.gitignore_template
github3.api.gitignore_templates
usegithub.GitHub.gitignore_templates
github3.api.issue
usegithub.GitHub.issue
github3.api.issues_on
usegithub.GitHub.issues_on
github3.api.markdown
usegithub.GitHub.markdown
github3.api.octocat
usegithub.GitHub.octocat
github3.api.organization
github3.api.organizations_with
usegithub.GitHub.organizations_with
github3.api.public_gists
usegithub.GitHub.public_gists
github3.api.pull_request
usegithub.GitHub.pull_request
github3.api.rate_limit
github3.api.repositories_by
usegithub.GitHub.organizations_with
github3.api.repository
github3.api.search_code
usegithub.GitHub.search_code
github3.api.search_issues
usegithub.GitHub.search_issues
github3.api.search_repositories
usegithub.GitHub.search_repositories
github3.api.search_users
usegithub.GitHub.search_users
github3.api.starred_by
usegithub.GitHub.starred_by
github3.api.subscriptions_for
usegithub.GitHub.subscriptions_for
github3.api.user
github3.api.zen
usegithub.GitHub.zen
Git#Blob.decoded
useGit#Blob.decode_content
Team#is_member
useLogin#is_member
Team#add_member
useTeam#add_or_update_membership
Team#invite
useTeam#add_or_update_membership
Team#remove_member
useTeam#add_or_update_membership
Organization#add_member
addusername
toteam
.Organization#events
useOrganization#public_events
Issue#assign
useissues.issue.Issue.add_assignees
1.x Release Series
1.3.0: 2019-01-24
Features Added
Add partial support for the Checks API:
Add support for listing check runs via
check_runs
and check suites viacheck_suites
methods toRepoCommit
,MiniCommit
andShortCommit
classesCheckRun.update
to update the check runCheckSuite.check_runs
to retrieve the check runs for this suiteCheckRunOutput.annotations
class to retrieve the annotations for a check run
Add
unignore
method to unignore notifications from repository for the user, toRepository
andShortRepository
classes.Add
unsubscribe
method to unsubscribe the user to repository’s notifications, toRepository
andShortRepository
classes.Add support for webhooks in an organization by adding:
OrganizationHook
classcreate_hook
,hook
, andhooks
methods toShortOrganization
andOrganization
classes
A
Project.retrieve_issue_from_content
method was added to retrieve an Issue from the content url.A
Project.retrieve_pull_request_from_content
method was added to retrieve a PullRequest from the content url.Add support for Parent/Child teams via the
hellicat-preview
API preview type.Add support for specifying merge commit titles when merging a Pull Request.
Bugs Fixed
Stop hard-coding GitHub url that breaks work with a GitHub Enterprise instance.
Set default connect and read timeouts in
GitHubSession
to avoid hangs.
1.2.0: 2018-08-22
This is a larger release with some enhancements and bug fixes.
Features Added
Partial GitHub Apps support. We added the following:
GitHub.login_as_app
to login using JWT as an ApplicationGitHub.login_as_app_installation
to login using a token obtained from an App’s JWTGitHub.app
to retrieve an application by its “slug”GitHub.app_installation
to retrieve a specific installation by its IDGitHub.app_installations
to retrieve all of an App’s installationsGitHub.app_installation_for_organization
to retrieve an organization’s installation of an AppGitHub.app_installation_for_repository
to retrieve an installation for a specific repositoryGitHub.app_installation_for_user
to retrieve an installation for a specific userGitHub.authenticated_app
to retrieve the metadata for a specific AppNot supported as of this release:
Organization Invitations Preview API is now supported. This includes an additional
Invitation
object. This is the result of hard work by Hal Wine.A
ShortLabel
class was added to represent the shorter (description-less) representation of labels returned by the API.The branch protections API is now completely represented in github3.py.
We now support the GPG Keys API.
We now support the Commit Search API.
We now support Repository Invitations.
We now have assign and unassign methods that support assigning and unassigning multiple users at once.
We now support review requests on Pull Requests.
We now support the ability for a user to activate their membership in an Organization.
We now support recurisvely traverse a tree via the API.
We now support enabling or disabling projects on a Repository.
We now support editing and reading Repository topics.
We now support Repository Pull Request merge settings.
Bugs Fixed
No longer require a Gist to have an owner.
Branch.latest_sha()
now returns text (unicode) as documented.
Special Thanks
A great deal of the exception feature work done above was performed by the
newest team member of the github3.py project: Jacopo Notarstefano (a.k.a,
@jacquerie
on GitHub). This project has had new life breathed into it
thanks to Jacopo.
1.1.0: 2018-04-09
This is a small release with some enhancements.
Features Added
Repository collaborators now returns a
users.Collaborator
object, instead of ausers.ShortUser
object. This is to support collaborator affiliations. A refresh call of this object (andusers.Contributor
) will result in a fullusers.User
object.The call to iterate collaborators of a repository (
Repository#collaborators
) can now take anaffiliation
filter with options ofoutside
,direct
, andall
. The default isall
, which preserves the previous behavior of this method.
Bugs Fixed
Parse certain attributes on
IssueEvent
into objects (again, this was a regression in 1.0)Handle older GitHub Enterprise responses for authenticated user objects
Handle large file pull request responses not including a
patch
attribute
1.0.2: 2018-03-28
Bugs Fixed
Handle 304s from users passing etag
Generate
_api
attribute forShortBranch
objectsRequire auth for creating gists
Ensure only desired auth scheme is used with requests
Handle older GitHub Enterprise responses for repository objects
1.0.1: 2018-03-14
Bugs Fixed
Fix missing python-dateutil requirement when installing from a wheel.
1.0.0: 2018-03-13
1.0.0 is a huge release. It includes a great deal of changes to github3.py
.
It is suggested you read the following release notes carefully.
Unfortunately, it’s plausible that some things have slipped through the cracks in these release notes.
Breaking Changes
Methods that iterate over collections return a separate class than methods that retrieve a single instance. These objects have separate representations when retrieving the data from GitHub’s API. They include:
Team now can be represented by ShortTeam or Team
Organization now can be represented by ShortOrganization or Organization
Issue now can be represented by ShortIssue or Issue
PullRequest now can be represented by ShortPullRequest or PullRequest
Commit now can be represented by ShortCommit, or Commit
Gist now can be represented by ShortGist, GistFork, or Gist
GistFile now can be represented by ShortGistFile or GistFile
Repository objects:
Branch now can be represented by ShortBranch or Branch
RepoComment now can be represented by ShortComment or ShortRepoComment
Repository now can be represented by ShortRepository or Repository
RepoCommit now can be represented by MiniCommit, ShortCommit, or RepoCommit
Status now can be represented by ShortStatus or Status
User now can be represented by ShortUser, Contributor, User, or AuthenticatedUser
License now can be represented by ShortLicense or License
Refreshing a short representation of an object will result in a new object of a new class returned. For example:
import github3 users = [(u, u.refresh()) for u in github3.all_users(10)] for short_user, user in users: assert isinstance(short_user, github3.users.ShortUser) assert isinstance(user, github3.users.User)
Remove
Thread.comment
,Thread.thread
,Thread.urls
attributes.Remove
Thread#is_unread
method. Use theThread.unread
attribute instead.Subscription
has been split into two objects:ThreadSubscription
andRepositorySubscription
with the same methods.Remove
is_ignored
method from our Subscription objects. Use theignored
attribute instead.Remove
is_subscribed
method from our Subscription objects. Use thesubscribed
attribute instead.Move
Users#add_email_addresses
toGitHub#add_email_addresses
.Move
Users#delete_email_addresses
toGitHub#delete_email_addresses
.Remove
Users#add_email_address
andUsers#delete_email_address
.Remove
Repository#update_label
.When you download a release asset, instead of returning
True
orFalse
, it will return the name of the file in which it saved the asset.The
download
method ongithub3.pulls.PullFile
instances has been removed.The
contents
method ongithub3.pulls.PullFile
instances now return instances ofgithub3.repos.contents.Contents
.Replace
Repository#comments_on_commit
withRepoCommit#comments
.Organization#add_member
has been changed. The second parameter has been changed toteam_id
and now expects an integer.Organization#add_repository
has been changed. The second parameter has been changed toteam_id
and now expects an integer.All methods and functions starting with
iter_
have been renamed.
Old name |
New name |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
github3.login
has been simplified and split into two functions:github3.login
serves the majority use case and only provides an authenticatedGitHub
object.github3.enterprise_login
allows GitHub Enterprise users to log into their service.
GitHub#iter_followers
was split into two functions:GitHub#followers_of
which iterates over all of the followers of a user whose username you provideGitHub#followers
which iterates over all of the followers of the authenticated user
GitHub#iter_following
was split into two functions:GitHub#followed_by
which iterates over all of the users followed by the username you provideGitHub#following
which iterates over all of the users followed by the authenticated user
GitHub#iter_gists
was split into three functions:GitHub#public_gists
which iterates over all of the public gists on GitHubGitHub#gists_for
which iterates over all the public gists of a specific userGitHub#gists
which iterates over the authenticated users gists
GitHub#iter_orgs
was split into two functions:GitHub#organizations
which iterates over the authenticated user’s organization membershipsGitHub#organizations_with
which iterates over the given user’s organization memberships
GitHub#iter_subscriptions
was split into two functions:GitHub#subscriptions_for
which iterates over an arbitrary user’s subscriptionsGitHub#subscriptions
which iterates over the authenticated user’s subscriptions
GitHub#iter_starred
was split into two functions:GitHub#starred_by
which iterates over an arbitrary user’s starsGitHub#starred
which iterates over the authenticated user’s stars
GitHub#user
was split into two functions:GitHub#user
which retrieves an arbitrary user’s informationGitHub#me
which retrieves the authenticated user’s information
GitHub#update_user
has been renamed toGitHub#update_me
and only uses 1 API call now. It was renamed to reflect the addition ofGitHub#me
.The legacy watching API has been removed:
GitHub#subscribe
GitHub#unsubscribe
GitHub#is_subscribed
GitHub#create_repo
was renamed toGitHub#create_repository
GitHub#delete_key
was removed. To delete a key retrieve it withGitHub#key
and then callKey#delete
.Repository#set_subscription
was split into two simpler functionsRepository#subscribe
subscribes the authenticated user to the repository’s notificationsRepository#ignore
ignores notifications from the repository for the authenticated user
Repository#contents
was split into two simpler functionsRepository#file_contents
returns the contents of a file objectRepository#directory_contents
returns the contents of files in a directory.
Organization#add_repo
andTeam#add_repo
have been renamed toOrganization#add_repository
andTeam#add_repository
respectively.Organization#create_repo
has been renamed toOrganization#create_repository
. It no longer acceptshas_downloads
. It now acceptslicense_template
.Organization#remove_repo
has been renamed toOrganization#remove_repository
. It now acceptsteam_id
instead ofteam
.github3.ratelimit_remaining
was removedGitHub
instances can no longer be used as context managersThe pull request API has changed.
The
links
attribute now contains the raw_links
attribute from the API.The
merge_commit_sha
attribute has been removed since it was deprecated in the GitHub API.To present a more consistent universal API, certain attributes have been renamed.
Old name |
New attribute name |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The Gist API has changed.
The
forks
andfiles
attributes that used to keep count of the number offorks
andfiles
have been removed.The
comments
attribute which provided the number of comments on a gist, has been renamed tocomments_count
.The
is_public
method has been removed since it just returned theGist.public
attribute.
Most instances of
login
as a parameter have been changed tousername
for clarity and consistency. This affects the following methods:github3.authorize
github3.repositories_by
github3.user
GitHub
GitHub#authorize
GitHub#follow
GitHub#is_following
GitHub#is_starred
GitHub#issue
GitHub#followers_of
GitHub#followed_by
GitHub#gists_by
GitHub#issues_on
GitHub#organizations_with
GitHub#starred_by
GitHub#subscriptions_for
GitHub#user
GitHubEnterprise
Issue#assign
Organization#add_member
Organization#is_member
Organization#is_public_member
Organization#remove_member
Repository#add_collaborator
Repository#is_assignee
Repository#is_collaborator
Repository#remove_collaborator
Team#add_member
Team#is_member
User#is_assignee_on
User#is_following
Repository.stargazers
is nowRepository.stargazers_count
(conforming with the attribute name returned by the API).The
Issue
API has changed in order to provide a more consistent attribute API.Issue.comments
is nowIssue.comments_count
and returns the number of comments on an issue.The
Issue.labels
attribute has also been renamed. It is now available fromIssue.original_labels
. This will provide the user with the list ofLabel
objects that was returned by the API. To retrieve an updated list of labels, the user can now useIssue#labels
, e.g.i = github3.issue('sigmavirus24', 'github3.py', 30) labels = list(i.labels())
The
Organization
andUser
APIs have changed to become more consistent with the rest of the library and GitHub API. The following attribute names have been changed
Old name |
New attribute name |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
The
Release.assets
attribute has been renamed toRelease.original_assets
. To retrieve up-to-date assets, use theRelease#assets
method.The
Authorization
API has changed. Theupdate
method has been split into three methods:add_scopes
,remove_scopes
,replace_scopes
. This highlights the fact thatAuthorization#update
used to require more than one request.Event#is_public
has been removed. Simply check the event’spublic
attribute instead.Repository#delete_file
andRepository#update_file
have been removed. Simply delete or update a file using the Contents API.Content#delete
now returns a dictionary that matches the JSON returned by the API. It contains the Contents and the Commit associated with the deletion.Content#update
now returns a dictionary that matches the JSON returned by the API. It contains the Contents and the Commit associated with the deletion.Issue.pull_request
has been renamed toIssue.pull_request_urls
New Features
Most objects now have a
session
attribute. This is a subclass of aSession
object fromrequests
. This can now be used in conjunction with a third-party caching mechanism. The suggested caching library iscachecontrol
.All object’s
url
attribute are now available.You can now retrieve a repository by its id with
GitHub#repository_with_id
.You can call the
pull_request
method on anIssue
now to retrieve the associated pull request:import github3 i = github3.issue('sigmavirus24', 'github3.py', 301) pr = i.pull_request()
Add support for the Issue locking API currently in Preview Mode
Add
Organization#all_events
.Add
Tag.tagger_as_User
which attempts to return the tagger as User.Add
Repo.statuses
and a correspondingrepo.status.CombinedStatus
toSupport filtering organization members by whether they have 2FA enabled.
Support filtering organization and team members by role.
Add
GitHub#all_organizations
.Add
PullRequest#create_comment
.Add
Repository#release_by_tag_name
to retrieve a Release from a Repository by its associated tag name.Add
Repository#latest_release
to retrieve the latest Release for a Repository.Add
GitHub#license
to retrieve agithub3.license.License
by the license name.Add
GitHub#licenses
to iterate over all the licenses returned by GitHub’s Licenses API.Add protection information to
github3.repos.branch.Branch
.Add
Branch#protect
andBranch#unprotect
to support updating a Branch’s protection status.Vastly improved GitHub Enterprise support:
Add
User#rename
to rename a user in a GitHub Enterprise installation.Add
GitHub#create_user
to create a user.Add
User#impersonate
to create an impersonation token by an admin for a particular user.Add
User#revoke_impersonation
to revoke all impersonation tokens for a user.Add
User#promote
to promote a particular user to a site administrator.Add
User#demote
to demote a site administrator to a simple user.Add
User#suspend
to suspend a user’s account.Add
User#unsuspend
to reinstate a user’s account.
Add
original_content
attribute to aGistFile
Add
GistFile#content
to retrieve the contents of a file in a gist from the API.Add support for the alpha bulk issue import API
You can now download a file in a pull request to a file on disk.
You can retrieve the contents of the file in a pull request as bytes.
Add
id
attribute togithub3.repos.milestone.Milestone
.Add support for sort, direction, and since parameters to the
comments
method ongithub3.issues.Issue
.Add branch argument to update and delete methods on
github3.repos.contents.Contents
.Add
permissions
attribute togithub3.repos.repo.Repository
object to retrieve the permissions for a specific repository.Allow a deployment to be retrieved by its id.
Add the
delete
method to thegithub3.repos.release.Asset
class.
Bugs Fixed
Fix the dependencies and requirements. In 1.0.0a3 we moved to using the
setup.cfg
file to define optional dependencies for wheels. By doing so we accidentally left out our actual hard dependencies.The
context
parameter toRepository#create_status
now properly defaults todefault
.Fix AttributeError when
IssueEvent
has assignee.Correctly set the
message
attribute onRepoCommit
instances.Include
browser_download_url
onAsset
instances.(Packaging related) Fix
setup.py
to use proper values for certain parameters.Fix
ValueError
forRepository#create_file
.Pull request files can now be downloaded even when the repository is private.
Fix exception when merging a pull request with an empty commit message.
Add missing Issue events.
Coerce review comment positions to integers.
Deprecations and Other Changes
Deprecate
Organization#events
in favor ofOrganization#public_events
.Fix test failures on Windows caused by unclosed file handles. get a combined view of commit statuses for a given ref.
The
refresh
method will eventually stop updating the instance in place and instead only return new instances of objects.
0.x Release Series
0.9.3: 2014-11-04
Backport of
PullRequest#create_review_comment
by Adrian MoiseyBackport of
PullRequest#review_comments
by Adrian MoiseyBackport of a fix that allows authenticated users to download Release Assets. Original bug reported by Eugene Fidelin in issue #288.
Documentation typo fix by Marc Abramowitz
0.9.2: 2014-10-05
Updates for new team management API changes
Add
Team#invite
,Team#membership_for
, andTeam#revoke_membership
Deprecate
Team#add_member
,Team#remove_member
, andOrganization#add_member
.Update payload handler for
TeamAddEvent
.
0.9.1: 2014-08-10
Correct Repository attribute
fork_count
should beforks_count
0.9.0: 2014-05-04
Add Deployments API
Add Pages API
Add support so applications can revoke a single authorization or all authorizations created by the application
Add the ability for users to ping hooks
Allow users to list a Repository’s collaborators
Allow users to create an empty blob on a Repository
Update how users can list issues and pull requests. See: http://developer.github.com/changes/2014-02-28-issue-and-pull-query-enhancements/ This includes breaking changes to
Repository#iter_pulls
.Update methods to handle the pagination changes.
Fix typo stargarzers_url
Add
assets
attribute toRelease
object.Fix wrong argument to
Organization#create_team
(permissions
versuspermission
)Fix Issue Search Result’s representation and initialization
Fix Repository Search Result’s initialization
Allow users to pass a two-factor authentication callback to
GitHub#authorize
.
0.8.2: 2014-02-11
Fix bug in
GitHub#search_users
(andgithub3.search_users
). Thanks @abestoExpose the stargazers count for repositories. Thanks @seveas
0.8.1: 2014-01-26
Add documentation for using Two-factor Authentication
Fix oversight where
github3.login
could not be used for 2FA
0.8.0: 2014-01-03
Breaking Change Remove legacy search API
I realize this should have been scheduled for 1.0 but I was a bit eager to remove this.
Use Betamax to start recording integration tests
Add support for Releases API
Add support for Feeds API
Add support for Two-Factor Authentication via the API
Add support for New Search API
Add
github3.search_code
,github3.search_issues
,github3.search_repositories
,github3.search_users
Add
GitHub#search_code
,GitHub#search_issues
,GitHub#search_repositories
,GitHub#search_users
Switch to requests >= 2.0
Totally remove all references to the Downloads API
Fix bug in
Repository#update_file
wherebranch
was not being sent to the API. Thanks @tpetr!Add
GitHub#rate_limit
to return all of the information from the/rate_limit
endpoint.Catch missing attributes –
diff_hunk
,original_commit_id
– onReviewComment
.Add support for the Emojis endpoint
Note deprecation of a few object attributes
Add support for the
ReleaseEvent
Add
GitHub#iter_user_teams
to return all of the teams the authenticated user belongs to
0.7.1: 2013-09-30
Add dependency on uritemplate.py to add URITemplates to different classes. See the documentation for attributes which are templates.
Fixed issue trying to parse
html_url
on Pull Requests courtesy of @rogerhu.Remove
expecter
as a test dependency courtesy of @esacteksab.Fixed issue #141 trying to find an Event that doesn’t exist.
0.7.0: 2013-05-19
Fix
Issue.close
,Issue.reopen
, andIssue.assign
. (Issue #106)Add
check_authorization
to theGitHub class
to cover the new part of the API.Add
create_file
,update_file
,delete_file
,iter_contributor_statistics
,iter_commit_activity
,iter_code_frequency
andweekly_commit_count
to theRepository
object.Add
update
anddelete
methods to theContents
object.Add
is_following
to theUser
object.Add
head
,base
parameters toRepository.iter_pulls
.The signature of
Hook.edit
has changed since that endpoint has changed as well. See: github/developer.github.com@b95f291a47954154a6a8cd7c2296cdda9b610164github3.GitHub
can now be used as a context manager, e.g.,with github.GitHub() as gh: u = gh.user('sigmavirus24')
0.6.1: 2013-04-06
Add equality for labels courtesy of Alejandro Gomez (@alejandrogomez)
0.6.0: 2013-04-05
Add
sort
andorder
parameters togithub3.GitHub.search_users
andgithub3.GitHub.search_repos
.Add
iter_commits
togithub3.gists.Gist
as a means of re-requesting just the history from GitHub and iterating over it.Add minimal logging (e.g.,
logging.getLogger('github3')
)Re-organize the library a bit. (Split up repos.py, issues.py, gists.py and a few others into sub-modules for my sanity.)
Calling
refresh(True)
on agithub3.structs.GitHubIterator
actually works as expected now.API
iter_
methods now accept theetag
argument as theGitHub.iter_
methods do.Make
github3.octocat
andgithub3.github.GitHub.octocat
both support sending messages to make the Octocat say things. (Think cowsay)Remove vendored dependency of PySO8601.
Split
GitHub.iter_repos
intoGitHub.iter_user_repos
andGitHub.iter_repos
. As a consequencegithub3.iter_repos
is nowgithub3.iter_user_repos
IssueComment.update
was corrected to match GitHub’s documentationgithub3.login
now accepts an optionalurl
parameter for users of theGitHubEnterprise
API, courtesy of Kristian Glass (@doismellburning)Several classes now allow their instances to be compared with
==
and!=
. In most cases this will check the unique id provided by GitHub. In others, it will check SHAs and any other guaranteed immutable and unique attribute. The class doc-strings all have information about this and details about how equivalence is determined.
0.5.3: 2013-03-19
Add missing optional parameter to Repository.contents. Thanks @tpetr
0.5.2: 2013-03-02
Stop trying to decode the byte strings returned by
b64decode
. Fixes #72
0.5.1: 2013-02-21
Hot fix an issue when a user doesn’t have a real name set
0.5.0: 2013-02-16
100% (mock) test coverage
Add support for conditional refreshing, e.g.,
import github3 u = github3.user('sigmavirus24') # some time later u.refresh() # Will ALWAYS send a GET request and lower your rate limit u.refresh(True) # Will send the GET with a header such that if nothing # has changed, it will not count against your rate limit # otherwise you'll get the updated user object.
Add support for conditional iterables. What this means is that you can do:
import github3 i = github3.iter_all_repos(10) for repo in i: # do stuff i = github3.iter_all_repos(10, etag=i.etag)
And the second call will only give you the new repositories since the last request. This mimics behavior in pengwynn/octokit
Add support for sortable stars.
In github3.users.User,
iter_keys
now allows you to iterate over any user’s keys. No name is returned for each key. This is the equivalent of visiting: github.com/:user.keysIn github3.repos.Repository,
pubsubhubbub
has been removed. Use github3.github.Github.pubsubhubbub insteadIn github3.api,
iter_repo_issues
’s signature has been corrected.Remove
list_{labels, comments, events}
methods from github3.issues.IssueRemove
list_{comments, commits, files}
methods from github3.pulls.PullRequestIn github3.gists.Gist:
the
user
attribute was changed by GitHub and is now theowner
attributethe
public
attribute and theis_public
method return the same information. The method will be removed in the next version.the
is_starred
method now requires authenticationthe default
refresh
method is no longer over-ridden. In a change made in before, a genericrefresh
method was added to most objects. This was overridden in the Gist object and would cause otherwise unexpected results.
github3.events.Event.is_public()
andgithub3.events.Event.public
now return the same information. In the next version, the former will be removed.In github3.issues.Issue
add_labels
now returns the list of Labels on the issue instead of a boolean.remove_label
now returns a boolean.remove_all_labels
andreplace_labels
now return lists. The former should return an empty list on a successful call. The latter should return a list ofgithub3.issue.Label
objects.
Now we won’t get spurious GitHubErrors on 404s, only on other expected errors whilst accessing the json in a response. All methods that return an object can now actually return None if it gets a 404 instead of just raising an exception. (Inspired by #49)
GitHubStatus API now works.
0.4.0: 2013-01-16
In github3.legacy.LegacyRepo
has_{downloads,issues,wiki}
are now attributes.is_private()
and theprivate
attribute return the same thingis_private()
will be deprecated in the next release.
In github3.repos.Repository
is_fork()
is now deprecated in favor of thefork
attributeis_private()
is now deprecated in favor of theprivate
attribute
In github3.repos.Hook
is_active()
is now deprecated in favor of theactive
attribute
In github3.pulls.PullRequest
is_mergeable()
is now deprecated in favor of themergeable
attribute
In github3.notifications.Thread
is_unread()
is now deprecated in favor of theunread
pubsubhubbub()
is now present on theGitHub
object and will be removed from theRepository
object in the next release70% test coverage
0.3.0: 2013-01-01
In github3.repos.Repository
is_fork() and fork return the same thing
is_private() and private return the same thing as well
has_downloads, has_issues, has_wiki are now straight attributes
In github3.repos.Hook
is_active() and active return the same value
In github3.pulls.PullRequest
is_mergeable() and mergeable are now the same
repository now returns a tuple of the login and name of the repository it belongs to
In github3.notifications.Thread
is_unread() and unread are now the same
In github3.gists
GistFile.filename and GistFile.name return the same information
Gist.history now lists the history of the gist
GistHistory is an object representing one commit or version of the history
You can retrieve gists at a specific version with GistHistory.get_gist()
github3.orgs.Organization.iter_repos now accepts all types
list_* methods on Organization objects that were missed are now deleted
Some objects now have
__str__
methods. You can now do things like:import github3 u = github3.user('sigmavirus24') r = github3.repository(u, 'github3.py')
And
import github3 repo = github3.repository('sigmavirus24', 'github3.py') template = """Some kind of template where you mention this repository {0}""" print(template.format(repo)) # Some kind of template where you mention this repository # sigmavirus24/github3.py
Current list of objects with this feature:
github3.users.User (uses the login name)
github3.users.Key (uses the key text)
github3.users.Repository (uses the login/name pair)
github3.users.RepoTag (uses the tag name)
github3.users.Contents (uses the decoded content)
60% test coverage with mock
Upgrade to requests 1.0.x
0.2.0: 2012-11-21
MAJOR API CHANGES:
GitHub.iter_subscribed
–>GitHub.iter_subscriptions
Broken
list_*
functions in github3.api have been renamed to the correctiter_*
methods onGitHub
.Removed
list_*
functions fromRepository
,Gist
,Organization
, andUser
objects
Added zen of GitHub method.
More tests
Changed the way
Repository.edit
works courtesy of Kristian Glass (@doismellburning)Changed
Repository.contents
behavior when acting on a 404.50% test coverage via mock tests
0.1.0: 2012-11-13
Add API for GitHub Enterprise customers.
0.1b2: 2012-11-10
Handle 500 errors better, courtesy of Kristian Glass (@doismellburning)
Handle sending JSON with
%
symbols better, courtesy of Kristian GlassCorrectly handle non-GitHub committers and authors courtesy of Paul Swartz (@paulswartz)
Correctly display method signatures in documentation courtesy of (@seveas)
0.1b1: 2012-10-31
unit tests implemented using mock instead of hitting the GitHub API (#37)
removed
list_*
functions from GitHub objectNotifications API coverage
0.1b0: 2012-10-06
Support for the complete GitHub API (accomplished)
Now also includes the Statuses API
Also covers the auto_init parameters to the Repository creation methodology
Limited implementation of iterators in the place of list functions.
98% coverage by unit tests
Contributing
All development happens on GitHub. Please remember to add yourself to the list of contributors in AUTHORS.rst, especially if you’re going to be working on the list below.
Contributor Friendly Work
In order of importance:
Documentation
I know I’m not the best at writing documentation so if you want to clarify or correct something, please do so.
Examples
Have a clever example that takes advantage of github3.py? Feel free to share it.
Otherwise, feel free to example the list of issues where we would like help and feel free to take one.
Running the Unittests
The tests are generally run using tox. Tox can be installed like so
pip install tox
We test against PyPy3 and the following versions of Python:
3.7
3.8
3.9
If you simply run tox
it will run tests against all of these versions of
python and run flake8
against the codebase as well. If you want to run
against one specific version, you can do
tox -e py39
And if you want to run tests against a specific file, you can do
tox -e py39 -- tests/unit/test_github.py
To run the tests, tox
uses py.test
so you can pass any options or
parameters to py.test
after specifying --
. For example, you can get
more verbose output by doing
tox -e py39 -- -vv
Writing Tests for github3.py
Unit Tests
In computer programming, unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures are tested to determine if they are fit for use. Intuitively, one can view a unit as the smallest testable part of an application.
In github3.py we use unit tests to make assertions about how the library behaves without making a request to the internet. For example, one assertion we might write would check if custom information is sent along in a request to GitHub.
An existing test like this can be found in
tests/unit/test_repos_release.py
:
def test_delete(self):
self.instance.delete()
self.session.delete.assert_called_once_with(
self.example_data['url'],
headers={'Accept': 'application/vnd.github.manifold-preview'}
)
In this test, we check that the library passes on important headers to the API
to ensure the request will work properly. self.instance
is created for us
and is an instance of the Release
class. The test then calls delete
to
make a request to the API. self.session
is a mock object which fakes out a
normal session. It does not allow the request through but allows us to verify
how github3.py makes a request. We can see that github3.py called delete
on the session. We assert that it was only called once and that the only
parameters sent were a URL and the custom headers that we are concerned with.
Mocks
Above we talked about mock objects. What are they?
In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.
We use mocks in github3.py to prevent the library from talking directly with GitHub. The mocks we use intercept requests the library makes so we can verify the parameters we use. In the example above, we were able to check that certain parameters were the only ones sent to a session method because we mocked out the session.
You may have noticed in the example above that we did not have to set up the
mock object. There is a convenient helper written in tests/unit/helper.py
to do this for you.
Example - Testing the Release Object
Here’s a full example of how we test the Release
object in
tests/unit/test_repos_release.py
.
Our first step is to import the UnitHelper
class from
tests/unit/helper.py
and the Release
object from
github3/repos/release.py
.
from .helper import UnitHelper
from github3.repos.release import Release
Then we construct our test class and indicate which class we will be testing (or describing).
class TestRelease(UnitHelper):
described_class = Release
We can then use the GitHub API documentation about Releases to retrieve example release data. We then can use that as example data for our test like so:
class TestRelease(UnitHelper):
described_class = Release
example_data = {
"url": releases_url("/1"),
"html_url": "https://github.com/octocat/Hello-World/releases/v1.0.0",
"assets_url": releases_url("/1/assets"),
"upload_url": releases_url("/1/assets{?name}"),
"id": 1,
"tag_name": "v1.0.0",
"target_commitish": "master",
"name": "v1.0.0",
"body": "Description of the release",
"draft": False,
"prerelease": False,
"created_at": "2013-02-27T19:35:32Z",
"published_at": "2013-02-27T19:35:32Z"
}
The above code now will handle making clean and brand new instances of the
Release
object with the example data and a faked out session. We can now
construct our first test.
def test_delete(self):
self.instance.delete()
self.session.delete.assert_called_once_with(
self.example_data['url'],
headers={'Accept': 'application/vnd.github.manifold-preview'}
)
Integration Tests
Integration testing is the phase in software testing in which individual software modules are combined and tested as a group.
The purpose of integration testing is to verify functional, performance, and reliability requirements placed on major design items.
In github3.py we use integration tests to ensure that when we make what should be a valid request to GitHub, it is in fact valid. For example, if we were testing how github3.py requests a user’s information, we would expect a request for a real user’s data to be valid. If the test fails we know either what the library is doing is wrong or the data requested does not exist.
An existing test that demonstrates integration testing can be found in
tests/integration/test_repos_release.py
:
def test_iter_assets(self):
"""Test the ability to iterate over the assets of a release."""
cassette_name = self.cassette_name('iter_assets')
with self.recorder.use_cassette(cassette_name):
repository = self.gh.repository('sigmavirus24', 'github3.py')
release = repository.release(76677)
for asset in release.iter_assets():
assert isinstance(asset, github3.repos.release.Asset)
assert asset is not None
In this test we use self.recorder
to record our interaction with GitHub.
We then proceed to make the request to GitHub that will exercise the code we
wish to test. First we request a Repository
object from GitHub and then
using that we request a Release
object. After receiving that release, we
exercise the code that lists the assets of a Release
. We verify that each
asset is an instance of the Asset
class and that at the end the asset
variable is not None
. If asset
was None
, that would indicate that
GitHub did not return any data and it did not exercise the code we are trying
to test.
Betamax
Betamax is the library that we use to create the recorder above. It sets up the session object to intercept every request and corresponding response and save them to what it calls cassettes. After you record the interaction it never has to speak to the internet again for that request.
In github3.py there is a helper class (much like UnitHelper
) in
tests/integration/helper.py
which sets everything up for us.
Example - Testing the Release Object
Here’s an example of how we write an integration test for github3.py. The
example can be found in tests/integration/test_repos_release.py
.
Our first steps are the necessary imports.
import github3
from .helper import IntegrationHelper
Then we start writing our test right away.
class TestRelease(IntegrationHelper):
def test_delete(self):
"""Test the ability to delete a release."""
self.token_login()
cassette_name = self.cassette_name('delete')
with self.recorder.use_cassette(cassette_name):
repository = self.gh.repository('github3py', 'github3.py')
release = repository.create_release(
'0.8.0.pre', 'develop', '0.8.0 fake release',
'To be deleted'
)
assert release is not None
assert release.delete() is True
Every test has access to self.gh
which is an instance of GitHub
.
IntegrationHelper
provides a lot of methods that allow you to focus on
what we are testing instead of setting up for the test. The first of those
methods we see in use is self.token_login
which handles authenticating
with a token. It’s sister method is self.basic_login
which handles
authentication with basic credentials. Both of these methods will set up the
authentication for you on self.gh
.
The next convenience method we see is self.cassette_name
. It constructs a
cassette name for you based on the test class name and the string you provide
it.
Every test also has access to self.recorder
. This is the Betamax recorder
that has been set up for you to record your interactions. The recorder is
started when you write
with self.recorder.use_cassette(cassette_name):
# …
Everything that talks to GitHub should be written inside of the context created by the context manager there. No requests to GitHub should be made outside of that context.
In that context, we then retrieve a repository and create a release for it. We
want to be sure that we will be deleting something that exists so we assert
that what we received back from GitHub is not None
. Finally we call
delete
and assert that it returns True
.
When you write your new test and record a new cassette, be sure to add the new cassette file to the repository, like so:
git add tests/cassettes/Release_delete.json
Contact
Twitter: @sigmavirus24
Private email: graffatcolmingov [at] gmail
Comment Objects
More information about these classes can be found in the official documentation about comments.
The representation of an abridged comment on an object in a repo.
This object has the following attributes:
The affiliation the author of this comment has with the repository.
The Markdown formatted text of this comment.
The SHA1 associated with this comment.
A
datetime
object representing the date and time when this comment was created.The URL to view this comment in a browser.
The unique identifier of this comment.
The line number where the comment is located.
The path to the file where this comment was made.
The position in the diff where the comment was left.
A
datetime
object representing the date and time when this comment was most recently updated.A
ShortUser
representing the author of this comment.The representation of the full comment on an object in a repository.
This object has the same attributes as a
ShortComment
as well as the following:The HTML formatted text of this comment.
The plain-text formatted text of this comment.