Skip to content
Myr

api.rst

This file

Path

docs/api.rst

270 lines · 7.2 KiB

Last changed by

Merge pull request #2976 from shoma/fix-debug-logging-docCory Benfieldbefore adoption00fa5f1

History of this file

Take 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:: delete272829Lower-Level Classes30~~~~~~~~~~~~~~~~~~~3132.. autoclass:: requests.Request33   :inherited-members:3435.. autoclass:: Response36   :inherited-members:3738Request Sessions39----------------4041.. autoclass:: Session42   :inherited-members:4344.. autoclass:: requests.adapters.HTTPAdapter45   :inherited-members:4647Authentication48--------------4950.. autoclass:: requests.auth.AuthBase51.. autoclass:: requests.auth.HTTPBasicAuth52.. autoclass:: requests.auth.HTTPProxyAuth53.. autoclass:: requests.auth.HTTPDigestAuth5455Exceptions56~~~~~~~~~~5758.. autoexception:: requests.exceptions.RequestException59.. autoexception:: requests.exceptions.ConnectionError60.. autoexception:: requests.exceptions.HTTPError61.. autoexception:: requests.exceptions.URLRequired62.. autoexception:: requests.exceptions.TooManyRedirects63.. autoexception:: requests.exceptions.ConnectTimeout64.. autoexception:: requests.exceptions.ReadTimeout65.. autoexception:: requests.exceptions.Timeout666768Status Code Lookup69~~~~~~~~~~~~~~~~~~7071.. autofunction:: requests.codes7273::7475    >>> requests.codes['temporary_redirect']76    3077778    >>> requests.codes.teapot79    4188081    >>> requests.codes['\o/']82    2008384.. _api-cookies:8586Cookies87~~~~~~~8889.. autofunction:: requests.utils.dict_from_cookiejar90.. autofunction:: requests.utils.cookiejar_from_dict91.. autofunction:: requests.utils.add_dict_to_cookiejar9293.. autoclass:: requests.cookies.RequestsCookieJar94   :inherited-members:9596.. autoclass:: requests.cookies.CookieConflictError97   :inherited-members:9899100Encodings101~~~~~~~~~102103.. autofunction:: requests.utils.get_encodings_from_content104.. autofunction:: requests.utils.get_encoding_from_headers105.. autofunction:: requests.utils.get_unicode_from_response106107108Classes109~~~~~~~110111.. autoclass:: requests.Response112   :inherited-members:113114.. autoclass:: requests.Request115   :inherited-members:116117.. autoclass:: requests.PreparedRequest118   :inherited-members:119120.. _sessionapi:121122.. autoclass:: requests.Session123   :inherited-members:124125.. autoclass:: requests.adapters.HTTPAdapter126   :inherited-members:127128129Migrating to 1.x130----------------131132This section details the main differences between 0.x and 1.x and is meant133to ease the pain of upgrading.134135136API Changes137~~~~~~~~~~~138139* ``Response.json`` is now a callable and not a property of a response.140141  ::142143      import requests144      r = requests.get('https://github.com/timeline.json')145      r.json()   # This *call* raises an exception if JSON decoding fails146147* The ``Session`` API has changed. Sessions objects no longer take parameters.148  ``Session`` is also now capitalized, but it can still be149  instantiated with a lowercase ``session`` for backwards compatibility.150151  ::152153      s = requests.Session()    # formerly, session took parameters154      s.auth = auth155      s.headers.update(headers)156      r = s.get('http://httpbin.org/headers')157158* All request hooks have been removed except 'response'.159160* Authentication helpers have been broken out into separate modules. See161  requests-oauthlib_ and requests-kerberos_.162163.. _requests-oauthlib: https://github.com/requests/requests-oauthlib164.. _requests-kerberos: https://github.com/requests/requests-kerberos165166* The parameter for streaming requests was changed from ``prefetch`` to167  ``stream`` and the logic was inverted. In addition, ``stream`` is now168  required for raw response reading.169170  ::171172      # in 0.x, passing prefetch=False would accomplish the same thing173      r = requests.get('https://github.com/timeline.json', stream=True)174      for chunk in r.iter_content(8192):175          ...176177* The ``config`` parameter to the requests method has been removed. Some of178  these options are now configured on a ``Session`` such as keep-alive and179  maximum number of redirects. The verbosity option should be handled by180  configuring logging.181182  ::183184      import requests185      import logging186187      # Enabling debugging at http.client level (requests->urllib3->http.client)188      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.189      # the only thing missing will be the response.body which is not logged.190      try: # for Python 3191          from http.client import HTTPConnection192      except ImportError:193          from httplib import HTTPConnection194      HTTPConnection.debuglevel = 1195196      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests197      logging.getLogger().setLevel(logging.DEBUG)198      requests_log = logging.getLogger("requests.packages.urllib3")199      requests_log.setLevel(logging.DEBUG)200      requests_log.propagate = True201202      requests.get('http://httpbin.org/headers')203204205206Licensing207~~~~~~~~~208209One key difference that has nothing to do with the API is a change in the210license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0211license ensures that contributions to Requests are also covered by the Apache2122.0 license.213214.. _ISC: http://opensource.org/licenses/ISC215.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0216217218Migrating to 2.x219----------------220221222Compared with the 1.0 release, there were relatively few backwards223incompatible changes, but there are still a few issues to be aware of with224this major release.225226For more details on the changes in this release including new APIs, links227to the relevant GitHub issues and some of the bug fixes, read Cory's blog_228on the subject.229230.. _blog: http://lukasa.co.uk/2013/09/Requests_20/231232233API Changes234~~~~~~~~~~~235236* There were a couple changes to how Requests handles exceptions.237  ``RequestException`` is now a subclass of ``IOError`` rather than238  ``RuntimeError`` as that more accurately categorizes the type of error.239  In addition, an invalid URL escape sequence now raises a subclass of240  ``RequestException`` rather than a ``ValueError``.241242  ::243244      requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL245246  Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked247  encoding will now raise a Requests ``ChunkedEncodingError`` instead.248249* The proxy API has changed slightly. The scheme for a proxy URL is now250  required.251252  ::253254      proxies = {255        "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead256      }257258      # In requests 1.x, this was legal, in requests 2.x,259      #  this raises requests.exceptions.MissingSchema260      requests.get("http://example.org", proxies=proxies)261262263Behavioural Changes264~~~~~~~~~~~~~~~~~~~~~~~265266* Keys in the ``headers`` dictionary are now native strings on all Python267  versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the268  keys are not native strings (unicode on Python2 or bytestrings on Python 3)269  they will be converted to the native string type assuming UTF-8 encoding.270