api.rst
This file
Path
docs/api.rst
275 lines · 7.5 KiB
Last changed by
Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
History of this fileTake 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.Timeout646566Status Code Lookup67~~~~~~~~~~~~~~~~~~6869.. autofunction:: requests.codes7071::7273 >>> requests.codes['temporary_redirect']74 3077576 >>> requests.codes.teapot77 4187879 >>> requests.codes['\o/']80 2008182Cookies83~~~~~~~8485.. autofunction:: requests.utils.dict_from_cookiejar86.. autofunction:: requests.utils.cookiejar_from_dict87.. autofunction:: requests.utils.add_dict_to_cookiejar888990Encodings91~~~~~~~~~9293.. autofunction:: requests.utils.get_encodings_from_content94.. autofunction:: requests.utils.get_encoding_from_headers95.. autofunction:: requests.utils.get_unicode_from_response969798Classes99~~~~~~~100101.. autoclass:: requests.Response102 :inherited-members:103104.. autoclass:: requests.Request105 :inherited-members:106107.. autoclass:: requests.PreparedRequest108 :inherited-members:109110.. _sessionapi:111112.. autoclass:: requests.Session113 :inherited-members:114115.. autoclass:: requests.adapters.HTTPAdapter116 :inherited-members:117118119Migrating to 1.x120----------------121122This section details the main differences between 0.x and 1.x and is meant123to ease the pain of upgrading.124125126API Changes127~~~~~~~~~~~128129* ``Response.json`` is now a callable and not a property of a response.130131 ::132133 import requests134 r = requests.get('https://github.com/timeline.json')135 r.json() # This *call* raises an exception if JSON decoding fails136137* The ``Session`` API has changed. Sessions objects no longer take parameters.138 ``Session`` is also now capitalized, but it can still be139 instantiated with a lowercase ``session`` for backwards compatibility.140141 ::142143 s = requests.Session() # formerly, session took parameters144 s.auth = auth145 s.headers.update(headers)146 r = s.get('http://httpbin.org/headers')147148* All request hooks have been removed except 'response'.149150* Authentication helpers have been broken out into separate modules. See151 requests-oauthlib_ and requests-kerberos_.152153.. _requests-oauthlib: https://github.com/requests/requests-oauthlib154.. _requests-kerberos: https://github.com/requests/requests-kerberos155156* The parameter for streaming requests was changed from ``prefetch`` to157 ``stream`` and the logic was inverted. In addition, ``stream`` is now158 required for raw response reading.159160 ::161162 # in 0.x, passing prefetch=False would accomplish the same thing163 r = requests.get('https://github.com/timeline.json', stream=True)164 for chunk in r.iter_content(8192):165 ...166167* The ``config`` parameter to the requests method has been removed. Some of168 these options are now configured on a ``Session`` such as keep-alive and169 maximum number of redirects. The verbosity option should be handled by170 configuring logging.171172 ::173174 import requests175 import logging176177 # these two lines enable debugging at httplib level (requests->urllib3->httplib)178 # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.179 # the only thing missing will be the response.body which is not logged.180 import httplib181 httplib.HTTPConnection.debuglevel = 1182183 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests184 logging.getLogger().setLevel(logging.DEBUG)185 requests_log = logging.getLogger("requests.packages.urllib3")186 requests_log.setLevel(logging.DEBUG)187 requests_log.propagate = True188189 requests.get('http://httpbin.org/headers')190191192193Licensing194~~~~~~~~~195196One key difference that has nothing to do with the API is a change in the197license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0198license ensures that contributions to Requests are also covered by the Apache1992.0 license.200201.. _ISC: http://opensource.org/licenses/ISC202.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0203204205Migrating to 2.x206----------------207208209Compared with the 1.0 release, there were relatively few backwards210incompatible changes, but there are still a few issues to be aware of with211this major release.212213For more details on the changes in this release including new APIs, links214to the relevant GitHub issues and some of the bug fixes, read Cory's blog_215on the subject.216217.. _blog: http://lukasa.co.uk/2013/09/Requests_20/218219220API Changes221~~~~~~~~~~~222223* There were a couple changes to how Requests handles exceptions.224 ``RequestException`` is now a subclass of ``IOError`` rather than225 ``RuntimeError`` as that more accurately categorizes the type of error.226 In addition, an invalid URL escape sequence now raises a subclass of227 ``RequestException`` rather than a ``ValueError``.228229 ::230231 requests.get('http://%zz/') # raises requests.exceptions.InvalidURL232233 Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked234 encoding will now raise a Requests ``ChunkedEncodingError`` instead.235236* The proxy API has changed slightly. The scheme for a proxy URL is now237 required.238239 ::240241 proxies = {242 "http": "10.10.1.10:3128", # use http://10.10.1.10:3128 instead243 }244245 # In requests 1.x, this was legal, in requests 2.x,246 # this raises requests.exceptions.MissingSchema247 requests.get("http://example.org", proxies=proxies)248249250Behavioral Changes251~~~~~~~~~~~~~~~~~~252253* Keys in the ``headers`` dictionary are now native strings on all Python254 versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the255 keys are not native strings (unicode on Python2 or bytestrings on Python 3)256 they will be converted to the native string type assuming UTF-8 encoding.257258* Timeouts behave slightly differently. On streaming requests, the timeout259 only applies to the connection attempt. On regular requests, the timeout260 is applied to the connection process and on to all attempts to read data from261 the underlying socket. It does *not* apply to the total download time for the262 request.263264 ::265266 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'267268 # One second timeout for the connection attempt269 # Unlimited time to download the tarball270 r = requests.get(tarball_url, stream=True, timeout=1)271272 # One second timeout for the connection attempt273 # Another full second timeout to download the tarball274 r = requests.get(tarball_url, timeout=1)275