Debian Codegraph @

docs/api.rst

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