Package: ghreq
GitHub|PyPI|Issues|Changelogghreqis a simple wrapper aroundrequestswith various customizations
aimed at working with the GitHub REST API.  Notable features include:When making a request, you only need to specify the part of the URL after the
API base URL.  You can even construct objects for making requests with a URL
baked in.All request methods return decoded JSON by default.4xx and 5xx responses are automatically raised as errors without needing to
callraise_for_status().Errors raised for 4xx and 5xx responses include the body of the response in
the error message.Support for iterating over paginated resultsTheAcceptandX-GitHub-Api-Versionheaders are automatically set to
their recommended values.FollowsGitHub’s recommendations for dealing with rate limits, including
waiting between mutating requests and waiting & retrying in response to
rate-limit errorsAutomatic retrying on 5xx errors with exponential backoffInstallationghreqrequires Python 3.8 or higher.  Just usepipfor Python 3 (You have pip, right?) to install it:python3 -m pip install ghreqExamplefromghreqimportClientwithClient(token="your-api-token-here")asclient:user=client.get("/user")print("I am user",user["login"])print()print("Here are my repositories:")forrepoinclient.paginate("/user/repos"):print(repo["full_name"])print()hello_world=client/"repos"/"octocat"/"Hello-World"details=hello_world.get()print(f"{details['full_name']}has been starred{details['stargazers_count']}times.")print("Here is the first page of its open issues & PRs:")forissuein(hello_world/"issues").get():print(f"#{issue['number']}:{issue['title']}")APIClientClassclassClient:def__init__(*,token:str|None=None,api_url:str=DEFAULT_API_URL,session:requests.Session|None=None,set_headers:bool|None=None,user_agent:str|None=None,accept:str|None=DEFAULT_ACCEPT,api_version:str|None=DEFAULT_API_VERSION,mutation_delay:float=1.0,retry_config:RetryConfig|None=None,)An HTTP client class for interacting with the GitHub REST API (or sufficiently
similar APIs).Constructor arguments:tokenThe GitHub access token, if any, to use to authenticate to the API.This argument is ignored ifset_headersisFalseor defaulted toFalse.api_urlThe base URL to which to append paths passed to the request methodssessionA pre-configuredrequests.Sessioninstance to use for making requests.
If no session is supplied, a new session is instantiated.set_headersWhether to set various headers for requests made via the session.  Ifset_headersisNone, it is defaulted toTrueifsessionisNoneand toFalseotherwise.Ifset_headersisTrueor defaulted toTrue, the following
request headers are set on the session:Accept(ifacceptis non-None)Authorization(set to"Bearer {token}"iftokenis
non-None)User-Agent(ifuser_agentis non-None)X-GitHub-Api-Version(ifapi_versionis non-None)any additional headers included inheadersIfset_headersisFalseor defaulted toFalse, thenClientdoes not set any headers on the session, and the other header-related
parameters are ignored.user_agentA user agent string to include in the headers of requests.  If not set, therequestslibrary’s default user agent is used.This argument is ignored ifset_headersisFalseor defaulted toFalse.acceptValue to set theAcceptheader to.  Can be set toNoneto not set
the header at all.This argument is ignored ifset_headersisFalseor defaulted toFalse.api_versionValue to set theX-GitHub-Api-Versionheader to.  Can be set toNoneto not set the header at all.This argument is ignored ifset_headersisFalseor defaulted toFalse.headersOptional mapping of additional headers to set on the session after setting
all other headers.This argument is ignored ifset_headersisFalseor defaulted toFalse.mutation_delayWhen making aPOST,PATCH,PUT, orDELETErequest, if the
time since the last such request is fewer thanmutation_delayseconds,
then the client will sleep long enough to make up the difference before
performing the request.retry_configConfiguration for the request retrying mechanism.  If not set, aRetryConfiginstance with all default attributes will be used; see
below.Clientinstances can be used as context managers, in which case they close
their internalrequests.Sessioninstances on exit (regardless of whether
the session was user-provided or not).AClientinstance can be “divided” by a string (e.g.,client / "user")
to obtain anEndpointinstance that makes requests to the URL formed fromapi_urland the “divisor”; see below.Client.request(method:str,path:str,json:Any=None,*,params:ParamsType=None,headers:HeadersType=None,data:DataType=None,timeout:TimeoutType=None,allow_redirects:bool=True,stream:bool=False,raw:bool=False,)->AnyPerform an HTTP request with the given method/verb.  Ifpathbegins withhttp://orhttps://, it is used as-is for the URL of the request.
Otherwise,pathis appended to theapi_urlvalue supplied to the
constructor, with a forward slash inserted in between if there isn’t one
present already.  Thus, given aclientconstructed with the defaultapi_url, the following are equivalent:client.request("GET","user")client.request("GET","/user")client.request("GET","https://api.github.com/user")If the request is successful, the body is decoded as JSON and returned; if the
body is empty (except possibly for whitespace),Noneis returned.  To make
the method return the actualrequests.Responseobject instead, passraw=True(orstream=True, which implies it).The remaining arguments have the same meaning as inrequests.If the request fails, it may be retried with exponentially increasing wait
times between attempts; see the documentation ofRetryConfigbelow.  If all
retries are exhausted without success, the exception from the final request is
raised.If the request fails with a 4xx or 5xx response, aPrettyHTTPErroris
raised.Client.get(path:str,*,params:ParamsType=None,headers:HeadersType=None,timeout:TimeoutType=None,stream:bool=False,raw:bool=False,)->AnyPerform aGETrequest.  See the documentation ofrequest()for more
information.Client.post(path:str,json:Any=None,*,params:ParamsType=None,headers:HeadersType=None,data:DataType=None,timeout:TimeoutType=None,stream:bool=False,raw:bool=False,)->AnyPerform aPOSTrequest.  See the documentation ofrequest()for more
information.Client.put(path:str,json:Any=None,*,params:ParamsType=None,headers:HeadersType=None,data:DataType=None,timeout:TimeoutType=None,stream:bool=False,raw:bool=False,)->AnyPerform aPUTrequest.  See the documentation ofrequest()for more
information.Client.patch(path:str,json:Any=None,*,params:ParamsType=None,headers:HeadersType=None,data:DataType=None,timeout:TimeoutType=None,stream:bool=False,raw:bool=False,)->AnyPerform aPATCHrequest.  See the documentation ofrequest()for more
information.Client.delete(path:str,json:Any=None,*,params:ParamsType=None,headers:HeadersType=None,data:DataType=None,timeout:TimeoutType=None,stream:bool=False,raw:bool=False,)->AnyPerform aDELETErequest.  See the documentation ofrequest()for more
information.Client.paginate(path:str,*,params:ParamsType=None,headers:HeadersType=None,timeout:TimeoutType=None,raw:Literal[True,False]=False,)->IteratorPerform a series of paginatedGETrequests and yield the items from each
page.  Thepathandparamsarguments are only used for the initial
request; further requests follow the “next” entry in theLinkheader of
each response.The bodies of the responses must be either JSON lists (in which case the list
elements are yielded) or JSON objects in which exactly one field is a list (in
which case the elements of that list are yielded); otherwise, an error occurs.IfrawisTrue, then instead of yielding each page’s items, the
returned iterator will yield each page as arequests.Responseobject.Client.close()->NoneClose the client’s internalrequests.Session.  No more request methods may
be called afterwards.This method is called automatically on exit when usingClientas a context
manager.EndpointClassclassEndpoint:client:Clienturl:strA combination of aClientinstance and a URL.Endpointhasrequest(),get(),post(),put(),patch(),delete(), andpaginate()methods that work the same way as forClient, except thatEndpoint’s methods do not takepatharguments; instead, they make
requests to the stored URL.  This is useful if you find yourself making
requests to the same URL and/or paths under the same URL over & over.AnEndpointinstance is constructed by applying the/(division)
operator to aClientorEndpointinstance on the left and a string on
the right.  If the string begins withhttp://orhttps://, it is used
as-is for the URL of the resultingEndpoint.  Otherwise, the string is
appended to theapi_urlorurlattribute of the object on the left,
with a forward slash inserted in between if there isn’t one present already.
Thus, given aclientconstructed with the defaultapi_url, the
following are equivalent:client.get("repos/octocat/hello-world")(client/"repos/octocat/hello-world").get()(client/"repos"/"octocat"/"hello-world").get()RetryConfigClassclassRetryConfig:def__init__(retries:int=10,backoff_factor:float=1.0,backoff_base:float=1.25,backoff_jitter:float=0.0backoff_max:float=120.0,total_wait:float|None=300.0,retry_statuses:Container[int]=range(500,600),)A container for storing configuration forghreq’s retrying mechanism.  A
request is retried if (a) aresponse.RequestExceptionis raised that is not
aValueError(e.g., a connection or timeout error), (b) the server responds
with a 403 status code and either theRetry-Afterheader is present or the
body contains the string"rate limit", or (c) the server responds with a
status code listed inretry_statuses.When a request is retried, the client sleeps for increasing amounts of time
between repeated requests until either a non-retriable response is obtained,retriesretry attempts have been performed, or the total amount of time
elapsed since the start of the first request exceedstotal_wait, if set.The first retry happens after sleeping forbackoff_factor * 0.1seconds,
and subsequent retries happen after sleeping forbackoff_factor * backoff_base ** (retry_number - 1) + random.random() * backoff_jitterseconds, up to a maximum ofbackoff_maxper retry.  If aRetry-Afterorx-ratelimit-resetheader indicates a larger duration to sleep for, that
value is used instead.  If the duration indicated by such a header would result
in the next retry attempt being aftertotal_waitis exceeded, retrying
stops early.PrettyHTTPErrorClassclassPrettyHTTPError(requests.HTTPError)A subclass ofrequests.HTTPErrorraised automatically by the request
methods if a response with a 4xx or 5xx status code is received.  Unlike its
parent class, stringifying aPrettyHTTPErrorwill produce a string that
contains the body of the response; if the body was JSON, that JSON will be
pretty-printed.ConstantsDEFAULT_ACCEPT="application/vnd.github+json"The default value of theacceptargument to theClientconstructorDEFAULT_API_URL="https://api.github.com"The default value of theapi_urlargument to theClientconstructorDEFAULT_API_VERSION="2022-11-28"The default value of theapi_versionargument to theClientconstructorUtility Functionsmake_user_agent(name:str,version:str|None=None,url:str|None=None)->strCreate a user agent string with the given client name, optional version, and
optional URL.  The string will also include the version of therequestslibrary used and the implemention & version of Python.get_github_api_url()->strIf theGITHUB_API_URLenvironment variable is set to a nonempty string,
that string is returned; otherwise,DEFAULT_API_URLis returned.