api.rst
This file
Path
docs/api.rst
261 lines · 7.2 KiB
Last changed by
docs: exclude Response.is_permanent_redirect from API docs (#7244)Dr Alex Mitrebefore adoption0e4ae38
History of this fileTake it
1.. _api:23Developer Interface4===================56.. module:: requests78This part of the documentation covers all the interfaces of Requests. For9parts where Requests depends on external libraries, we document the most10important right here and provide links to the canonical documentation.111213Main Interface14--------------1516All of Requests' functionality can be accessed by these 7 methods.17They all return an instance of the :class:`Response <Response>` object.1819.. autofunction:: request2021.. autofunction:: head22.. autofunction:: get23.. autofunction:: post24.. autofunction:: put25.. autofunction:: patch26.. autofunction:: delete2728Exceptions29----------3031.. autoexception:: requests.RequestException32.. autoexception:: requests.ConnectionError33.. autoexception:: requests.HTTPError34.. autoexception:: requests.TooManyRedirects35.. autoexception:: requests.ConnectTimeout36.. autoexception:: requests.ReadTimeout37.. autoexception:: requests.Timeout38.. autoexception:: requests.JSONDecodeError394041Request Sessions42----------------4344.. _sessionapi:4546.. autoclass:: Session47 :inherited-members:484950Lower-Level Classes51-------------------5253.. autoclass:: requests.Request54 :inherited-members:5556.. autoclass:: Response57 :inherited-members:58 :exclude-members: is_permanent_redirect596061Lower-Lower-Level Classes62-------------------------6364.. autoclass:: requests.PreparedRequest65 :inherited-members:6667.. autoclass:: requests.adapters.BaseAdapter68 :inherited-members:6970.. autoclass:: requests.adapters.HTTPAdapter71 :inherited-members:7273Authentication74--------------7576.. autoclass:: requests.auth.AuthBase77.. autoclass:: requests.auth.HTTPBasicAuth78.. autoclass:: requests.auth.HTTPProxyAuth79.. autoclass:: requests.auth.HTTPDigestAuth80818283Encodings84---------8586.. autofunction:: requests.utils.get_encodings_from_content87.. autofunction:: requests.utils.get_encoding_from_headers88.. autofunction:: requests.utils.get_unicode_from_response899091.. _api-cookies:9293Cookies94-------9596.. autofunction:: requests.utils.dict_from_cookiejar97.. autofunction:: requests.utils.add_dict_to_cookiejar98.. autofunction:: requests.cookies.cookiejar_from_dict99100.. autoclass:: requests.cookies.RequestsCookieJar101 :inherited-members:102103.. autoclass:: requests.cookies.CookieConflictError104 :inherited-members:105106107108Status Code Lookup109------------------110111.. autoclass:: requests.codes112113.. automodule:: requests.status_codes114115116Migrating to 1.x117----------------118119This section details the main differences between 0.x and 1.x and is meant120to ease the pain of upgrading.121122123API Changes124~~~~~~~~~~~125126* ``Response.json`` is now a callable and not a property of a response.127128 ::129130 import requests131 r = requests.get('https://api.github.com/events')132 r.json() # This *call* raises an exception if JSON decoding fails133134* The ``Session`` API has changed. Sessions objects no longer take parameters.135 ``Session`` is also now capitalized, but it can still be136 instantiated with a lowercase ``session`` for backwards compatibility.137138 ::139140 s = requests.Session() # formerly, session took parameters141 s.auth = auth142 s.headers.update(headers)143 r = s.get('https://httpbin.org/headers')144145* All request hooks have been removed except 'response'.146147* Authentication helpers have been broken out into separate modules. See148 requests-oauthlib_ and requests-kerberos_.149150.. _requests-oauthlib: https://github.com/requests/requests-oauthlib151.. _requests-kerberos: https://github.com/requests/requests-kerberos152153* The parameter for streaming requests was changed from ``prefetch`` to154 ``stream`` and the logic was inverted. In addition, ``stream`` is now155 required for raw response reading.156157 ::158159 # in 0.x, passing prefetch=False would accomplish the same thing160 r = requests.get('https://api.github.com/events', stream=True)161 for chunk in r.iter_content(8192):162 ...163164* The ``config`` parameter to the requests method has been removed. Some of165 these options are now configured on a ``Session`` such as keep-alive and166 maximum number of redirects. The verbosity option should be handled by167 configuring logging.168169 ::170171 import requests172 import logging173174 # Enabling debugging at http.client level (requests->urllib3->http.client)175 # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.176 # the only thing missing will be the response.body which is not logged.177 try: # for Python 3178 from http.client import HTTPConnection179 except ImportError:180 from httplib import HTTPConnection181 HTTPConnection.debuglevel = 1182183 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests184 logging.getLogger().setLevel(logging.DEBUG)185 requests_log = logging.getLogger("urllib3")186 requests_log.setLevel(logging.DEBUG)187 requests_log.propagate = True188189 requests.get('https://httpbin.org/headers')190191192193Licensing194~~~~~~~~~195196One key difference that has nothing to do with the API is a change in the197license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0198license ensures that contributions to Requests are also covered by the Apache1992.0 license.200201.. _ISC: https://opensource.org/licenses/ISC202.. _Apache 2.0: https://opensource.org/licenses/Apache-2.0203204205Migrating to 2.x206----------------207208209Compared with the 1.0 release, there were relatively few backwards210incompatible changes, but there are still a few issues to be aware of with211this major release.212213For more details on the changes in this release including new APIs, links214to the relevant GitHub issues and some of the bug fixes, read Cory's blog_215on the subject.216217.. _blog: https://lukasa.co.uk/2013/09/Requests_20/218219220API Changes221~~~~~~~~~~~222223* There were a couple changes to how Requests handles exceptions.224 ``RequestException`` is now a subclass of ``IOError`` rather than225 ``RuntimeError`` as that more accurately categorizes the type of error.226 In addition, an invalid URL escape sequence now raises a subclass of227 ``RequestException`` rather than a ``ValueError``.228229 ::230231 requests.get('http://%zz/') # raises requests.exceptions.InvalidURL232233 Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked234 encoding will now raise a Requests ``ChunkedEncodingError`` instead.235236* The proxy API has changed slightly. The scheme for a proxy URL is now237 required.238239 ::240241 proxies = {242 "http": "10.10.1.10:3128", # use http://10.10.1.10:3128 instead243 }244245 # In requests 1.x, this was legal, in requests 2.x,246 # this raises requests.exceptions.MissingSchema247 requests.get("http://example.org", proxies=proxies)248249250Behavioural Changes251~~~~~~~~~~~~~~~~~~~~~~~252253* Keys in the ``headers`` dictionary are now native strings on all Python254 versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the255 keys are not native strings (unicode on Python 2 or bytestrings on Python 3)256 they will be converted to the native string type assuming UTF-8 encoding.257258* Values in the ``headers`` dictionary should always be strings. This has259 been the project's position since before 1.0 but a recent change260 (since version 2.11.0) enforces this more strictly. It's advised to avoid261 passing header values as unicode when possible.