Skip to content
Myr

api.rst

This file

Path

docs/api.rst

260 lines · 7.1 KiB

Last changed by

Merge pull request #1 from requests/masterMaina Nickbefore adoption3a831be

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.. automodule:: requests.status_codes113114115Migrating to 1.x116----------------117118This section details the main differences between 0.x and 1.x and is meant119to ease the pain of upgrading.120121122API Changes123~~~~~~~~~~~124125* ``Response.json`` is now a callable and not a property of a response.126127  ::128129      import requests130      r = requests.get('https://github.com/timeline.json')131      r.json()   # This *call* raises an exception if JSON decoding fails132133* The ``Session`` API has changed. Sessions objects no longer take parameters.134  ``Session`` is also now capitalized, but it can still be135  instantiated with a lowercase ``session`` for backwards compatibility.136137  ::138139      s = requests.Session()    # formerly, session took parameters140      s.auth = auth141      s.headers.update(headers)142      r = s.get('https://httpbin.org/headers')143144* All request hooks have been removed except 'response'.145146* Authentication helpers have been broken out into separate modules. See147  requests-oauthlib_ and requests-kerberos_.148149.. _requests-oauthlib: https://github.com/requests/requests-oauthlib150.. _requests-kerberos: https://github.com/requests/requests-kerberos151152* The parameter for streaming requests was changed from ``prefetch`` to153  ``stream`` and the logic was inverted. In addition, ``stream`` is now154  required for raw response reading.155156  ::157158      # in 0.x, passing prefetch=False would accomplish the same thing159      r = requests.get('https://github.com/timeline.json', stream=True)160      for chunk in r.iter_content(8192):161          ...162163* The ``config`` parameter to the requests method has been removed. Some of164  these options are now configured on a ``Session`` such as keep-alive and165  maximum number of redirects. The verbosity option should be handled by166  configuring logging.167168  ::169170      import requests171      import logging172173      # Enabling debugging at http.client level (requests->urllib3->http.client)174      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.175      # the only thing missing will be the response.body which is not logged.176      try: # for Python 3177          from http.client import HTTPConnection178      except ImportError:179          from httplib import HTTPConnection180      HTTPConnection.debuglevel = 1181182      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests183      logging.getLogger().setLevel(logging.DEBUG)184      requests_log = logging.getLogger("urllib3")185      requests_log.setLevel(logging.DEBUG)186      requests_log.propagate = True187188      requests.get('https://httpbin.org/headers')189190191192Licensing193~~~~~~~~~194195One key difference that has nothing to do with the API is a change in the196license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0197license ensures that contributions to Requests are also covered by the Apache1982.0 license.199200.. _ISC: https://opensource.org/licenses/ISC201.. _Apache 2.0: https://opensource.org/licenses/Apache-2.0202203204Migrating to 2.x205----------------206207208Compared with the 1.0 release, there were relatively few backwards209incompatible changes, but there are still a few issues to be aware of with210this major release.211212For more details on the changes in this release including new APIs, links213to the relevant GitHub issues and some of the bug fixes, read Cory's blog_214on the subject.215216.. _blog: https://lukasa.co.uk/2013/09/Requests_20/217218219API Changes220~~~~~~~~~~~221222* There were a couple changes to how Requests handles exceptions.223  ``RequestException`` is now a subclass of ``IOError`` rather than224  ``RuntimeError`` as that more accurately categorizes the type of error.225  In addition, an invalid URL escape sequence now raises a subclass of226  ``RequestException`` rather than a ``ValueError``.227228  ::229230      requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL231232  Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked233  encoding will now raise a Requests ``ChunkedEncodingError`` instead.234235* The proxy API has changed slightly. The scheme for a proxy URL is now236  required.237238  ::239240      proxies = {241        "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead242      }243244      # In requests 1.x, this was legal, in requests 2.x,245      #  this raises requests.exceptions.MissingSchema246      requests.get("http://example.org", proxies=proxies)247248249Behavioural Changes250~~~~~~~~~~~~~~~~~~~~~~~251252* Keys in the ``headers`` dictionary are now native strings on all Python253  versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the254  keys are not native strings (unicode on Python 2 or bytestrings on Python 3)255  they will be converted to the native string type assuming UTF-8 encoding.256257* Values in the ``headers`` dictionary should always be strings. This has258  been the project's position since before 1.0 but a recent change259  (since version 2.11.0) enforces this more strictly. It's advised to avoid260  passing header values as unicode when possible.