Skip to content
Myr

api.rst

This file

Path

docs/api.rst

259 lines · 6.9 KiB

Last changed by

Merge pull request #2187 from kevinburke/more-docsKenneth Reitzbefore adoption07bbe21

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    2008384Cookies85~~~~~~~8687.. autofunction:: requests.utils.dict_from_cookiejar88.. autofunction:: requests.utils.cookiejar_from_dict89.. autofunction:: requests.utils.add_dict_to_cookiejar909192Encodings93~~~~~~~~~9495.. autofunction:: requests.utils.get_encodings_from_content96.. autofunction:: requests.utils.get_encoding_from_headers97.. autofunction:: requests.utils.get_unicode_from_response9899100Classes101~~~~~~~102103.. autoclass:: requests.Response104   :inherited-members:105106.. autoclass:: requests.Request107   :inherited-members:108109.. autoclass:: requests.PreparedRequest110   :inherited-members:111112.. _sessionapi:113114.. autoclass:: requests.Session115   :inherited-members:116117.. autoclass:: requests.adapters.HTTPAdapter118   :inherited-members:119120121Migrating to 1.x122----------------123124This section details the main differences between 0.x and 1.x and is meant125to ease the pain of upgrading.126127128API Changes129~~~~~~~~~~~130131* ``Response.json`` is now a callable and not a property of a response.132133  ::134135      import requests136      r = requests.get('https://github.com/timeline.json')137      r.json()   # This *call* raises an exception if JSON decoding fails138139* The ``Session`` API has changed. Sessions objects no longer take parameters.140  ``Session`` is also now capitalized, but it can still be141  instantiated with a lowercase ``session`` for backwards compatibility.142143  ::144145      s = requests.Session()    # formerly, session took parameters146      s.auth = auth147      s.headers.update(headers)148      r = s.get('http://httpbin.org/headers')149150* All request hooks have been removed except 'response'.151152* Authentication helpers have been broken out into separate modules. See153  requests-oauthlib_ and requests-kerberos_.154155.. _requests-oauthlib: https://github.com/requests/requests-oauthlib156.. _requests-kerberos: https://github.com/requests/requests-kerberos157158* The parameter for streaming requests was changed from ``prefetch`` to159  ``stream`` and the logic was inverted. In addition, ``stream`` is now160  required for raw response reading.161162  ::163164      # in 0.x, passing prefetch=False would accomplish the same thing165      r = requests.get('https://github.com/timeline.json', stream=True)166      for chunk in r.iter_content(8192):167          ...168169* The ``config`` parameter to the requests method has been removed. Some of170  these options are now configured on a ``Session`` such as keep-alive and171  maximum number of redirects. The verbosity option should be handled by172  configuring logging.173174  ::175176      import requests177      import logging178179      # these two lines enable debugging at httplib level (requests->urllib3->httplib)180      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.181      # the only thing missing will be the response.body which is not logged.182      import httplib183      httplib.HTTPConnection.debuglevel = 1184185      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests186      logging.getLogger().setLevel(logging.DEBUG)187      requests_log = logging.getLogger("requests.packages.urllib3")188      requests_log.setLevel(logging.DEBUG)189      requests_log.propagate = True190191      requests.get('http://httpbin.org/headers')192193194195Licensing196~~~~~~~~~197198One key difference that has nothing to do with the API is a change in the199license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0200license ensures that contributions to Requests are also covered by the Apache2012.0 license.202203.. _ISC: http://opensource.org/licenses/ISC204.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0205206207Migrating to 2.x208----------------209210211Compared with the 1.0 release, there were relatively few backwards212incompatible changes, but there are still a few issues to be aware of with213this major release.214215For more details on the changes in this release including new APIs, links216to the relevant GitHub issues and some of the bug fixes, read Cory's blog_217on the subject.218219.. _blog: http://lukasa.co.uk/2013/09/Requests_20/220221222API Changes223~~~~~~~~~~~224225* There were a couple changes to how Requests handles exceptions.226  ``RequestException`` is now a subclass of ``IOError`` rather than227  ``RuntimeError`` as that more accurately categorizes the type of error.228  In addition, an invalid URL escape sequence now raises a subclass of229  ``RequestException`` rather than a ``ValueError``.230231  ::232233      requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL234235  Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked236  encoding will now raise a Requests ``ChunkedEncodingError`` instead.237238* The proxy API has changed slightly. The scheme for a proxy URL is now239  required.240241  ::242243      proxies = {244        "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead245      }246247      # In requests 1.x, this was legal, in requests 2.x,248      #  this raises requests.exceptions.MissingSchema249      requests.get("http://example.org", proxies=proxies)250251252Behavioural Changes253~~~~~~~~~~~~~~~~~~~~~~~254255* Keys in the ``headers`` dictionary are now native strings on all Python256  versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the257  keys are not native strings (unicode on Python2 or bytestrings on Python 3)258  they will be converted to the native string type assuming UTF-8 encoding.259