advanced.rst
This file
Path
docs/user/advanced.rst
1,137 lines · 40.9 KiB
Last changed by
docs: Fix missing hook output in docs example (#7421)eggsortbefore adoptione8d2c01
History of this fileTake it
1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.78.. _session-objects:910Session Objects11---------------1213The Session object allows you to persist certain parameters across14requests. It also persists cookies across all requests made from the15Session instance, and will use ``urllib3``'s `connection pooling`_. So if16you're making several requests to the same host, the underlying TCP17connection will be reused, which can result in a significant performance18increase (see `HTTP persistent connection`_).1920A Session object has all the methods of the main Requests API.2122Let's persist some cookies across requests::2324 s = requests.Session()2526 s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')27 r = s.get('https://httpbin.org/cookies')2829 print(r.text)30 # '{"cookies": {"sessioncookie": "123456789"}}'313233Sessions can also be used to provide default data to the request methods. This34is done by providing data to the properties on a Session object::3536 s = requests.Session()37 s.auth = ('user', 'pass')38 s.headers.update({'x-test': 'true'})3940 # both 'x-test' and 'x-test2' are sent41 s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})424344Any dictionaries that you pass to a request method will be merged with the45session-level values that are set. The method-level parameters override session46parameters.4748Note, however, that method-level parameters will *not* be persisted across49requests, even if using a session. This example will only send the cookies50with the first request, but not the second::5152 s = requests.Session()5354 r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'5758 r = s.get('https://httpbin.org/cookies')59 print(r.text)60 # '{"cookies": {}}'616263If you want to manually add cookies to your session, use the64:ref:`Cookie utility functions <api-cookies>` to manipulate65:attr:`Session.cookies <requests.Session.cookies>`.6667Sessions can also be used as context managers::6869 with requests.Session() as s:70 s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')7172This will make sure the session is closed as soon as the ``with`` block is73exited, even if unhandled exceptions occurred.747576.. admonition:: Remove a Value From a Dict Parameter7778 Sometimes you'll want to omit session-level keys from a dict parameter. To79 do this, you simply set that key's value to ``None`` in the method-level80 parameter. It will automatically be omitted.8182All values that are contained within a session are directly available to you.83See the :ref:`Session API Docs <sessionapi>` to learn more.8485.. _request-and-response-objects:8687Request and Response Objects88----------------------------8990Whenever a call is made to ``requests.get()`` and friends, you are doing two91major things. First, you are constructing a ``Request`` object which will be92sent off to a server to request or query some resource. Second, a ``Response``93object is generated once Requests gets a response back from the server.94The ``Response`` object contains all of the information returned by the server and95also contains the ``Request`` object you created originally. Here is a simple96request to get some very important information from Wikipedia's servers::9798 >>> r = requests.get('https://en.wikipedia.org/wiki/Monty_Python')99100If we want to access the headers the server sent back to us, we do this::101102 >>> r.headers103 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':104 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':105 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',106 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',107 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,108 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':109 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,110 MISS from cp1010.eqiad.wmnet:80'}111112However, if we want to get the headers we sent the server, we simply access the113request, and then the request's headers::114115 >>> r.request.headers116 {'Accept-Encoding': 'identity, deflate, compress, gzip',117 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}118119.. _prepared-requests:120121Prepared Requests122-----------------123124Whenever you receive a :class:`Response <requests.Response>` object125from an API call or a Session call, the ``request`` attribute is actually the126``PreparedRequest`` that was used. In some cases you may wish to do some extra127work to the body or headers (or anything else really) before sending a128request. The simple recipe for this is the following::129130 from requests import Request, Session131132 s = Session()133134 req = Request('POST', url, data=data, headers=headers)135 prepped = req.prepare()136137 # do something with prepped.body138 prepped.body = 'No, I want exactly this as the body.'139140 # do something with prepped.headers141 del prepped.headers['Content-Type']142143 resp = s.send(prepped,144 stream=stream,145 verify=verify,146 proxies=proxies,147 cert=cert,148 timeout=timeout149 )150151 print(resp.status_code)152153Since you are not doing anything special with the ``Request`` object, you154prepare it immediately and modify the ``PreparedRequest`` object. You then155send that with the other parameters you would have sent to ``requests.*`` or156``Session.*``.157158However, the above code will lose some of the advantages of having a Requests159:class:`Session <requests.Session>` object. In particular,160:class:`Session <requests.Session>`-level state such as cookies will161not get applied to your request. To get a162:class:`PreparedRequest <requests.PreparedRequest>` with that state163applied, replace the call to :meth:`Request.prepare()164<requests.Request.prepare>` with a call to165:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::166167 from requests import Request, Session168169 s = Session()170 req = Request('GET', url, data=data, headers=headers)171172 prepped = s.prepare_request(req)173174 # do something with prepped.body175 prepped.body = 'Seriously, send exactly these bytes.'176177 # do something with prepped.headers178 prepped.headers['Keep-Dead'] = 'parrot'179180 resp = s.send(prepped,181 stream=stream,182 verify=verify,183 proxies=proxies,184 cert=cert,185 timeout=timeout186 )187188 print(resp.status_code)189190When you are using the prepared request flow, keep in mind that it does not take into account the environment.191This can cause problems if you are using environment variables to change the behaviour of requests.192For example: Self-signed SSL certificates specified in ``REQUESTS_CA_BUNDLE`` will not be taken into account.193As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.194You can get around this behaviour by explicitly merging the environment settings into your session::195196 from requests import Request, Session197198 s = Session()199 req = Request('GET', url)200201 prepped = s.prepare_request(req)202203 # Merge environment settings into session204 settings = s.merge_environment_settings(prepped.url, {}, None, None, None)205 resp = s.send(prepped, **settings)206207 print(resp.status_code)208209.. _verification:210211SSL Cert Verification212---------------------213214Requests verifies SSL certificates for HTTPS requests, just like a web browser.215By default, SSL verification is enabled, and Requests will throw a SSLError if216it's unable to verify the certificate::217218 >>> requests.get('https://requestb.in')219 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'220221I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::222223 >>> requests.get('https://github.com')224 <Response [200]>225226You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::227228 >>> requests.get('https://github.com', verify='/path/to/certfile')229230or persistent::231232 s = requests.Session()233 s.verify = '/path/to/certfile'234235.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using236 the ``c_rehash`` utility supplied with OpenSSL.237238This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.239If ``REQUESTS_CA_BUNDLE`` is not set, ``CURL_CA_BUNDLE`` will be used as fallback.240241Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::242243 >>> requests.get('https://kennethreitz.org', verify=False)244 <Response [200]>245246Note that when ``verify`` is set to ``False``, requests will accept any TLS247certificate presented by the server, and will ignore hostname mismatches248and/or expired certificates, which will make your application vulnerable to249man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful250during local development or testing.251252By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.253254Client Side Certificates255------------------------256257You can also specify a local cert to use as client side certificate, as a single258file (containing the private key and the certificate) or as a tuple of both259files' paths::260261 >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))262 <Response [200]>263264or persistent::265266 s = requests.Session()267 s.cert = '/path/client.cert'268269If you specify a wrong path or an invalid cert, you'll get a SSLError::270271 >>> requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')272 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib273274.. warning:: The private key to your local certificate *must* be unencrypted.275 Currently, Requests does not support using encrypted keys.276277.. _ca-certificates:278279CA Certificates280---------------281282Requests uses certificates from the package `certifi`_. This allows for users283to update their trusted certificates without changing the version of Requests.284285Before version 2.16, Requests bundled a set of root CAs that it trusted,286sourced from the `Mozilla trust store`_. The certificates were only updated287once for each Requests version. When ``certifi`` was not installed, this led to288extremely out-of-date certificate bundles when using significantly older289versions of Requests.290291For the sake of security we recommend upgrading certifi frequently!292293.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection294.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/urllib3.connectionpool.html295.. _certifi: https://certifiio.readthedocs.io/296.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt297298.. _body-content-workflow:299300Body Content Workflow301---------------------302303By default, when you make a request, the body of the response is downloaded304immediately. You can override this behaviour and defer downloading the response305body until you access the :attr:`Response.content <requests.Response.content>`306attribute with the ``stream`` parameter::307308 tarball_url = 'https://github.com/psf/requests/tarball/main'309 r = requests.get(tarball_url, stream=True)310311At this point only the response headers have been downloaded and the connection312remains open, hence allowing us to make content retrieval conditional::313314 if int(r.headers['content-length']) < TOO_LONG:315 content = r.content316 ...317318You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`319and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.320Alternatively, you can read the undecoded body from the underlying321urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at322:attr:`Response.raw <requests.Response.raw>`.323324If you set ``stream`` to ``True`` when making a request, Requests cannot325release the connection back to the pool unless you consume all the data or call326:meth:`Response.close <requests.Response.close>`. This can lead to327inefficiency with connections. If you find yourself partially reading request328bodies (or not reading them at all) while using ``stream=True``, you should329make the request within a ``with`` statement to ensure it's always closed::330331 with requests.get('https://httpbin.org/get', stream=True) as r:332 # Do things with the response here.333334.. _keep-alive:335336Keep-Alive337----------338339Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!340Any requests that you make within a session will automatically reuse the appropriate341connection!342343Note that connections are only released back to the pool for reuse once all body344data has been read; be sure to either set ``stream`` to ``False`` or read the345``content`` property of the ``Response`` object.346347.. _streaming-uploads:348349Streaming Uploads350-----------------351352Requests supports streaming uploads, which allow you to send large streams or353files without reading them into memory. To stream and upload, simply provide a354file-like object for your body::355356 with open('massive-body', 'rb') as f:357 requests.post('http://some.url/streamed', data=f)358359.. warning:: It is strongly recommended that you open files in :ref:`binary360 mode <tut-files>`. This is because Requests may attempt to provide361 the ``Content-Length`` header for you, and if it does this value362 will be set to the number of *bytes* in the file. Errors may occur363 if you open the file in *text mode*.364365366.. _chunk-encoding:367368Chunk-Encoded Requests369----------------------370371Requests also supports Chunked transfer encoding for outgoing and incoming requests.372To send a chunk-encoded request, simply provide a generator (or any iterator without373a length) for your body::374375 def gen():376 yield 'hi'377 yield 'there'378379 requests.post('http://some.url/chunked', data=gen())380381For chunked encoded responses, it's best to iterate over the data using382:meth:`Response.iter_content() <requests.Response.iter_content>`. In383an ideal situation you'll have set ``stream=True`` on the request, in which384case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``385parameter of ``None``. If you want to set a maximum size of the chunk,386you can set a ``chunk_size`` parameter to any integer.387388389.. _multipart:390391POST Multiple Multipart-Encoded Files392-------------------------------------393394You can send multiple files in one request. For example, suppose you want to395upload image files to an HTML form with a multiple file field 'images'::396397 <input type="file" name="images" multiple="true" required="true"/>398399To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::400401 >>> url = 'https://httpbin.org/post'402 >>> multiple_files = [403 ... ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),404 ... ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]405 >>> r = requests.post(url, files=multiple_files)406 >>> r.text407 {408 ...409 'files': {'images': 'data:image/png;base64,iVBORw ....'}410 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',411 ...412 }413414.. warning:: It is strongly recommended that you open files in :ref:`binary415 mode <tut-files>`. This is because Requests may attempt to provide416 the ``Content-Length`` header for you, and if it does this value417 will be set to the number of *bytes* in the file. Errors may occur418 if you open the file in *text mode*.419420421.. _event-hooks:422423Event Hooks424-----------425426Requests has a hook system that you can use to manipulate portions of427the request process, or signal event handling.428429Available hooks:430431``response``:432 The response generated from a Request.433434435You can assign a hook function on a per-request basis by passing a436``{hook_name: callback_function}`` dictionary to the ``hooks`` request437parameter::438439 hooks={'response': print_url}440441That ``callback_function`` will receive a chunk of data as its first442argument.443444::445446 def print_url(r, *args, **kwargs):447 print(r.url)448449Your callback function must handle its own exceptions. Any unhandled exception won't be passed silently and thus should be handled by the code calling Requests.450451If the callback function returns a value, it is assumed that it is to452replace the data that was passed in. If the function doesn't return453anything, nothing else is affected.454455::456457 def record_hook(r, *args, **kwargs):458 r.hook_called = True459 return r460461Let's print some request method arguments at runtime::462463 >>> requests.get('https://httpbin.org/', hooks={'response': print_url})464 https://httpbin.org/465 <Response [200]>466467You can add multiple hooks to a single request. Let's call two hooks at once::468469 >>> r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})470 https://httpbin.org/471 >>> r.hook_called472 True473474You can also add hooks to a ``Session`` instance. Any hooks you add will then475be called on every request made to the session. For example::476477 >>> s = requests.Session()478 >>> s.hooks['response'].append(print_url)479 >>> s.get('https://httpbin.org/')480 https://httpbin.org/481 <Response [200]>482483A ``Session`` can have multiple hooks, which will be called in the order484they are added.485486.. _custom-auth:487488Custom Authentication489---------------------490491Requests allows you to specify your own authentication mechanism.492493Any callable which is passed as the ``auth`` argument to a request method will494have the opportunity to modify the request before it is dispatched.495496Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,497and are easy to define. Requests provides two common authentication scheme498implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and499:class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.500501Let's pretend that we have a web service that will only respond if the502``X-Pizza`` header is set to a password value. Unlikely, but just go with it.503504::505506 from requests.auth import AuthBase507508 class PizzaAuth(AuthBase):509 """Attaches HTTP Pizza Authentication to the given Request object."""510 def __init__(self, username):511 # setup any auth-related data here512 self.username = username513514 def __call__(self, r):515 # modify and return the request516 r.headers['X-Pizza'] = self.username517 return r518519Then, we can make a request using our Pizza Auth::520521 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))522 <Response [200]>523524.. _streaming-requests:525526Streaming Requests527------------------528529With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily530iterate over streaming APIs such as the `Twitter Streaming531API <https://dev.twitter.com/streaming/overview>`_. Simply532set ``stream`` to ``True`` and iterate over the response with533:meth:`~requests.Response.iter_lines()`::534535 import json536 import requests537538 r = requests.get('https://httpbin.org/stream/20', stream=True)539540 for line in r.iter_lines():541542 # filter out keep-alive new lines543 if line:544 decoded_line = line.decode('utf-8')545 print(json.loads(decoded_line))546547When using `decode_unicode=True` with548:meth:`Response.iter_lines() <requests.Response.iter_lines>` or549:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want550to provide a fallback encoding in the event the server doesn't provide one::551552 r = requests.get('https://httpbin.org/stream/20', stream=True)553554 if r.encoding is None:555 r.encoding = 'utf-8'556557 for line in r.iter_lines(decode_unicode=True):558 if line:559 print(json.loads(line))560561.. warning::562563 :meth:`~requests.Response.iter_lines()` is not reentrant safe.564 Calling this method multiple times causes some of the received data565 being lost. In case you need to call it from multiple places, use566 the resulting iterator object instead::567568 lines = r.iter_lines()569 # Save the first line for later or just skip it570571 first_line = next(lines)572573 for line in lines:574 print(line)575576.. _proxies:577578Proxies579-------580581If you need to use a proxy, you can configure individual requests with the582``proxies`` argument to any request method::583584 import requests585586 proxies = {587 'http': 'http://10.10.1.10:3128',588 'https': 'http://10.10.1.10:1080',589 }590591 requests.get('http://example.org', proxies=proxies)592593Alternatively you can configure it once for an entire594:class:`Session <requests.Session>`::595596 import requests597598 proxies = {599 'http': 'http://10.10.1.10:3128',600 'https': 'http://10.10.1.10:1080',601 }602 session = requests.Session()603 session.proxies.update(proxies)604605 session.get('http://example.org')606607.. warning:: Setting ``session.proxies`` may behave differently than expected.608 Values provided will be overwritten by environmental proxies609 (those returned by `urllib.request.getproxies <https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies>`_).610 To ensure the use of proxies in the presence of environmental proxies,611 explicitly specify the ``proxies`` argument on all individual requests as612 initially explained above.613614 See `#2018 <https://github.com/psf/requests/issues/2018>`_ for details.615616When the proxies configuration is not overridden per request as shown above,617Requests relies on the proxy configuration defined by standard618environment variables ``http_proxy``, ``https_proxy``, ``no_proxy``,619and ``all_proxy``. Uppercase variants of these variables are also supported.620You can therefore set them to configure Requests (only set the ones relevant621to your needs)::622623 $ export HTTP_PROXY="http://10.10.1.10:3128"624 $ export HTTPS_PROXY="http://10.10.1.10:1080"625 $ export ALL_PROXY="socks5://10.10.1.10:3434"626627 $ python628 >>> import requests629 >>> requests.get('http://example.org')630631To use HTTP Basic Auth with your proxy, use the `http://user:password@host/`632syntax in any of the above configuration entries::633634 $ export HTTPS_PROXY="http://user:pass@10.10.1.10:1080"635636 $ python637 >>> proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}638639.. warning:: Storing sensitive username and password information in an640 environment variable or a version-controlled file is a security risk and is641 highly discouraged.642643To give a proxy for a specific scheme and host, use the644`scheme://hostname` form for the key. This will match for645any request to the given scheme and exact hostname.646647::648649 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}650651Note that proxy URLs must include the scheme.652653Finally, note that using a proxy for https connections typically requires your654local machine to trust the proxy's root certificate. By default the list of655certificates trusted by Requests can be found with::656657 from requests.utils import DEFAULT_CA_BUNDLE_PATH658 print(DEFAULT_CA_BUNDLE_PATH)659660You override this default certificate bundle by setting the ``REQUESTS_CA_BUNDLE``661(or ``CURL_CA_BUNDLE``) environment variable to another file path::662663 $ export REQUESTS_CA_BUNDLE="/usr/local/myproxy_info/cacert.pem"664 $ export https_proxy="http://10.10.1.10:1080"665666 $ python667 >>> import requests668 >>> requests.get('https://example.org')669670.. _socks:671672SOCKS673^^^^^674675.. versionadded:: 2.10.0676677In addition to basic HTTP proxies, Requests also supports proxies using the678SOCKS protocol. This is an optional feature that requires that additional679third-party libraries be installed before use.680681You can get the dependencies for this feature from ``pip``::682683 $ python -m pip install 'requests[socks]'684685Once you've installed those dependencies, using a SOCKS proxy is just as easy686as using a HTTP one::687688 proxies = {689 'http': 'socks5://user:pass@host:port',690 'https': 'socks5://user:pass@host:port'691 }692693Using the scheme ``socks5`` causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use ``socks5h`` as the scheme.694695.. _compliance:696697Compliance698----------699700Requests is intended to be compliant with all relevant specifications and701RFCs where that compliance will not cause difficulties for users. This702attention to the specification can lead to some behaviour that may seem703unusual to those not familiar with the relevant specification.704705Encodings706^^^^^^^^^707708When you receive a response, Requests makes a guess at the encoding to709use for decoding the response when you access the :attr:`Response.text710<requests.Response.text>` attribute. Requests will first check for an711encoding in the HTTP header, and if none is present, will use712`charset_normalizer <https://pypi.org/project/charset_normalizer/>`_713or `chardet <https://github.com/chardet/chardet>`_ to attempt to714guess the encoding.715716If ``chardet`` is installed, ``requests`` uses it, however for python3717``chardet`` is no longer a mandatory dependency. The ``chardet``718library is an LGPL-licenced dependency and some users of requests719cannot depend on mandatory LGPL-licensed dependencies.720721When you install ``requests`` without specifying ``[use_chardet_on_py3]`` extra,722and ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``723(MIT-licensed) to guess the encoding.724725The only time Requests will not guess the encoding is if no explicit charset726is present in the HTTP headers **and** the ``Content-Type``727header contains ``text``. In this situation, `RFC 2616728<https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies729that the default charset must be ``ISO-8859-1``. Requests follows the730specification in this case. If you require a different encoding, you can731manually set the :attr:`Response.encoding <requests.Response.encoding>`732property, or use the raw :attr:`Response.content <requests.Response.content>`.733734.. _http-verbs:735736HTTP Verbs737----------738739Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,740HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of741using these various verbs in Requests, using the GitHub API.742743We will begin with the verb most commonly used: GET. HTTP GET is an idempotent744method that returns a resource from a given URL. As a result, it is the verb745you ought to use when attempting to retrieve data from a web location. An746example usage would be attempting to get information about a specific commit747from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it748like so::749750 >>> import requests751 >>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')752753We should confirm that GitHub responded correctly. If it has, we want to work754out what type of content it is. Do this like so::755756 >>> if r.status_code == requests.codes.ok:757 ... print(r.headers['content-type'])758 ...759 application/json; charset=utf-8760761So, GitHub returns JSON. That's great, we can use the :meth:`r.json762<requests.Response.json>` method to parse it into Python objects.763764::765766 >>> commit_data = r.json()767768 >>> print(commit_data.keys())769 ['committer', 'author', 'url', 'tree', 'sha', 'parents', 'message']770771 >>> print(commit_data['committer'])772 {'date': '2012-05-10T11:10:50-07:00', 'email': 'me@kennethreitz.com', 'name': 'Kenneth Reitz'}773774 >>> print(commit_data['message'])775 makin' history776777So far, so simple. Well, let's investigate the GitHub API a little bit. Now,778we could look at the documentation, but we might have a little more fun if we779use Requests instead. We can take advantage of the Requests OPTIONS verb to780see what kinds of HTTP methods are supported on the url we just used.781782::783784 >>> verbs = requests.options(r.url)785 >>> verbs.status_code786 500787788Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't789actually implement the OPTIONS method. This is an annoying oversight, but it's790OK, we can just use the boring documentation. If GitHub had correctly791implemented OPTIONS, however, they should return the allowed methods in the792headers, e.g.793794::795796 >>> verbs = requests.options('http://a-good-website.com/api/cats')797 >>> print(verbs.headers['allow'])798 GET,HEAD,POST,OPTIONS799800Turning to the documentation, we see that the only other method allowed for801commits is POST, which creates a new commit. As we're using the Requests repo,802we should probably avoid making ham-handed POSTS to it. Instead, let's play803with the Issues feature of GitHub.804805This documentation was added in response to806`Issue #482 <https://github.com/psf/requests/issues/482>`_. Given that807this issue already exists, we will use it as an example. Let's start by getting it.808809::810811 >>> r = requests.get('https://api.github.com/repos/psf/requests/issues/482')812 >>> r.status_code813 200814815 >>> issue = json.loads(r.text)816817 >>> print(issue['title'])818 Feature any http verb in docs819820 >>> print(issue['comments'])821 3822823Cool, we have three comments. Let's take a look at the last of them.824825::826827 >>> r = requests.get(r.url + '/comments')828 >>> r.status_code829 200830831 >>> comments = r.json()832833 >>> print(comments[0].keys())834 ['body', 'url', 'created_at', 'updated_at', 'user', 'id']835836 >>> print(comments[2]['body'])837 Probably in the "advanced" section838839Well, that seems like a silly place. Let's post a comment telling the poster840that he's silly. Who is the poster, anyway?841842::843844 >>> print(comments[2]['user']['login'])845 kennethreitz846847OK, so let's tell this Kenneth guy that we think this example should go in the848quickstart guide instead. According to the GitHub API doc, the way to do this849is to POST to the thread. Let's do it.850851::852853 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})854 >>> url = u"https://api.github.com/repos/psf/requests/issues/482/comments"855856 >>> r = requests.post(url=url, data=body)857 >>> r.status_code858 404859860Huh, that's weird. We probably need to authenticate. That'll be a pain, right?861Wrong. Requests makes it easy to use many forms of authentication, including862the very common Basic Auth.863864::865866 >>> from requests.auth import HTTPBasicAuth867 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')868869 >>> r = requests.post(url=url, data=body, auth=auth)870 >>> r.status_code871 201872873 >>> content = r.json()874 >>> print(content['body'])875 Sounds great! I'll get right on it.876877Brilliant. Oh, wait, no! I meant to add that it would take me a while, because878I had to go feed my cat. If only I could edit this comment! Happily, GitHub879allows us to use another HTTP verb, PATCH, to edit this comment. Let's do880that.881882::883884 >>> print(content[u"id"])885 5804413886887 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})888 >>> url = u"https://api.github.com/repos/psf/requests/issues/comments/5804413"889890 >>> r = requests.patch(url=url, data=body, auth=auth)891 >>> r.status_code892 200893894Excellent. Now, just to torture this Kenneth guy, I've decided to let him895sweat and not tell him that I'm working on this. That means I want to delete896this comment. GitHub lets us delete comments using the incredibly aptly named897DELETE method. Let's get rid of it.898899::900901 >>> r = requests.delete(url=url, auth=auth)902 >>> r.status_code903 204904 >>> r.headers['status']905 '204 No Content'906907Excellent. All gone. The last thing I want to know is how much of my ratelimit908I've used. Let's find out. GitHub sends that information in the headers, so909rather than download the whole page I'll send a HEAD request to get the910headers.911912::913914 >>> r = requests.head(url=url, auth=auth)915 >>> print(r.headers)916 ...917 'x-ratelimit-remaining': '4995'918 'x-ratelimit-limit': '5000'919 ...920921Excellent. Time to write a Python program that abuses the GitHub API in all922kinds of exciting ways, 4995 more times.923924.. _custom-verbs:925926Custom Verbs927------------928929From time to time you may be working with a server that, for whatever reason,930allows use or even requires use of HTTP verbs not covered above. One example of931this would be the MKCOL method some WEBDAV servers use. Do not fret, these can932still be used with Requests. These make use of the built-in ``.request``933method. For example::934935 >>> r = requests.request('MKCOL', url, data=data)936 >>> r.status_code937 200 # Assuming your call was correct938939Utilising this, you can make use of any method verb that your server allows.940941942.. _link-headers:943944Link Headers945------------946947Many HTTP APIs feature Link headers. They make APIs more self describing and948discoverable.949950GitHub uses these for `pagination <https://docs.github.com/en/rest/guides/using-pagination-in-the-rest-api>`_951in their API, for example::952953 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'954 >>> r = requests.head(url=url)955 >>> r.headers['link']956 '<https://api.github.com/users/kennethreitz/repos?page=2&per_page=10>; rel="next", <https://api.github.com/users/kennethreitz/repos?page=6&per_page=10>; rel="last"'957958Requests will automatically parse these link headers and make them easily consumable::959960 >>> r.links["next"]961 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}962963 >>> r.links["last"]964 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}965966.. _transport-adapters:967968Transport Adapters969------------------970971As of v1.0.0, Requests has moved to a modular internal design using Transport972Adapters. These objects provide a mechanism to define interaction methods for an973HTTP service. In particular, they allow you to apply per-service configuration.974975Requests ships with a single Transport Adapter, the :class:`HTTPAdapter976<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests977interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever978a Requests :class:`Session <requests.Session>` is initialized, one of these is979attached to the :class:`Session <requests.Session>` object for HTTP, and one980for HTTPS.981982Requests enables users to create and use their own Transport Adapters that983provide specific functionality. Once created, a Transport Adapter can be984mounted to a Session object, along with an indication of which web services985it should apply to.986987::988989 >>> s = requests.Session()990 >>> s.mount('https://github.com/', MyAdapter())991992The mount call registers a specific instance of a Transport Adapter to a993prefix. Once mounted, any HTTP request made using that session whose URL starts994with the given prefix will use the given Transport Adapter.995996.. note:: The adapter will be chosen based on a longest prefix match. Be mindful997 prefixes such as ``http://localhost`` will also match ``http://localhost.other.com``998 or ``http://localhost@other.com``. It's recommended to terminate full hostnames with a ``/``.9991000Many of the details of implementing a Transport Adapter are beyond the scope of1001this documentation, but take a look at the next example for a simple SSL use-1002case. For more than that, you might look at subclassing the1003:class:`BaseAdapter <requests.adapters.BaseAdapter>`.10041005Example: Specific SSL Version1006^^^^^^^^^^^^^^^^^^^^^^^^^^^^^10071008The Requests team has made a specific choice to use whatever SSL version is1009default in the underlying library (`urllib3`_). Normally this is fine, but from1010time to time, you might find yourself needing to connect to a service-endpoint1011that uses a version that isn't compatible with the default.10121013You can use Transport Adapters for this by taking most of the existing1014implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets1015passed-through to `urllib3`. We'll make a Transport Adapter that instructs the1016library to use SSLv3::10171018 import ssl1019 from urllib3.poolmanager import PoolManager10201021 from requests.adapters import HTTPAdapter102210231024 class Ssl3HttpAdapter(HTTPAdapter):1025 """"Transport adapter" that allows us to use SSLv3."""10261027 def init_poolmanager(self, connections, maxsize, block=False):1028 self.poolmanager = PoolManager(1029 num_pools=connections, maxsize=maxsize,1030 block=block, ssl_version=ssl.PROTOCOL_SSLv3)10311032Example: Automatic Retries1033^^^^^^^^^^^^^^^^^^^^^^^^^^10341035By default, Requests does not retry failed connections. However, it is possible1036to implement automatic retries with a powerful array of features, including1037backoff, within a Requests :class:`Session <requests.Session>` using the1038`urllib3.util.Retry`_ class::10391040 from urllib3.util import Retry1041 from requests import Session1042 from requests.adapters import HTTPAdapter10431044 s = Session()1045 retries = Retry(1046 total=3,1047 backoff_factor=0.1,1048 status_forcelist=[502, 503, 504],1049 allowed_methods={'POST'},1050 )1051 s.mount('https://', HTTPAdapter(max_retries=retries))10521053.. _`urllib3`: https://github.com/urllib3/urllib31054.. _`urllib3.util.Retry`: https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.Retry10551056.. _blocking-or-nonblocking:10571058Blocking Or Non-Blocking?1059-------------------------10601061With the default Transport Adapter in place, Requests does not provide any kind1062of non-blocking IO. The :attr:`Response.content <requests.Response.content>`1063property will block until the entire response has been downloaded. If1064you require more granularity, the streaming features of the library (see1065:ref:`streaming-requests`) allow you to retrieve smaller quantities of the1066response at a time. However, these calls will still block.10671068If you are concerned about the use of blocking IO, there are lots of projects1069out there that combine Requests with one of Python's asynchronicity frameworks.1070Some excellent examples are `requests-threads`_, `grequests`_, `requests-futures`_, and `httpx`_.10711072.. _`requests-threads`: https://github.com/requests/requests-threads1073.. _`grequests`: https://github.com/spyoungtech/grequests1074.. _`requests-futures`: https://github.com/ross/requests-futures1075.. _`httpx`: https://github.com/encode/httpx10761077Header Ordering1078---------------10791080In unusual circumstances you may want to provide headers in an ordered manner. If you pass an ``OrderedDict`` to the ``headers`` keyword argument, that will provide the headers with an ordering. *However*, the ordering of the default headers used by Requests will be preferred, which means that if you override default headers in the ``headers`` keyword argument, they may appear out of order compared to other headers in that keyword argument.10811082If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session.headers <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.10831084.. _timeouts:10851086Timeouts1087--------10881089Most requests to external servers should have a timeout attached, in case the1090server is not responding in a timely manner. By default, requests do not time1091out unless a timeout value is set explicitly. Without a timeout, your code may1092hang for minutes or more.10931094The **connect** timeout is the number of seconds Requests will wait for your1095client to establish a connection to a remote machine (corresponding to the1096`connect()`_) call on the socket. It's a good practice to set connect timeouts1097to slightly larger than a multiple of 3, which is the default `TCP packet1098retransmission window <https://datatracker.ietf.org/doc/html/rfc2988>`_.10991100Once your client has connected to the server and sent the HTTP request, the1101**read** timeout is the number of seconds the client will wait for the server1102to send a response. (Specifically, it's the number of seconds that the client1103will wait *between* bytes sent from the server. In 99.9% of cases, this is the1104time before the server sends the first byte).11051106If you specify a single value for the timeout, like this::11071108 r = requests.get('https://github.com', timeout=5)11091110The timeout value will be applied to both the ``connect`` and the ``read``1111timeouts. Specify a tuple if you would like to set the values separately::11121113 r = requests.get('https://github.com', timeout=(3.05, 27))11141115If the remote server is very slow, you can tell Requests to wait forever for1116a response, by passing None as a timeout value and then retrieving a cup of1117coffee.11181119::11201121 r = requests.get('https://github.com', timeout=None)11221123.. note:: The connect timeout applies to each connection attempt to an IP address.1124 If multiple addresses exist for a domain name, the underlying ``urllib3`` will1125 try each address sequentially until one successfully connects.1126 This may lead to an effective total connection timeout *multiple* times longer1127 than the specified time, e.g. an unresponsive server having both IPv4 and IPv61128 addresses will have its perceived timeout *doubled*, so take that into account1129 when setting the connection timeout.1130.. note:: Neither the connect nor read timeouts are `wall clock`_. This means1131 that if you start a request, and look at the time, and then look at1132 the time when the request finishes or times out, the real-world time1133 may be greater than what you specified.113411351136.. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_time1137.. _`connect()`: https://linux.die.net/man/2/connect