Skip to content
Myr

api.rst

This file

Path

docs/api.rst

270 lines · 7.2 KiB

Last changed by

Merge pull request #3663 from nateprewitt/fix_cookiejar_from_dict_docs_pathCory Benfieldbefore adoption87e40d1

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.BaseAdapter67   :inherited-members:6869.. autoclass:: requests.adapters.HTTPAdapter70   :inherited-members:7172Authentication73--------------7475.. autoclass:: requests.auth.AuthBase76.. autoclass:: requests.auth.HTTPBasicAuth77.. autoclass:: requests.auth.HTTPProxyAuth78.. autoclass:: requests.auth.HTTPDigestAuth79808182Encodings83---------8485.. autofunction:: requests.utils.get_encodings_from_content86.. autofunction:: requests.utils.get_encoding_from_headers87.. autofunction:: requests.utils.get_unicode_from_response888990.. _api-cookies:9192Cookies93-------9495.. autofunction:: requests.utils.dict_from_cookiejar96.. autofunction:: requests.utils.add_dict_to_cookiejar97.. autofunction:: requests.cookies.cookiejar_from_dict9899.. autoclass:: requests.cookies.RequestsCookieJar100   :inherited-members:101102.. autoclass:: requests.cookies.CookieConflictError103   :inherited-members:104105106107Status Code Lookup108------------------109110.. autoclass:: requests.codes111112::113114    >>> requests.codes['temporary_redirect']115    307116117    >>> requests.codes.teapot118    418119120    >>> requests.codes['\o/']121    200122123124125Migrating to 1.x126----------------127128This section details the main differences between 0.x and 1.x and is meant129to ease the pain of upgrading.130131132API Changes133~~~~~~~~~~~134135* ``Response.json`` is now a callable and not a property of a response.136137  ::138139      import requests140      r = requests.get('https://github.com/timeline.json')141      r.json()   # This *call* raises an exception if JSON decoding fails142143* The ``Session`` API has changed. Sessions objects no longer take parameters.144  ``Session`` is also now capitalized, but it can still be145  instantiated with a lowercase ``session`` for backwards compatibility.146147  ::148149      s = requests.Session()    # formerly, session took parameters150      s.auth = auth151      s.headers.update(headers)152      r = s.get('http://httpbin.org/headers')153154* All request hooks have been removed except 'response'.155156* Authentication helpers have been broken out into separate modules. See157  requests-oauthlib_ and requests-kerberos_.158159.. _requests-oauthlib: https://github.com/requests/requests-oauthlib160.. _requests-kerberos: https://github.com/requests/requests-kerberos161162* The parameter for streaming requests was changed from ``prefetch`` to163  ``stream`` and the logic was inverted. In addition, ``stream`` is now164  required for raw response reading.165166  ::167168      # in 0.x, passing prefetch=False would accomplish the same thing169      r = requests.get('https://github.com/timeline.json', stream=True)170      for chunk in r.iter_content(8192):171          ...172173* The ``config`` parameter to the requests method has been removed. Some of174  these options are now configured on a ``Session`` such as keep-alive and175  maximum number of redirects. The verbosity option should be handled by176  configuring logging.177178  ::179180      import requests181      import logging182183      # Enabling debugging at http.client level (requests->urllib3->http.client)184      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.185      # the only thing missing will be the response.body which is not logged.186      try: # for Python 3187          from http.client import HTTPConnection188      except ImportError:189          from httplib import HTTPConnection190      HTTPConnection.debuglevel = 1191192      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests193      logging.getLogger().setLevel(logging.DEBUG)194      requests_log = logging.getLogger("requests.packages.urllib3")195      requests_log.setLevel(logging.DEBUG)196      requests_log.propagate = True197198      requests.get('http://httpbin.org/headers')199200201202Licensing203~~~~~~~~~204205One key difference that has nothing to do with the API is a change in the206license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0207license ensures that contributions to Requests are also covered by the Apache2082.0 license.209210.. _ISC: http://opensource.org/licenses/ISC211.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0212213214Migrating to 2.x215----------------216217218Compared with the 1.0 release, there were relatively few backwards219incompatible changes, but there are still a few issues to be aware of with220this major release.221222For more details on the changes in this release including new APIs, links223to the relevant GitHub issues and some of the bug fixes, read Cory's blog_224on the subject.225226.. _blog: http://lukasa.co.uk/2013/09/Requests_20/227228229API Changes230~~~~~~~~~~~231232* There were a couple changes to how Requests handles exceptions.233  ``RequestException`` is now a subclass of ``IOError`` rather than234  ``RuntimeError`` as that more accurately categorizes the type of error.235  In addition, an invalid URL escape sequence now raises a subclass of236  ``RequestException`` rather than a ``ValueError``.237238  ::239240      requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL241242  Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked243  encoding will now raise a Requests ``ChunkedEncodingError`` instead.244245* The proxy API has changed slightly. The scheme for a proxy URL is now246  required.247248  ::249250      proxies = {251        "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead252      }253254      # In requests 1.x, this was legal, in requests 2.x,255      #  this raises requests.exceptions.MissingSchema256      requests.get("http://example.org", proxies=proxies)257258259Behavioural Changes260~~~~~~~~~~~~~~~~~~~~~~~261262* Keys in the ``headers`` dictionary are now native strings on all Python263  versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the264  keys are not native strings (unicode on Python 2 or bytestrings on Python 3)265  they will be converted to the native string type assuming UTF-8 encoding.266267* Values in the ``headers`` dictionary should always be strings. This has268  been the project's position since before 1.0 but a recent change269  (since version 2.11.0) enforces this more strictly. It's advised to avoid270  passing header values as unicode when possible.