Utilities
Authentication
- class github.Auth.Login(login: str, password: str)
This class is used to authenticate with login and password.
- property username: str
The username.
- property password: str
The password.
- class github.Auth.Token(token: str)
This class is used to authenticate with a single constant token.
- property token_type: str
The type of the auth token as used in the HTTP Authorization header, e.g. Bearer or Basic.
- Returns:
token type
- property token: str
The auth token as used in the HTTP Authorization header.
- Returns:
token
- class github.Auth.JWT
This class is the base class to authenticate with a JSON Web Token (JWT).
- property token_type: str
The type of the auth token as used in the HTTP Authorization header, e.g. Bearer or Basic.
- Returns:
token type
- class github.Auth.AppAuth(app_id: int | str, private_key: str | Callable[[], str | bytes] | None = None, *, sign_func: Callable[[dict], str | bytes] | None = None, jwt_expiry: int = 300, jwt_issued_at: int = -60)
This class is used to authenticate as a GitHub App.
- property token: str
The auth token as used in the HTTP Authorization header.
- Returns:
token
- get_installation_auth(installation_id: int, token_permissions: dict[str, str] | None = None, requester: Requester | None = None) AppInstallationAuth
Creates a github.Auth.AppInstallationAuth instance for an installation.
- Parameters:
installation_id – installation id
token_permissions – optional permissions
requester – optional requester with app authentication
- Returns:
- create_jwt(expiration: int | None = None) str
Create a signed JWT https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
- Return string:
jwt
- class github.Auth.AppAuthToken(token: str)
This class is used to authenticate as a GitHub App with a single constant JWT.
- property token: str
The auth token as used in the HTTP Authorization header.
- Returns:
token
- class github.Auth.AppInstallationAuth(app_auth: AppAuth, installation_id: int, token_permissions: dict[str, str] | None = None, requester: Requester | None = None)
This class is used to authenticate as a GitHub App Installation.
- property token_type: str
The type of the auth token as used in the HTTP Authorization header, e.g. Bearer or Basic.
- Returns:
token type
- property token: str
The auth token as used in the HTTP Authorization header.
- Returns:
token
- class github.Auth.AppUserAuth(client_id: str, client_secret: str, token: str, token_type: str | None = None, expires_at: datetime | None = None, refresh_token: str | None = None, refresh_expires_at: datetime | None = None, requester: Requester | None = None)
This class is used to authenticate as a GitHub App on behalf of a user.
- class ApplicationOAuth(requester: Requester, headers: dict[str, Any], attributes: Any)
This class is used for identifying and authorizing users for Github Apps.
The reference can be found at https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps
- get_access_token(code: str, state: str | None = None) AccessToken
- get_login_url(redirect_uri: str | None = None, state: str | None = None, login: str | None = None) str
Return the URL you need to redirect a user to in order to authorize your App.
- refresh_access_token(refresh_token: str) AccessToken
- Calls:
- Parameters:
refresh_token – string
- property token_type: str
The type of the auth token as used in the HTTP Authorization header, e.g. Bearer or Basic.
- Returns:
token type
- property token: str
The auth token as used in the HTTP Authorization header.
- Returns:
token
Logging
- github.enable_console_debug_logging() None
This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting.
Error Handling
- exception github.GithubException.GithubException(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Error handling in PyGithub is done with exceptions. This class is the base of all exceptions raised by PyGithub (but
github.GithubException.BadAttributeException).Some other types of exceptions might be raised by underlying libraries, for example for network-related issues.
- property status: int
The status returned by the Github API.
- property data: Any
The (decoded) data returned by the Github API.
- property headers: dict[str, str] | None
The headers returned by the Github API.
- exception github.GithubException.BadCredentialsException(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Exception raised in case of bad credentials (when Github API replies with a 401 or 403 HTML status)
- exception github.GithubException.UnknownObjectException(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Exception raised when a non-existing object is requested (when Github API replies with a 404 HTML status)
- exception github.GithubException.BadUserAgentException(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Exception raised when request is sent with a bad user agent header (when Github API replies with a 403 bad user agent HTML status)
- exception github.GithubException.RateLimitExceededException(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Exception raised when the rate limit is exceeded (when Github API replies with a 403 rate limit exceeded HTML status)
- exception github.GithubException.BadAttributeException(actualValue: Any, expectedType: dict[tuple[type[str], type[str]], type[dict]] | tuple[type[str], type[str]] | list[type[dict]] | list[tuple[type[str], type[str]]], transformationException: Exception | None)
Exception raised when Github returns an attribute with the wrong type.
- property actual_value: Any
The value returned by Github.
- property expected_type: list[type[dict]] | tuple[type[str], type[str]] | dict[tuple[type[str], type[str]], type[dict]] | list[tuple[type[str], type[str]]]
The type PyGithub expected.
- property transformation_exception: Exception | None
The exception raised when PyGithub tried to parse the value.
- exception github.GithubException.TwoFactorException(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Exception raised when Github requires a onetime password for two-factor authentication.
- exception github.GithubException.IncompletableObject(status: int, data: Any = None, headers: dict[str, str] | None = None, message: str | None = None)
Exception raised when we can not request an object from Github because the data returned did not include a URL.
Default argument
github.NotSet is a special value for arguments you don’t want to provide. You should not have to manipulate it directly, because it’s the default value of all parameters accepting it. Just note that it is different from None, which is an allowed value for some parameters.
Pagination
- class github.PaginatedList.PaginatedList
This class abstracts the pagination of the REST API and the GraphQl API.
You can simply enumerate through instances of this class:
for repo in user.get_repos(): print(repo.name)
If you want to know the total number of items in the list:
print(user.get_repos().totalCount)
You can also index them or take slices:
second_repo = user.get_repos()[1] first_repos = user.get_repos()[:10]
If you want to iterate in reversed order, just do:
for repo in reversed(user.get_repos()): print(repo.name)
And if you really need it, you can explicitly access a specific page:
repos = user.get_repos() assert repos.is_rest, "get_page not supported by the GraphQL API" some_repos = repos.get_page(0) some_other_repos = repos.get_page(3)
Input classes
- class github.InputFileContent.InputFileContent(content: str, new_name: str | _NotSetType = NotSet)
This class represents InputFileContents.
- class github.InputGitAuthor.InputGitAuthor(name: str, email: str, date: str | _NotSetType = NotSet)
This class represents InputGitAuthors.
- class github.InputGitTreeElement.InputGitTreeElement(path: str, mode: str, type: str, content: str | _NotSetType = NotSet, sha: str | None | _NotSetType = NotSet)
This class represents InputGitTreeElements.
Raw Requests
If you need to make requests to APIs not yet supported by PyGithub,
you can use the Requester object directly, available as object.requester on most PyGithub objects.
- class github.Requester.Requester(auth: Auth | None, base_url: str, timeout: int, user_agent: str, per_page: int, verify: bool | str, retry: int | Retry | None, pool_size: int | None, seconds_between_requests: float | None = None, seconds_between_writes: float | None = None, lazy: bool = False)
- NEW_DEBUG_FRAME(requestHeader: dict[str, str]) None
Initialize a debug frame with requestHeader Frame count is updated and will be attached to respond header The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data] Some of them may be None
- DEBUG_ON_RESPONSE(statusCode: int, responseHeader: dict[str, str | int], data: str) None
Update current frame with response Current frame index will be attached to responseHeader.
- close() None
Close the connection to the server.
- property kwargs: dict[str, Any]
Returns arguments required to recreate this Requester with Requester.__init__, as well as with MainClass.__init__ and GithubIntegration.__init__.
- withAuth(auth: Auth | None) Requester
Create a new requester instance with identical configuration but the given authentication method.
- Parameters:
auth – authentication method
- Returns:
new Requester instance
- withLazy(lazy: bool | _NotSetType) Requester
Create a new requester instance with identical configuration but the given lazy setting.
- Parameters:
lazy – if True, completable objects created from this instance are lazy, as well as completable objects created from those, and so on.
- Returns:
new Requester instance if is_defined(lazy) and lazy != self.is_lazy, this instance otherwise
- requestJsonAndCheck(verb: str, url: str, parameters: dict[str, Any] | None = None, headers: dict[str, str] | None = None, input: Any | None = None, follow_302_redirect: bool = False) tuple[dict[str, Any], Any]
Send a request with JSON body.
- Parameters:
input – request body, serialized to JSON if specified
- Returns:
(headers: dict, JSON Response: Any)- Raises:
GithubExceptionfor error status codes
- requestMultipartAndCheck(verb: str, url: str, parameters: dict[str, Any] | None = None, headers: dict[str, Any] | None = None, input: dict[str, str] | None = None) tuple[dict[str, Any], dict[str, Any] | None]
Send a request with multi-part-encoded body.
- Parameters:
input – request body, will be multi-part encoded if specified
- Returns:
(headers: dict, JSON Response: Any)- Raises:
GithubExceptionfor error status codes
- requestBlobAndCheck(verb: str, url: str, parameters: dict[str, str] | None = None, headers: dict[str, str] | None = None, input: str | None = None, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None) tuple[dict[str, Any], dict[str, Any]]
Send a request with a file for the body.
- Parameters:
input – path to a file to use for the request body
- Returns:
(headers: dict, JSON Response: Any)- Raises:
GithubExceptionfor error status codes
- graphql_query(query: str, variables: dict[str, Any]) tuple[dict[str, Any], dict[str, Any]]
Queries the GraphQL API.
- Parameters:
query – GraphQL query
variables – GraphQL variables
- Returns:
(headers: dict, JSON Response: dict)- Raises:
GithubExceptionfor error status codes
- graphql_query_class(query: str, variables: dict[str, Any], data_path: list[str], klass: type[T_gh]) T_gh
Queries the GraphQL API, extracts data from a given path, populates and returns a PyGithub class instance.
Uses
graphql_query()to query the GraphQL API.- Parameters:
query – GraphQL query
data_path – GraphQL path in the response to extract the properties for the class to return
klass – PyGithub class
- Returns:
PyGithub class instance
- Raises:
GithubExceptionfor error status codes
- graphql_node(node_id: str, output_schema: str, node_type: str) tuple[dict[str, Any], dict[str, Any]]
Fetches a GraphQL node by id in the give schema.
This sends the following GraphQL request:
query Q($id. ID!) { node(id: $id) { __typename ... on <node_type> { <output_schema> } } }- Parameters:
node_id – GraphQL node id
output_schema – The schema of the retrieved properties of the node, without enclosing curly brackets
node_type – The GraphQL node type
- Returns:
(headers: dict, JSON Response: dict)- Raises:
GithubExceptionfor error status codes
- graphql_node_class(node_id: str, output_schema: str, klass: type[T_gh], node_type: str | None = None) T_gh
Fetches a GraphQL node by id in the give schema, and returns a PyGithub instance of the given class populated with the retrieved properties.
Uses
graph_node()to retrieve the GraphQl node.- Parameters:
node_id – GraphQL node id
output_schema – The schema of the retrieved properties of the node, without enclosing curly brackets
klass – PyGithub class
node_type – Optional GraphQL node type, defaults to the name of the PyGithub class
- Returns:
PyGithub class instance
- Raises:
GithubExceptionfor error status codes
- graphql_named_mutation(mutation_name: str, mutation_input: dict[str, Any], output_schema: str) tuple[dict[str, Any], dict[str, Any]]
Send a GraphQL mutation to the GraphQL API.
This sends the following GraphQL request:
mutation Mutation($input: MutationNameInput!) { mutationName(input: $input) { <output_schema> } }Uses
graphql_query()to send the request to the GraphQL API.- Parameters:
mutation_name – name of the mutation
mutation_input – input data for the mutation
output_schema – The schema of the retrieved properties of the mutation, without enclosing curly brackets
- Returns:
(headers: dict, JSON Response: dict)- Raises:
GithubExceptionfor error status codes
- graphql_named_mutation_class(mutation_name: str, mutation_input: dict[str, Any], output_schema: str, item: str, klass: type[T_gh]) T_gh
Send a GraphQL mutation to the GraphQL API, populates and returns a PyGithub class instance.
Uses
graphql_named_mutation()to send the mutation to the GraphQL API.- Parameters:
mutation_name – name of the mutation
mutation_input – input data for the mutation
output_schema – The schema of the retrieved properties of the mutation, without enclosing curly brackets
item – property in the response to extract the properties for the class to return
- Returns:
PyGithub class instance
- Raises:
GithubExceptionfor error status codes
- getFile(url: str, path: str, parameters: dict[str, Any] | None = None, headers: dict[str, str] | None = None, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None, chunk_size: int | None = 1) None
GET a file from the server and save it to the given path, which includes the filename.
- getStream(url: str, parameters: dict[str, Any] | None = None, headers: dict[str, str] | None = None, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None, chunk_size: int | None = 1) tuple[int, dict[str, Any], Iterator]
GET a stream from the server.
:returns:
(status, headers, stream_chunk_iterator)
- requestJson(verb: str, url: str, parameters: dict[str, Any] | None = None, headers: dict[str, Any] | None = None, input: Any | None = None, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None, follow_302_redirect: bool = False) tuple[int, dict[str, Any], str]
Send a request with JSON input.
- Parameters:
input – request body, will be serialized as JSON
:returns:
(status, headers, body)
- requestMultipart(verb: str, url: str, parameters: dict[str, Any] | None = None, headers: dict[str, Any] | None = None, input: dict[str, str] | None = None, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None) tuple[int, dict[str, Any], str]
Send a request with multi-part encoding.
- Parameters:
input – request body, will be serialized as multipart form data
:returns:
(status, headers, body)
- requestBlob(verb: str, url: str, parameters: dict[str, str] | None = None, headers: dict[str, str] | None = None, input: str | None = None, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None) tuple[int, dict[str, Any], str]
Send a request with a file as request body.
- Parameters:
input – path to a local file to use for request body
:returns:
(status, headers, body)
- requestMemoryBlobAndCheck(verb: str, url: str, parameters: Any, headers: dict[str, Any], file_like: BinaryIO, cnx: HTTPRequestsConnectionClass | HTTPSRequestsConnectionClass | None = None) tuple[dict[str, Any], Any]
Send a request with a binary file-like for the body.
- Parameters:
file_like – file-like object to use for the request body
- Returns:
(headers: dict, JSON Response: Any)- Raises:
GithubExceptionfor error status codes