Debian Codegraph @

docs/user/quickstart.rst

raw
1 .. _quickstart:
2
3 Quickstart
4 ==========
5
6 .. module:: requests.models
7
8 Eager to get started? This page gives a good introduction in how to get started
9 with Requests.
10
11 First, make sure that:
12
13 * Requests is :ref:`installed <install>`
14 * Requests is :ref:`up-to-date <updates>`
15
16
17 Let's get started with some simple examples.
18
19
20 Make a Request
21 --------------
22
23 Making a request with Requests is very simple.
24
25 Begin by importing the Requests module::
26
27 >>> import requests
28
29 Now, let's try to get a webpage. For this example, let's get GitHub's public
30 timeline::
31
32 >>> r = requests.get('https://api.github.com/events')
33
34 Now, we have a :class:`Response <requests.Response>` object called ``r``. We can
35 get all the information we need from this object.
36
37 Requests' simple API means that all forms of HTTP request are as obvious. For
38 example, this is how you make an HTTP POST request::
39
40 >>> r = requests.post('https://httpbin.org/post', data={'key': 'value'})
41
42 Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
43 OPTIONS? These are all just as simple::
44
45 >>> r = requests.put('https://httpbin.org/put', data={'key': 'value'})
46 >>> r = requests.delete('https://httpbin.org/delete')
47 >>> r = requests.head('https://httpbin.org/get')
48 >>> r = requests.options('https://httpbin.org/get')
49
50 That's all well and good, but it's also only the start of what Requests can
51 do.
52
53
54 Passing Parameters In URLs
55 --------------------------
56
57 You often want to send some sort of data in the URL's query string. If
58 you were constructing the URL by hand, this data would be given as key/value
59 pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.
60 Requests allows you to provide these arguments as a dictionary of strings,
61 using the ``params`` keyword argument. As an example, if you wanted to pass
62 ``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the
63 following code::
64
65 >>> payload = {'key1': 'value1', 'key2': 'value2'}
66 >>> r = requests.get('https://httpbin.org/get', params=payload)
67
68 You can see that the URL has been correctly encoded by printing the URL::
69
70 >>> print(r.url)
71 https://httpbin.org/get?key2=value2&key1=value1
72
73 Note that any dictionary key whose value is ``None`` will not be added to the
74 URL's query string.
75
76 You can also pass a list of items as a value::
77
78 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
79
80 >>> r = requests.get('https://httpbin.org/get', params=payload)
81 >>> print(r.url)
82 https://httpbin.org/get?key1=value1&key2=value2&key2=value3
83
84 Response Content
85 ----------------
86
87 We can read the content of the server's response. Consider the GitHub timeline
88 again::
89
90 >>> import requests
91
92 >>> r = requests.get('https://api.github.com/events')
93 >>> r.text
94 '[{"repository":{"open_issues":0,"url":"https://github.com/...
95
96 Requests will automatically decode content from the server. Most unicode
97 charsets are seamlessly decoded.
98
99 When you make a request, Requests makes educated guesses about the encoding of
100 the response based on the HTTP headers. The text encoding guessed by Requests
101 is used when you access ``r.text``. You can find out what encoding Requests is
102 using, and change it, using the ``r.encoding`` property::
103
104 >>> r.encoding
105 'utf-8'
106 >>> r.encoding = 'ISO-8859-1'
107
108 If you change the encoding, Requests will use the new value of ``r.encoding``
109 whenever you call ``r.text``. You might want to do this in any situation where
110 you can apply special logic to work out what the encoding of the content will
111 be. For example, HTML and XML have the ability to specify their encoding in
112 their body. In situations like this, you should use ``r.content`` to find the
113 encoding, and then set ``r.encoding``. This will let you use ``r.text`` with
114 the correct encoding.
115
116 Requests will also use custom encodings in the event that you need them. If
117 you have created your own encoding and registered it with the ``codecs``
118 module, you can simply use the codec name as the value of ``r.encoding`` and
119 Requests will handle the decoding for you.
120
121 Binary Response Content
122 -----------------------
123
124 You can also access the response body as bytes, for non-text requests::
125
126 >>> r.content
127 b'[{"repository":{"open_issues":0,"url":"https://github.com/...
128
129 The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.
130
131 The ``br`` transfer-encoding is automatically decoded for you if a Brotli library
132 like `brotli <https://pypi.org/project/brotli>`_ or `brotlicffi <https://pypi.org/project/brotlicffi>`_ is installed.
133
134 For example, to create an image from binary data returned by a request, you can
135 use the following code::
136
137 >>> from PIL import Image
138 >>> from io import BytesIO
139
140 >>> i = Image.open(BytesIO(r.content))
141
142
143 JSON Response Content
144 ---------------------
145
146 There's also a builtin JSON decoder, in case you're dealing with JSON data::
147
148 >>> import requests
149
150 >>> r = requests.get('https://api.github.com/events')
151 >>> r.json()
152 [{'repository': {'open_issues': 0, 'url': 'https://github.com/...
153
154 In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if
155 the response gets a 204 (No Content), or if the response contains invalid JSON,
156 attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception
157 provides interoperability for multiple exceptions that may be thrown by different
158 python versions and json serialization libraries.
159
160 It should be noted that the success of the call to ``r.json()`` does **not**
161 indicate the success of the response. Some servers may return a JSON object in a
162 failed response (e.g. error details with HTTP 500). Such JSON will be decoded
163 and returned. To check that a request is successful, use
164 ``r.raise_for_status()`` or check ``r.status_code`` is what you expect.
165
166
167 Raw Response Content
168 --------------------
169
170 In the rare case that you'd like to get the raw socket response from the
171 server, you can access ``r.raw``. If you want to do this, make sure you set
172 ``stream=True`` in your initial request. Once you do, you can do this::
173
174 >>> r = requests.get('https://api.github.com/events', stream=True)
175
176 >>> r.raw
177 <urllib3.response.HTTPResponse object at 0x101194810>
178
179 >>> r.raw.read(10)
180 b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
181
182 In general, however, you should use a pattern like this to save what is being
183 streamed to a file::
184
185 with open(filename, 'wb') as fd:
186 for chunk in r.iter_content(chunk_size=128):
187 fd.write(chunk)
188
189 Using ``Response.iter_content`` will handle a lot of what you would otherwise
190 have to handle when using ``Response.raw`` directly. When streaming a
191 download, the above is the preferred and recommended way to retrieve the
192 content. Note that ``chunk_size`` can be freely adjusted to a number that
193 may better fit your use cases.
194
195 .. note::
196
197 An important note about using ``Response.iter_content`` versus ``Response.raw``.
198 ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``
199 transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not
200 transform the response content. If you really need access to the bytes as they
201 were returned, use ``Response.raw``.
202
203
204 .. _custom-headers:
205
206 Custom Headers
207 --------------
208
209 If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the
210 ``headers`` parameter.
211
212 For example, we didn't specify our user-agent in the previous example::
213
214 >>> url = 'https://api.github.com/some/endpoint'
215 >>> headers = {'user-agent': 'my-app/0.0.1'}
216
217 >>> r = requests.get(url, headers=headers)
218
219 Note: Custom headers are given less precedence than more specific sources of information. For instance:
220
221 * Authorization headers set with `headers=` will be overridden if credentials
222 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``
223 parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,
224 or at the path specified by the `NETRC` environment variable.
225 Check details in :ref:`netrc authentication <authentication>`.
226 * Authorization headers will be removed if you get redirected off-host.
227 * Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.
228 * Content-Length headers will be overridden when we can determine the length of the content.
229
230 Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.
231
232 Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.
233
234 More complicated POST requests
235 ------------------------------
236
237 Typically, you want to send some form-encoded data — much like an HTML form.
238 To do this, simply pass a dictionary to the ``data`` argument. Your
239 dictionary of data will automatically be form-encoded when the request is made::
240
241 >>> payload = {'key1': 'value1', 'key2': 'value2'}
242
243 >>> r = requests.post('https://httpbin.org/post', data=payload)
244 >>> print(r.text)
245 {
246 ...
247 "form": {
248 "key2": "value2",
249 "key1": "value1"
250 },
251 ...
252 }
253
254 The ``data`` argument can also have multiple values for each key. This can be
255 done by making ``data`` either a list of tuples or a dictionary with lists
256 as values. This is particularly useful when the form has multiple elements that
257 use the same key::
258
259 >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
260 >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
261 >>> payload_dict = {'key1': ['value1', 'value2']}
262 >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)
263 >>> print(r1.text)
264 {
265 ...
266 "form": {
267 "key1": [
268 "value1",
269 "value2"
270 ]
271 },
272 ...
273 }
274 >>> # httpbin may embed non-deterministic metadata,
275 >>> # so we only compare our submitted data here.
276 >>> r1.json()['form'] == r2.json()['form']
277 True
278
279 There are times that you may want to send data that is not form-encoded. If
280 you pass in a ``string`` instead of a ``dict``, that data will be posted directly.
281
282 For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::
283
284 >>> import json
285
286 >>> url = 'https://api.github.com/some/endpoint'
287 >>> payload = {'some': 'data'}
288
289 >>> r = requests.post(url, data=json.dumps(payload))
290
291 Please note that the above code will NOT add the ``Content-Type`` header
292 (so in particular it will NOT set it to ``application/json``).
293
294 If you need that header set and you don't want to encode the ``dict`` yourself,
295 you can also pass it directly using the ``json`` parameter (added in version 2.4.2)
296 and it will be encoded automatically:
297
298 >>> url = 'https://api.github.com/some/endpoint'
299 >>> payload = {'some': 'data'}
300
301 >>> r = requests.post(url, json=payload)
302
303 Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.
304
305 POST a Multipart-Encoded File
306 -----------------------------
307
308 Requests makes it simple to upload Multipart-encoded files::
309
310 >>> url = 'https://httpbin.org/post'
311 >>> files = {'file': open('report.xls', 'rb')}
312
313 >>> r = requests.post(url, files=files)
314 >>> r.text
315 {
316 ...
317 "files": {
318 "file": "<censored...binary...data>"
319 },
320 ...
321 }
322
323 You can set the filename, content_type and headers explicitly::
324
325 >>> url = 'https://httpbin.org/post'
326 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
327
328 >>> r = requests.post(url, files=files)
329 >>> r.text
330 {
331 ...
332 "files": {
333 "file": "<censored...binary...data>"
334 },
335 ...
336 }
337
338 If you want, you can send strings to be received as files::
339
340 >>> url = 'https://httpbin.org/post'
341 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
342
343 >>> r = requests.post(url, files=files)
344 >>> r.text
345 {
346 ...
347 "files": {
348 "file": "some,data,to,send\\nanother,row,to,send\\n"
349 },
350 ...
351 }
352
353 In the event you are posting a very large file as a ``multipart/form-data``
354 request, you may want to stream the request. By default, ``requests`` does not
355 support this, but there is a separate package which does -
356 ``requests-toolbelt``. You should read `the toolbelt's documentation
357 <https://toolbelt.readthedocs.io>`_ for more details about how to use it.
358
359 For sending multiple files in one request refer to the :ref:`advanced <advanced>`
360 section.
361
362 .. warning:: It is strongly recommended that you open files in :ref:`binary
363 mode <tut-files>`. This is because Requests may attempt to provide
364 the ``Content-Length`` header for you, and if it does this value
365 will be set to the number of *bytes* in the file. Errors may occur
366 if you open the file in *text mode*.
367
368
369 Response Status Codes
370 ---------------------
371
372 We can check the response status code::
373
374 >>> r = requests.get('https://httpbin.org/get')
375 >>> r.status_code
376 200
377
378 Requests also comes with a built-in status code lookup object for easy
379 reference::
380
381 >>> r.status_code == requests.codes.ok
382 True
383
384 If we made a bad request (a 4XX client error or 5XX server error response), we
385 can raise it with
386 :meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::
387
388 >>> bad_r = requests.get('https://httpbin.org/status/404')
389 >>> bad_r.status_code
390 404
391
392 >>> bad_r.raise_for_status()
393 Traceback (most recent call last):
394 File "requests/models.py", line 832, in raise_for_status
395 raise http_error
396 requests.exceptions.HTTPError: 404 Client Error
397
398 But, since our ``status_code`` for ``r`` was ``200``, when we call
399 ``raise_for_status()`` we get::
400
401 >>> r.raise_for_status()
402 None
403
404 All is well.
405
406
407 Response Headers
408 ----------------
409
410 We can view the server's response headers using a Python dictionary::
411
412 >>> r.headers
413 {
414 'content-encoding': 'gzip',
415 'transfer-encoding': 'chunked',
416 'connection': 'close',
417 'server': 'nginx/1.0.4',
418 'x-runtime': '148ms',
419 'etag': '"e1ca502697e5c9317743dc078f67693f"',
420 'content-type': 'application/json'
421 }
422
423 The dictionary is special, though: it's made just for HTTP headers. According to
424 `RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names
425 are case-insensitive.
426
427 So, we can access the headers using any capitalization we want::
428
429 >>> r.headers['Content-Type']
430 'application/json'
431
432 >>> r.headers.get('content-type')
433 'application/json'
434
435 It is also special in that the server could have sent the same header multiple
436 times with different values, but requests combines them so they can be
437 represented in the dictionary within a single mapping, as per
438 `RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:
439
440 A recipient MAY combine multiple header fields with the same field name
441 into one "field-name: field-value" pair, without changing the semantics
442 of the message, by appending each subsequent field value to the combined
443 field value in order, separated by a comma.
444
445 Cookies
446 -------
447
448 If a response contains some Cookies, you can quickly access them::
449
450 >>> url = 'http://example.com/some/cookie/setting/url'
451 >>> r = requests.get(url)
452
453 >>> r.cookies['example_cookie_name']
454 'example_cookie_value'
455
456 To send your own cookies to the server, you can use the ``cookies``
457 parameter::
458
459 >>> url = 'https://httpbin.org/cookies'
460 >>> cookies = dict(cookies_are='working')
461
462 >>> r = requests.get(url, cookies=cookies)
463 >>> r.text
464 '{"cookies": {"cookies_are": "working"}}'
465
466 Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,
467 which acts like a ``dict`` but also offers a more complete interface,
468 suitable for use over multiple domains or paths. Cookie jars can
469 also be passed in to requests::
470
471 >>> jar = requests.cookies.RequestsCookieJar()
472 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
473 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
474 >>> url = 'https://httpbin.org/cookies'
475 >>> r = requests.get(url, cookies=jar)
476 >>> r.text
477 '{"cookies": {"tasty_cookie": "yum"}}'
478
479
480 Redirection and History
481 -----------------------
482
483 By default Requests will perform location redirection for all verbs except
484 HEAD.
485
486 We can use the ``history`` property of the Response object to track redirection.
487
488 The :attr:`Response.history <requests.Response.history>` list contains the
489 :class:`Response <requests.Response>` objects that were created in order to
490 complete the request. The list is sorted from the oldest to the most recent
491 response.
492
493 For example, GitHub redirects all HTTP requests to HTTPS::
494
495 >>> r = requests.get('http://github.com/')
496
497 >>> r.url
498 'https://github.com/'
499
500 >>> r.status_code
501 200
502
503 >>> r.history
504 [<Response [301]>]
505
506
507 If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
508 redirection handling with the ``allow_redirects`` parameter::
509
510 >>> r = requests.get('http://github.com/', allow_redirects=False)
511
512 >>> r.status_code
513 301
514
515 >>> r.history
516 []
517
518 If you're using HEAD, you can enable redirection as well::
519
520 >>> r = requests.head('http://github.com/', allow_redirects=True)
521
522 >>> r.url
523 'https://github.com/'
524
525 >>> r.history
526 [<Response [301]>]
527
528
529 Timeouts
530 --------
531
532 You can tell Requests to stop waiting for a response after a given number of
533 seconds with the ``timeout`` parameter. Nearly all production code should use
534 this parameter in nearly all requests. Failure to do so can cause your program
535 to hang indefinitely::
536
537 >>> requests.get('https://github.com/', timeout=0.001)
538 Traceback (most recent call last):
539 File "<stdin>", line 1, in <module>
540 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
541
542
543 .. admonition:: Note
544
545 ``timeout`` is not a time limit on the entire response download;
546 rather, an exception is raised if the server has not issued a
547 response for ``timeout`` seconds (more precisely, if no bytes have been
548 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do
549 not time out.
550
551
552 Errors and Exceptions
553 ---------------------
554
555 In the event of a network problem (e.g. DNS failure, refused connection, etc),
556 Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.
557
558 :meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will
559 raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request
560 returned an unsuccessful status code.
561
562 If a request times out, a :exc:`~requests.exceptions.Timeout` exception is
563 raised.
564
565 If a request exceeds the configured number of maximum redirections, a
566 :exc:`~requests.exceptions.TooManyRedirects` exception is raised.
567
568 All exceptions that Requests explicitly raises inherit from
569 :exc:`requests.exceptions.RequestException`.
570
571 -----------------------
572
573 Ready for more? Check out the :ref:`advanced <advanced>` section.