api.rst 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. .. _api:
  2. Developer Interface
  3. ===================
  4. .. module:: requests
  5. This part of the documentation covers all the interfaces of Requests. For
  6. parts where Requests depends on external libraries, we document the most
  7. important right here and provide links to the canonical documentation.
  8. Main Interface
  9. --------------
  10. All of Requests' functionality can be accessed by these 7 methods.
  11. They all return an instance of the :class:`Response <Response>` object.
  12. .. autofunction:: request
  13. .. autofunction:: head
  14. .. autofunction:: get
  15. .. autofunction:: post
  16. .. autofunction:: put
  17. .. autofunction:: patch
  18. .. autofunction:: delete
  19. Exceptions
  20. ----------
  21. .. autoexception:: requests.RequestException
  22. .. autoexception:: requests.ConnectionError
  23. .. autoexception:: requests.HTTPError
  24. .. autoexception:: requests.URLRequired
  25. .. autoexception:: requests.TooManyRedirects
  26. .. autoexception:: requests.ConnectTimeout
  27. .. autoexception:: requests.ReadTimeout
  28. .. autoexception:: requests.Timeout
  29. Request Sessions
  30. ----------------
  31. .. _sessionapi:
  32. .. autoclass:: Session
  33. :inherited-members:
  34. Lower-Level Classes
  35. -------------------
  36. .. autoclass:: requests.Request
  37. :inherited-members:
  38. .. autoclass:: Response
  39. :inherited-members:
  40. Lower-Lower-Level Classes
  41. -------------------------
  42. .. autoclass:: requests.PreparedRequest
  43. :inherited-members:
  44. .. autoclass:: requests.adapters.HTTPAdapter
  45. :inherited-members:
  46. Authentication
  47. --------------
  48. .. autoclass:: requests.auth.AuthBase
  49. .. autoclass:: requests.auth.HTTPBasicAuth
  50. .. autoclass:: requests.auth.HTTPProxyAuth
  51. .. autoclass:: requests.auth.HTTPDigestAuth
  52. Encodings
  53. ---------
  54. .. autofunction:: requests.utils.get_encodings_from_content
  55. .. autofunction:: requests.utils.get_encoding_from_headers
  56. .. autofunction:: requests.utils.get_unicode_from_response
  57. .. _api-cookies:
  58. Cookies
  59. -------
  60. .. autofunction:: requests.utils.dict_from_cookiejar
  61. .. autofunction:: requests.utils.cookiejar_from_dict
  62. .. autofunction:: requests.utils.add_dict_to_cookiejar
  63. .. autoclass:: requests.cookies.RequestsCookieJar
  64. :inherited-members:
  65. .. autoclass:: requests.cookies.CookieConflictError
  66. :inherited-members:
  67. Status Code Lookup
  68. ------------------
  69. .. autoclass:: requests.codes
  70. ::
  71. >>> requests.codes['temporary_redirect']
  72. 307
  73. >>> requests.codes.teapot
  74. 418
  75. >>> requests.codes['\o/']
  76. 200
  77. Migrating to 1.x
  78. ----------------
  79. This section details the main differences between 0.x and 1.x and is meant
  80. to ease the pain of upgrading.
  81. API Changes
  82. ~~~~~~~~~~~
  83. * ``Response.json`` is now a callable and not a property of a response.
  84. ::
  85. import requests
  86. r = requests.get('https://github.com/timeline.json')
  87. r.json() # This *call* raises an exception if JSON decoding fails
  88. * The ``Session`` API has changed. Sessions objects no longer take parameters.
  89. ``Session`` is also now capitalized, but it can still be
  90. instantiated with a lowercase ``session`` for backwards compatibility.
  91. ::
  92. s = requests.Session() # formerly, session took parameters
  93. s.auth = auth
  94. s.headers.update(headers)
  95. r = s.get('http://httpbin.org/headers')
  96. * All request hooks have been removed except 'response'.
  97. * Authentication helpers have been broken out into separate modules. See
  98. requests-oauthlib_ and requests-kerberos_.
  99. .. _requests-oauthlib: https://github.com/requests/requests-oauthlib
  100. .. _requests-kerberos: https://github.com/requests/requests-kerberos
  101. * The parameter for streaming requests was changed from ``prefetch`` to
  102. ``stream`` and the logic was inverted. In addition, ``stream`` is now
  103. required for raw response reading.
  104. ::
  105. # in 0.x, passing prefetch=False would accomplish the same thing
  106. r = requests.get('https://github.com/timeline.json', stream=True)
  107. for chunk in r.iter_content(8192):
  108. ...
  109. * The ``config`` parameter to the requests method has been removed. Some of
  110. these options are now configured on a ``Session`` such as keep-alive and
  111. maximum number of redirects. The verbosity option should be handled by
  112. configuring logging.
  113. ::
  114. import requests
  115. import logging
  116. # Enabling debugging at http.client level (requests->urllib3->http.client)
  117. # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
  118. # the only thing missing will be the response.body which is not logged.
  119. try: # for Python 3
  120. from http.client import HTTPConnection
  121. except ImportError:
  122. from httplib import HTTPConnection
  123. HTTPConnection.debuglevel = 1
  124. logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
  125. logging.getLogger().setLevel(logging.DEBUG)
  126. requests_log = logging.getLogger("requests.packages.urllib3")
  127. requests_log.setLevel(logging.DEBUG)
  128. requests_log.propagate = True
  129. requests.get('http://httpbin.org/headers')
  130. Licensing
  131. ~~~~~~~~~
  132. One key difference that has nothing to do with the API is a change in the
  133. license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0
  134. license ensures that contributions to Requests are also covered by the Apache
  135. 2.0 license.
  136. .. _ISC: http://opensource.org/licenses/ISC
  137. .. _Apache 2.0: http://opensource.org/licenses/Apache-2.0
  138. Migrating to 2.x
  139. ----------------
  140. Compared with the 1.0 release, there were relatively few backwards
  141. incompatible changes, but there are still a few issues to be aware of with
  142. this major release.
  143. For more details on the changes in this release including new APIs, links
  144. to the relevant GitHub issues and some of the bug fixes, read Cory's blog_
  145. on the subject.
  146. .. _blog: http://lukasa.co.uk/2013/09/Requests_20/
  147. API Changes
  148. ~~~~~~~~~~~
  149. * There were a couple changes to how Requests handles exceptions.
  150. ``RequestException`` is now a subclass of ``IOError`` rather than
  151. ``RuntimeError`` as that more accurately categorizes the type of error.
  152. In addition, an invalid URL escape sequence now raises a subclass of
  153. ``RequestException`` rather than a ``ValueError``.
  154. ::
  155. requests.get('http://%zz/') # raises requests.exceptions.InvalidURL
  156. Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked
  157. encoding will now raise a Requests ``ChunkedEncodingError`` instead.
  158. * The proxy API has changed slightly. The scheme for a proxy URL is now
  159. required.
  160. ::
  161. proxies = {
  162. "http": "10.10.1.10:3128", # use http://10.10.1.10:3128 instead
  163. }
  164. # In requests 1.x, this was legal, in requests 2.x,
  165. # this raises requests.exceptions.MissingSchema
  166. requests.get("http://example.org", proxies=proxies)
  167. Behavioural Changes
  168. ~~~~~~~~~~~~~~~~~~~~~~~
  169. * Keys in the ``headers`` dictionary are now native strings on all Python
  170. versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the
  171. keys are not native strings (unicode on Python2 or bytestrings on Python 3)
  172. they will be converted to the native string type assuming UTF-8 encoding.