### Install Requests from source Source: https://requests.readthedocs.io/en/latest/user/install After obtaining the source code, change into the requests directory and install it into site-packages using pip. ```shell $ cd requests $ python -m pip install . ``` -------------------------------- ### Install Requests with pip Source: https://requests.readthedocs.io/en/latest/user/install Installs the Requests library using pip. Run this command in your terminal to install the package. ```shell $ python -m pip install requests ``` -------------------------------- ### requests.request() GET example Source: https://requests.readthedocs.io/en/latest/api Shows the basic usage of requests.request() with a GET request. The output is a Response object with status code 200. ```python >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') >>> req ``` -------------------------------- ### Usage example for HTTPAdapter Source: https://requests.readthedocs.io/en/latest/_modules/requests/adapters Shows how to create a Session, mount an HTTPAdapter with max_retries=3, and use it for HTTP requests. ```python >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) ``` -------------------------------- ### Install SOCKS proxy dependencies Source: https://requests.readthedocs.io/en/latest/user/advanced Install the optional dependencies required for SOCKS proxy support. This feature is new in version 2.10.0. ```bash $ python -m pip install 'requests[socks]' ``` -------------------------------- ### Prepare and modify a request with Session.prepare_request() Source: https://requests.readthedocs.io/en/latest/user/advanced Use this recipe to prepare a request with Session.prepare_request() so that Session-level state (like cookies) is applied. It then sends the prepared request with the same parameters as the previous example. ```python from requests import Request, Session s = Session() req = Request('GET', url, data=data, headers=headers) prepped = s.prepare_request(req) # do something with prepped.body prepped.body = 'Seriously, send exactly these bytes.' # do something with prepped.headers prepped.headers['Keep-Dead'] = 'parrot' resp = s.send(prepped, stream=stream, verify=verify, proxies=proxies, cert=cert, timeout=timeout ) print(resp.status_code) ``` -------------------------------- ### Import the Requests module Source: https://requests.readthedocs.io/en/latest/user/quickstart Start by importing the requests module to use its API. ```python >>> import requests ``` -------------------------------- ### Timeout example with requests.get Source: https://requests.readthedocs.io/en/latest/user/quickstart Shows the exception raised when a request exceeds the timeout. The example uses a very short timeout (0.001 seconds) to demonstrate the failure. The traceback shows a requests.exceptions.Timeout error, indicating the server did not respond within the specified time. ```python >>> requests.get('https://github.com/', timeout=0.001) Traceback (most recent call last): File "", line 1, in requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001) ``` -------------------------------- ### Basic requests.Session usage Source: https://requests.readthedocs.io/en/latest/api Creates a requests.Session and sends a GET request to httpbin.org, returning a Response object with status 200. Use this to demonstrate basic session usage with cookie persistence and connection pooling. ```python >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') ``` -------------------------------- ### Enable redirects for HEAD with allow_redirects=True Source: https://requests.readthedocs.io/en/latest/user/quickstart Enable redirection for HEAD requests using `allow_redirects=True`. The example shows the final URL and the history containing the 301 response. ```python >>> r = requests.head('http://github.com/', allow_redirects=True) >>> r.url 'https://github.com/' >>> r.history [] ``` -------------------------------- ### Session.get(url, params=None, **kwargs) Source: https://requests.readthedocs.io/en/latest/api Sends a GET request. Returns a Response object. ```APIDOC ## Session.get(url, params=None, **kwargs) ### Description Sends a GET request. Returns a Response object. ### Method get ### Endpoint Session.get(url, params=None, **kwargs) ### Parameters #### Path Parameters - **url** (UriType) - Required - URL for the new Request object. #### Query Parameters - **params** (ParamsType) - Optional - Dictionary, list of tuples or bytes to send in the query string for the Request. - **kwargs** (GetKwargs) - Optional - Optional arguments that request takes. ### Response #### Success Response - **Response** (requests.Response) - The response object. ``` -------------------------------- ### Send cookies with requests.get Source: https://requests.readthedocs.io/en/latest/user/quickstart Send custom cookies to the server using the `cookies` parameter. The example passes a dictionary of cookies and shows the server's response. ```python >>> url = 'https://httpbin.org/cookies' >>> cookies = dict(cookies_are='working') >>> r = requests.get(url, cookies=cookies) >>> r.text '{"cookies": {"cookies_are": "working"}}' ``` -------------------------------- ### Create and prepare a requests.Request Source: https://requests.readthedocs.io/en/latest/api Shows how to create a Request object, prepare it, and see the resulting PreparedRequest. The output is shown as the last line. ```python >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() ``` -------------------------------- ### Access response cookies Source: https://requests.readthedocs.io/en/latest/user/quickstart Access cookies from a response using the `cookies` attribute. The example shows retrieving a cookie value by name after a GET request. ```python >>> url = 'http://example.com/some/cookie/setting/url' >>> r = requests.get(url) >>> r.cookies['example_cookie_name'] 'example_cookie_value' ``` -------------------------------- ### Check response status code with requests.get Source: https://requests.readthedocs.io/en/latest/user/quickstart Checks the HTTP status code of a response. The example shows that a successful GET request returns 200. ```python >>> r = requests.get('https://httpbin.org/get') >>> r.status_code 200 ``` -------------------------------- ### Digest Authentication with HTTPDigestAuth Source: https://requests.readthedocs.io/en/latest/user/authentication Use HTTPDigestAuth from requests.auth to authenticate a GET request with digest authentication. The example shows the expected response status code 200. ```python >>> from requests.auth import HTTPDigestAuth >>> url = 'https://httpbin.org/digest-auth/auth/user/pass' >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass')) ``` -------------------------------- ### Create and send a PreparedRequest with requests Source: https://requests.readthedocs.io/en/latest/api Shows how to create a PreparedRequest from a Request object and send it through a Session. The output demonstrates the PreparedRequest representation and the resulting Response object. ```python >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> r >>> s = requests.Session() >>> s.send(r) ``` -------------------------------- ### Disable redirects with allow_redirects=False Source: https://requests.readthedocs.io/en/latest/user/quickstart Disable redirection for GET, OPTIONS, POST, PUT, PATCH, or DELETE using `allow_redirects=False`. The example shows a 301 status and an empty history. ```python >>> r = requests.get('http://github.com/', allow_redirects=False) >>> r.status_code 301 >>> r.history [] ``` -------------------------------- ### Use RequestsCookieJar to send cookies Source: https://requests.readthedocs.io/en/latest/user/quickstart Use a `RequestsCookieJar` to manage cookies across domains and paths. The example sets cookies with domain and path, then sends them with a GET request. ```python >>> jar = requests.cookies.RequestsCookieJar() >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies') >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere') >>> url = 'https://httpbin.org/cookies' >>> r = requests.get(url, cookies=jar) >>> r.text '{"cookies": {"tasty_cookie": "yum"}}' ``` -------------------------------- ### Track redirection history with Response.history Source: https://requests.readthedocs.io/en/latest/user/quickstart Track redirection history with the `history` property. The example shows a GET request that follows a redirect from HTTP to HTTPS, with the history containing the 301 response. ```python >>> r = requests.get('http://github.com/') >>> r.url 'https://github.com/' >>> r.status_code 200 >>> r.history [] ``` -------------------------------- ### Create image from binary response with PIL and BytesIO Source: https://requests.readthedocs.io/en/latest/user/quickstart Shows how to create an image from binary data returned by a request, using PIL.Image and io.BytesIO with r.content. ```python >>> from PIL import Image >>> from io import BytesIO >>> i = Image.open(BytesIO(r.content)) ``` -------------------------------- ### Send a request with full parameter support Source: https://requests.readthedocs.io/en/latest/_modules/requests/sessions Constructs, prepares, and sends a Request, returning a Response. Supports optional parameters for query params, data, JSON, headers, cookies, files, auth, timeout, redirects, proxies, hooks, streaming, TLS verification, and client certificates. ```python def request( self, method: str, url: _t.UriType, params: _t.ParamsType = None, data: _t.DataType = None, headers: _t.HeadersType = None, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, files: _t.FilesType = None, auth: _t.AuthType = None, timeout: _t.TimeoutType = None, allow_redirects: bool = True, proxies: dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, stream: bool | None = None, verify: _t.VerifyType | None = None, cert: _t.CertType | None = None, json: _t.JsonType | None = None, ) -> Response: """Constructs a :class:`Request `, prepares it and sends it. Returns :class:`Response ` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) ` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param hooks: (optional) Dictionary mapping hook name to one event or list of events, event must be callable. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ if isinstance(url, bytes): url = url.decode("utf-8") # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) assert _is_prepared(prep) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { "timeout": timeout, "allow_redirects": allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp ``` -------------------------------- ### Custom authentication with requests.auth.AuthBase Source: https://requests.readthedocs.io/en/latest/user/authentication Subclass requests.auth.AuthBase and implement __call__() to create a custom authentication handler. Attach it to a request with the auth parameter; the handler is invoked during request setup. The example shows a minimal handler that returns the request unchanged and a successful response. ```python >>> import requests >>> class MyAuth(requests.auth.AuthBase): ... def __call__(self, r): ... # Implement my authentication ... return r ... >>> url = 'https://httpbin.org/get' >>> requests.get(url, auth=MyAuth()) ``` -------------------------------- ### Configure proxies via environment variables Source: https://requests.readthedocs.io/en/latest/user/advanced Configure proxies via standard environment variables `http_proxy`, `https_proxy`, `no_proxy`, and `all_proxy` (uppercase variants also supported). Set only the ones relevant to your needs. ```bash $ export HTTP_PROXY="http://10.10.1.10:3128" $ export HTTPS_PROXY="http://10.10.1.10:1080" $ export ALL_PROXY="socks5://10.10.1.10:3434" $ python >>> import requests >>> requests.get('http://example.org') ``` -------------------------------- ### PreparedRequest.__init__ constructor Source: https://requests.readthedocs.io/en/latest/_modules/requests/models Initializes a PreparedRequest with default None values for method, URL, headers, cookies, body, hooks, and body position. The hooks are set to default_hooks(). ```python def __init__(self) -> None: #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # type: ignore[assignment] # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None ``` -------------------------------- ### Session.merge_environment_settings(url, proxies, stream, verify, cert) Source: https://requests.readthedocs.io/en/latest/api Check the environment and merge it with some settings. ```APIDOC ## Session.merge_environment_settings(url, proxies, stream, verify, cert) ### Description Check the environment and merge it with some settings. ### Method merge_environment_settings ### Endpoint Session.merge_environment_settings(url, proxies, stream, verify, cert) ### Parameters #### Path Parameters - **url** (str) - Required - The URL. - **proxies** (dict[str, str] | None) - Required - Proxies to use. - **stream** (bool | None) - Required - Whether to stream. - **verify** (VerifyType | None) - Required - SSL verification setting. - **cert** (CertType) - Required - SSL client certificate. ### Response #### Success Response - **settings** (dict) - The merged settings. ``` -------------------------------- ### requests.get(url, params=None, **kwargs) → Response Source: https://requests.readthedocs.io/en/latest/api Sends a GET request. This is a convenience method that calls requests.request with the GET method. ```APIDOC ## requests.get(url, params=None, **kwargs) → Response ### Description Sends a GET request. This is a convenience method that calls `requests.request` with the `GET` method. ### Method `get` ### Endpoint `requests.get(url, params=None, **kwargs)` ### Parameters - **url** (UriType) - Required - URL for the new `Request` object. - **params** (optional) - Dictionary, list of tuples or bytes to send in the query string. - **kwargs** - Optional arguments that `request` takes. ### Request Example ```python import requests resp = requests.get('https://httpbin.org/get') ``` ### Response Returns a `Response` object. #### Response Example ```python ``` ``` -------------------------------- ### request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None) Source: https://requests.readthedocs.io/en/latest/api Constructs a Request, prepares it and sends it. Returns a Response object. ```APIDOC ## request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None) ### Description Constructs a `Request`, prepares it and sends it. Returns `Response` object. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters - **method** (str) - Required - method for the new `Request` object. - **url** (UriType) - Required - URL for the new `Request` object. - **params** (ParamsType) - Optional - Dictionary or bytes to be sent in the query string for the `Request`. - **data** (DataType) - Optional - Dictionary, list of tuples, bytes, or file-like object to send in the body of the `Request`. - **json** (JsonType) - Optional - json to send in the body of the `Request`. - **headers** (HeadersType) - Optional - Dictionary of HTTP Headers to send with the `Request`. - **cookies** (RequestsCookieJar | CookieJar | dict[str, str]) - Optional - Dict or CookieJar object to send with the `Request`. - **files** (FilesType) - Optional - Dictionary of `'filename': file-like-objects` for multipart encoding upload. - **auth** (AuthType) - Optional - Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. - **timeout** (float or tuple) - Optional - How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple. - **allow_redirects** (bool) - Optional - Set to True by default. - **proxies** (dict[str, str]) - Optional - Dictionary mapping protocol or protocol and hostname to the URL of the proxy. - **hooks** (HooksInputType) - Optional - Dictionary mapping hook name to one event or list of events, event must be callable. - **stream** (bool) - Optional - whether to immediately download the response content. Defaults to `False`. - **verify** (VerifyType) - Optional - Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to `True`. When set to `False`, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to `False` may be useful during local development or testing. - **cert** (CertType) - Optional - if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair. ### Return Type requests.Response ### Response #### Success Response - **Response** (requests.Response) - The response object returned by the request. #### Response Example N/A (not provided in source) ``` -------------------------------- ### Mount an HTTPAdapter with max_retries=3 Source: https://requests.readthedocs.io/en/latest/api Shows how to create a Session, attach an HTTPAdapter with max_retries=3, and mount it for the http:// scheme. The max_retries parameter applies only to failed DNS lookups, socket connections, and connection timeouts, not to requests where data has reached the server. ```python >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) ``` -------------------------------- ### Session.get method Source: https://requests.readthedocs.io/en/latest/_modules/requests/sessions Sends a GET request via the Session object. Sets allow_redirects to True by default and delegates to self.request with the GET method. ```python def get( self, url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs], ) -> Response: r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return self.request("GET", url, params=params, **kwargs) ``` -------------------------------- ### Request.__init__ constructor Source: https://requests.readthedocs.io/en/latest/_modules/requests/models Initializes a Request object with optional method, URL, headers, files, data, params, auth, cookies, hooks, and json. Defaults empty containers for data, files, headers, params, and hooks. Registers any provided hooks and stores all parameters as instance attributes. ```python def __init__( self, method: str | None = None, url: _t.UriType | None = None, headers: _t.HeadersType = None, files: _t.FilesType = None, data: _t.DataType = None, params: _t.ParamsType = None, auth: _t.AuthType = None, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, json: _t.JsonType = None, ) -> None: # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for k, v in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self) -> str: return f"" ``` -------------------------------- ### Send a GET request with requests.get() Source: https://requests.readthedocs.io/en/latest/user/advanced Creates a Response object by sending a GET request to Wikipedia. The response contains the server's reply and the original Request object. ```python >>> r = requests.get('https://en.wikipedia.org/wiki/Monty_Python') ``` -------------------------------- ### Install Requests with use_chardet_on_py3 extra Source: https://requests.readthedocs.io/en/latest/community/updates Install Requests with the use_chardet_on_py3 extra to force the chardet dependency instead of charset_normalizer on Python 3. This extra is available in Requests 2.26.0 and later. ```shell pip install "requests[use_chardet_on_py3]" ``` -------------------------------- ### Request class definition with usage example Source: https://requests.readthedocs.io/en/latest/_modules/requests/models The Request class inherits from RequestHooksMixin and is used to prepare a PreparedRequest. The docstring includes a usage example showing how to create and prepare a request. ```python class Request(RequestHooksMixin): """A user-created :class:`Request ` object. Used to prepare a :class:`PreparedRequest `, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() """ hooks: dict[str, list[_t.HookType]] method: str | None url: _t.UriType | None headers: Mapping[str, str | bytes] files: _t.FilesType data: _t.DataType json: _t.JsonType params: _t.ParamsType auth: _t.AuthType cookies: RequestsCookieJar | CookieJar | dict[str, str] | None ``` -------------------------------- ### Session basic usage and context manager Source: https://requests.readthedocs.io/en/latest/_modules/requests/sessions Shows basic usage of the Session class: creating a session and making a GET request, and using the session as a context manager. The output is a Response object with status 200. ```python >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') ``` ```python >>> with requests.Session() as s: ... s.get('https://httpbin.org/get') ``` -------------------------------- ### Basic GET request with authentication and response inspection Source: https://requests.readthedocs.io/en/latest Shows the basic usage of Requests: making a GET request with basic authentication, then accessing status code, headers, encoding, text, and JSON response. The output demonstrates typical response attributes and JSON parsing. ```python >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass')) >>> r.status_code 200 >>> r.headers['content-type'] 'application/json; charset=utf8' >>> r.encoding 'utf-8' >>> r.text '{"type":"User"...' >>> r.json() {'private_gists': 419, 'total_private_repos': 77, ...} ``` -------------------------------- ### rebuild_method: adjust HTTP method on redirect (303, 302, 301) Source: https://requests.readthedocs.io/en/latest/_modules/requests/sessions Changes the HTTP method during redirects according to RFC 7231 and browser behavior: 303 and 302 become GET (unless HEAD), and 301 turns POST into GET. Updates the prepared request's method. ```python def rebuild_method( self, prepared_request: PreparedRequest, response: Response ) -> None: """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != "HEAD": method = "GET" # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != "HEAD": method = "GET" # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == "POST": method = "GET" prepared_request.method = method ``` -------------------------------- ### Session.prepare_request(request) Source: https://requests.readthedocs.io/en/latest/api Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session. ```APIDOC ## Session.prepare_request(request) ### Description Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session. ### Method prepare_request ### Endpoint Session.prepare_request(request) ### Parameters #### Path Parameters - **request** (Request) - Required - Request instance to prepare with this session's settings. ### Response #### Success Response - **prepared_request** (PreparedRequest) - The prepared request. ``` -------------------------------- ### mount method Source: https://requests.readthedocs.io/en/latest/_modules/requests/sessions Registers an adapter for a URL prefix, moving shorter-prefix entries to the end to maintain descending order by prefix length. ```python def mount(self, prefix: str, adapter: BaseAdapter) -> None: """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key) ``` -------------------------------- ### Prepare request with merged settings Source: https://requests.readthedocs.io/en/latest/_modules/requests/sessions Prepares a request by merging authentication, headers, params, cookies, and hooks into a PreparedRequest. Uses netrc authentication when trust_env is enabled and no explicit auth is set. ```python # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(url) p = PreparedRequest() p.prepare( method=method.upper(), url=url, files=request.files, data=request.data, json=request.json, headers=merge_setting( request.headers, self.headers, dict_class=CaseInsensitiveDict ), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p ``` -------------------------------- ### GET a GitHub commit and parse JSON response Source: https://requests.readthedocs.io/en/latest/user/advanced Retrieves a specific GitHub commit via the GET verb, checks the response status and content type, then parses the JSON body into a Python dict. The output shows the commit's keys, committer info, and message. Use this pattern when you need to fetch and inspect a resource from a REST API. ```python >>> import requests >>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad') ``` ```python >>> if r.status_code == requests.codes.ok: ... print(r.headers['content-type']) ... application/json; charset=utf-8 ``` ```python >>> commit_data = r.json() >>> print(commit_data.keys()) ['committer', 'author', 'url', 'tree', 'sha', 'parents', 'message'] >>> print(commit_data['committer']) {'date': '2012-05-10T11:10:50-07:00', 'email': 'me@kennethreitz.com', 'name': 'Kenneth Reitz'} >>> print(commit_data['message']) makin' history ```