Skip to content
Myr

api.rst

This file

Path

docs/api.rst

268 lines · 7.3 KiB

Last changed by

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

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:464748Exceptions49~~~~~~~~~~5051.. autoexception:: requests.exceptions.RequestException52.. autoexception:: requests.exceptions.ConnectionError53.. autoexception:: requests.exceptions.HTTPError54.. autoexception:: requests.exceptions.URLRequired55.. autoexception:: requests.exceptions.TooManyRedirects56.. autoexception:: requests.exceptions.Timeout575859Status Code Lookup60~~~~~~~~~~~~~~~~~~6162.. autofunction:: requests.codes6364::6566    >>> requests.codes['temporary_redirect']67    3076869    >>> requests.codes.teapot70    4187172    >>> requests.codes['\o/']73    2007475Cookies76~~~~~~~7778.. autofunction:: requests.utils.dict_from_cookiejar79.. autofunction:: requests.utils.cookiejar_from_dict80.. autofunction:: requests.utils.add_dict_to_cookiejar818283Encodings84~~~~~~~~~8586.. autofunction:: requests.utils.get_encodings_from_content87.. autofunction:: requests.utils.get_encoding_from_headers88.. autofunction:: requests.utils.get_unicode_from_response899091Classes92~~~~~~~9394.. autoclass:: requests.Response95   :inherited-members:9697.. autoclass:: requests.Request98   :inherited-members:99100.. autoclass:: requests.PreparedRequest101   :inherited-members:102103.. _sessionapi:104105.. autoclass:: requests.Session106   :inherited-members:107108.. autoclass:: requests.adapters.HTTPAdapter109   :inherited-members:110111112Migrating to 1.x113----------------114115This section details the main differences between 0.x and 1.x and is meant116to ease the pain of upgrading.117118119API Changes120~~~~~~~~~~~121122* ``Response.json`` is now a callable and not a property of a response.123124  ::125126      import requests127      r = requests.get('https://github.com/timeline.json')128      r.json()   # This *call* raises an exception if JSON decoding fails129130* The ``Session`` API has changed. Sessions objects no longer take parameters.131  ``Session`` is also now capitalized, but it can still be132  instantiated with a lowercase ``session`` for backwards compatibility.133134  ::135136      s = requests.Session()    # formerly, session took parameters137      s.auth = auth138      s.headers.update(headers)139      r = s.get('http://httpbin.org/headers')140141* All request hooks have been removed except 'response'.142143* Authentication helpers have been broken out into separate modules. See144  requests-oauthlib_ and requests-kerberos_.145146.. _requests-oauthlib: https://github.com/requests/requests-oauthlib147.. _requests-kerberos: https://github.com/requests/requests-kerberos148149* The parameter for streaming requests was changed from ``prefetch`` to150  ``stream`` and the logic was inverted. In addition, ``stream`` is now151  required for raw response reading.152153  ::154155      # in 0.x, passing prefetch=False would accomplish the same thing156      r = requests.get('https://github.com/timeline.json', stream=True)157      for chunk in r.iter_content(8192):158          ...159160* The ``config`` parameter to the requests method has been removed. Some of161  these options are now configured on a ``Session`` such as keep-alive and162  maximum number of redirects. The verbosity option should be handled by163  configuring logging.164165  ::166167      import requests168      import logging169170      # these two lines enable debugging at httplib level (requests->urllib3->httplib)171      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.172      # the only thing missing will be the response.body which is not logged.173      import httplib174      httplib.HTTPConnection.debuglevel = 1175176      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests177      logging.getLogger().setLevel(logging.DEBUG)178      requests_log = logging.getLogger("requests.packages.urllib3")179      requests_log.setLevel(logging.DEBUG)180      requests_log.propagate = True181182      requests.get('http://httpbin.org/headers')183184185186Licensing187~~~~~~~~~188189One key difference that has nothing to do with the API is a change in the190license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0191license ensures that contributions to Requests are also covered by the Apache1922.0 license.193194.. _ISC: http://opensource.org/licenses/ISC195.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0196197198Migrating to 2.x199----------------200201202Compared with the 1.0 release, there were relatively few backwards203incompatible changes, but there are still a few issues to be aware of with204this major release.205206For more details on the changes in this release including new APIs, links207to the relevant GitHub issues and some of the bug fixes, read Cory's blog_208on the subject.209210.. _blog: http://lukasa.co.uk/2013/09/Requests_20/211212213API Changes214~~~~~~~~~~~215216* There were a couple changes to how Requests handles exceptions.217  ``RequestException`` is now a subclass of ``IOError`` rather than218  ``RuntimeError`` as that more accurately categorizes the type of error.219  In addition, an invalid URL escape sequence now raises a subclass of220  ``RequestException`` rather than a ``ValueError``.221222  ::223224      requests.get('http://%zz/')   # raises requests.exceptions.InvalidURL225226  Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked227  encoding will now raise a Requests ``ChunkedEncodingError`` instead.228229* The proxy API has changed slightly. The scheme for a proxy URL is now230  required.231232  ::233234      proxies = {235        "http": "10.10.1.10:3128",    # use http://10.10.1.10:3128 instead236      }237238      # In requests 1.x, this was legal, in requests 2.x,239      #  this raises requests.exceptions.MissingSchema240      requests.get("http://example.org", proxies=proxies)241242243Behavioral Changes244~~~~~~~~~~~~~~~~~~245246* Keys in the ``headers`` dictionary are now native strings on all Python247  versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the248  keys are not native strings (unicode on Python2 or bytestrings on Python 3)249  they will be converted to the native string type assuming UTF-8 encoding.250251* Timeouts behave slightly differently. On streaming requests, the timeout252  only applies to the connection attempt. On regular requests, the timeout253  is applied to the connection process and on to all attempts to read data from254  the underlying socket. It does *not* apply to the total download time for the255  request.256257  ::258259      tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'260261      # One second timeout for the connection attempt262      # Unlimited time to download the tarball263      r = requests.get(tarball_url, stream=True, timeout=1)264265      # One second timeout for the connection attempt266      # Another full second timeout to download the tarball267      r = requests.get(tarball_url, timeout=1)268