Skip to content
Myr

api.rst

This file

Path

docs/api.rst

263 lines · 6.9 KiB

Last changed by

Merge pull request #3041 from bsandrow/patch-2Kenneth Reitzbefore adoption3a26d13

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:: delete2728Exceptions29----------3031.. autoexception:: requests.RequestException32.. autoexception:: requests.ConnectionError33.. autoexception:: requests.HTTPError34.. autoexception:: requests.URLRequired35.. autoexception:: requests.TooManyRedirects36.. autoexception:: requests.ConnectTimeout37.. autoexception:: requests.ReadTimeout38.. autoexception:: requests.Timeout394041Request Sessions42----------------4344.. _sessionapi:4546.. autoclass:: Session47   :inherited-members:484950Lower-Level Classes51-------------------5253.. autoclass:: requests.Request54   :inherited-members:5556.. autoclass:: Response57   :inherited-members:585960Lower-Lower-Level Classes61-------------------------6263.. autoclass:: requests.PreparedRequest64   :inherited-members:6566.. autoclass:: requests.adapters.HTTPAdapter67   :inherited-members:6869Authentication70--------------7172.. autoclass:: requests.auth.AuthBase73.. autoclass:: requests.auth.HTTPBasicAuth74.. autoclass:: requests.auth.HTTPProxyAuth75.. autoclass:: requests.auth.HTTPDigestAuth76777879Encodings80---------8182.. autofunction:: requests.utils.get_encodings_from_content83.. autofunction:: requests.utils.get_encoding_from_headers84.. autofunction:: requests.utils.get_unicode_from_response858687.. _api-cookies:8889Cookies90-------9192.. autofunction:: requests.utils.dict_from_cookiejar93.. autofunction:: requests.utils.cookiejar_from_dict94.. autofunction:: requests.utils.add_dict_to_cookiejar9596.. autoclass:: requests.cookies.RequestsCookieJar97   :inherited-members:9899.. autoclass:: requests.cookies.CookieConflictError100   :inherited-members:101102103104Status Code Lookup105------------------106107.. autoclass:: requests.codes108109::110111    >>> requests.codes['temporary_redirect']112    307113114    >>> requests.codes.teapot115    418116117    >>> requests.codes['\o/']118    200119120121122Migrating to 1.x123----------------124125This section details the main differences between 0.x and 1.x and is meant126to ease the pain of upgrading.127128129API Changes130~~~~~~~~~~~131132* ``Response.json`` is now a callable and not a property of a response.133134  ::135136      import requests137      r = requests.get('https://github.com/timeline.json')138      r.json()   # This *call* raises an exception if JSON decoding fails139140* The ``Session`` API has changed. Sessions objects no longer take parameters.141  ``Session`` is also now capitalized, but it can still be142  instantiated with a lowercase ``session`` for backwards compatibility.143144  ::145146      s = requests.Session()    # formerly, session took parameters147      s.auth = auth148      s.headers.update(headers)149      r = s.get('http://httpbin.org/headers')150151* All request hooks have been removed except 'response'.152153* Authentication helpers have been broken out into separate modules. See154  requests-oauthlib_ and requests-kerberos_.155156.. _requests-oauthlib: https://github.com/requests/requests-oauthlib157.. _requests-kerberos: https://github.com/requests/requests-kerberos158159* The parameter for streaming requests was changed from ``prefetch`` to160  ``stream`` and the logic was inverted. In addition, ``stream`` is now161  required for raw response reading.162163  ::164165      # in 0.x, passing prefetch=False would accomplish the same thing166      r = requests.get('https://github.com/timeline.json', stream=True)167      for chunk in r.iter_content(8192):168          ...169170* The ``config`` parameter to the requests method has been removed. Some of171  these options are now configured on a ``Session`` such as keep-alive and172  maximum number of redirects. The verbosity option should be handled by173  configuring logging.174175  ::176177      import requests178      import logging179180      # Enabling debugging at http.client level (requests->urllib3->http.client)181      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.182      # the only thing missing will be the response.body which is not logged.183      try: # for Python 3184          from http.client import HTTPConnection185      except ImportError:186          from httplib import HTTPConnection187      HTTPConnection.debuglevel = 1188189      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests190      logging.getLogger().setLevel(logging.DEBUG)191      requests_log = logging.getLogger("requests.packages.urllib3")192      requests_log.setLevel(logging.DEBUG)193      requests_log.propagate = True194195      requests.get('http://httpbin.org/headers')196197198199Licensing200~~~~~~~~~201202One key difference that has nothing to do with the API is a change in the203license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0204license ensures that contributions to Requests are also covered by the Apache2052.0 license.206207.. _ISC: http://opensource.org/licenses/ISC208.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0209210211Migrating to 2.x212----------------213214215Compared with the 1.0 release, there were relatively few backwards216incompatible changes, but there are still a few issues to be aware of with217this major release.218219For more details on the changes in this release including new APIs, links220to the relevant GitHub issues and some of the bug fixes, read Cory's blog_221on the subject.222223.. _blog: http://lukasa.co.uk/2013/09/Requests_20/224225226API Changes227~~~~~~~~~~~228229* There were a couple changes to how Requests handles exceptions.230  ``RequestException`` is now a subclass of ``IOError`` rather than231  ``RuntimeError`` as that more accurately categorizes the type of error.232  In addition, an invalid URL escape sequence now raises a subclass of233  ``RequestException`` rather than a ``ValueError``.234235  ::236237      requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL238239  Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked240  encoding will now raise a Requests ``ChunkedEncodingError`` instead.241242* The proxy API has changed slightly. The scheme for a proxy URL is now243  required.244245  ::246247      proxies = {248        "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead249      }250251      # In requests 1.x, this was legal, in requests 2.x,252      #  this raises requests.exceptions.MissingSchema253      requests.get("http://example.org", proxies=proxies)254255256Behavioural Changes257~~~~~~~~~~~~~~~~~~~~~~~258259* Keys in the ``headers`` dictionary are now native strings on all Python260  versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the261  keys are not native strings (unicode on Python2 or bytestrings on Python 3)262  they will be converted to the native string type assuming UTF-8 encoding.263