Debian Codegraph @

docs/user-guide.rst

raw
1 User Guide
2 ==========
3
4 .. currentmodule:: urllib3
5
6 Installing
7 ----------
8
9 urllib3 can be installed with `pip <https://pip.pypa.io>`_
10
11 .. code-block:: bash
12
13 $ python -m pip install urllib3
14
15
16 Making Requests
17 ---------------
18
19 First things first, import the urllib3 module:
20
21 .. code-block:: python
22
23 import urllib3
24
25 You'll need a :class:`~poolmanager.PoolManager` instance to make requests.
26 This object handles all of the details of connection pooling and thread safety
27 so that you don't have to:
28
29 .. code-block:: python
30
31 http = urllib3.PoolManager()
32
33 To make a request use :meth:`~urllib3.PoolManager.request`:
34
35 .. code-block:: python
36
37 import urllib3
38
39 # Creating a PoolManager instance for sending requests.
40 http = urllib3.PoolManager()
41
42 # Sending a GET request and getting back response as HTTPResponse object.
43 resp = http.request("GET", "https://httpbin.org/robots.txt")
44
45 # Print the returned data.
46 print(resp.data)
47 # b"User-agent: *\nDisallow: /deny\n"
48
49 ``request()`` returns a :class:`~response.HTTPResponse` object, the
50 :ref:`response_content` section explains how to handle various responses.
51
52 You can use :meth:`~urllib3.PoolManager.request` to make requests using any
53 HTTP verb:
54
55 .. code-block:: python
56
57 import urllib3
58
59 http = urllib3.PoolManager()
60 resp = http.request(
61 "POST",
62 "https://httpbin.org/post",
63 fields={"hello": "world"} # Add custom form fields
64 )
65
66 print(resp.data)
67 # b"{\n "form": {\n "hello": "world"\n }, ... }
68
69 The :ref:`request_data` section covers sending other kinds of requests data,
70 including JSON, files, and binary data.
71
72 .. note:: For quick scripts and experiments you can also use a top-level ``urllib3.request()``.
73 It uses a module-global ``PoolManager`` instance.
74 Because of that, its side effects could be shared across dependencies relying on it.
75 To avoid side effects, create a new ``PoolManager`` instance and use it instead.
76 In addition, the method does not accept the low-level ``**urlopen_kw`` keyword arguments.
77 System CA certificates are loaded on default.
78
79 .. _response_content:
80
81 Response Content
82 ----------------
83
84 The :class:`~response.HTTPResponse` object provides
85 :attr:`~response.HTTPResponse.status`, :attr:`~response.HTTPResponse.data`, and
86 :attr:`~response.HTTPResponse.headers` attributes:
87
88 .. code-block:: python
89
90 import urllib3
91
92 # Making the request (The request function returns HTTPResponse object)
93 resp = urllib3.request("GET", "https://httpbin.org/ip")
94
95 print(resp.status)
96 # 200
97 print(resp.data)
98 # b"{\n "origin": "104.232.115.37"\n}\n"
99 print(resp.headers)
100 # HTTPHeaderDict({"Content-Length": "32", ...})
101
102 .. _json_content:
103
104 JSON Content
105 ~~~~~~~~~~~~
106 JSON content can be loaded by :meth:`~response.HTTPResponse.json`
107 method of the response:
108
109 .. code-block:: python
110
111 import urllib3
112
113 resp = urllib3.request("GET", "https://httpbin.org/ip")
114
115 print(resp.json())
116 # {"origin": "127.0.0.1"}
117
118 Alternatively, Custom JSON libraries such as `orjson` can be used to encode data,
119 retrieve data by decoding and deserializing the :attr:`~response.HTTPResponse.data`
120 attribute of the request:
121
122 .. code-block:: python
123
124 import orjson
125 import urllib3
126
127 encoded_data = orjson.dumps({"attribute": "value"})
128 resp = urllib3.request(method="POST", url="http://httpbin.org/post", body=encoded_data)
129
130 print(orjson.loads(resp.data)["json"])
131 # {'attribute': 'value'}
132
133 Binary Content
134 ~~~~~~~~~~~~~~
135
136 The :attr:`~response.HTTPResponse.data` attribute of the response is always set
137 to a byte string representing the response content:
138
139 .. code-block:: python
140
141 import urllib3
142
143 resp = urllib3.request("GET", "https://httpbin.org/bytes/8")
144
145 print(resp.data)
146 # b"\xaa\xa5H?\x95\xe9\x9b\x11"
147
148 .. note:: For responses of large or unknown length, it's sometimes better to
149 :ref:`stream <stream>` the response.
150
151 Using io Wrappers with Response Content
152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
153
154 Sometimes you want to use :class:`io.TextIOWrapper` or similar objects like a CSV reader
155 directly with :class:`~response.HTTPResponse` data. Making these two interfaces play nice
156 together requires using the :attr:`~response.HTTPResponse.auto_close` attribute by setting it
157 to ``False``. By default HTTP responses are closed after reading all bytes, this disables that behavior:
158
159 .. code-block:: python
160
161 import io
162 import urllib3
163
164 resp = urllib3.request("GET", "https://example.com", preload_content=False)
165 resp.auto_close = False
166
167 for line in io.TextIOWrapper(resp):
168 print(line)
169 # <!doctype html>
170 # <html>
171 # <head>
172 # ....
173 # </body>
174 # </html>
175
176 .. _request_data:
177
178 Request Data
179 ------------
180
181 Headers
182 ~~~~~~~
183
184 You can specify headers as a dictionary in the ``headers`` argument in :meth:`~urllib3.PoolManager.request`:
185
186 .. code-block:: python
187
188 import urllib3
189
190 resp = urllib3.request(
191 "GET",
192 "https://httpbin.org/headers",
193 headers={
194 "X-Something": "value"
195 }
196 )
197
198 print(resp.json()["headers"])
199 # {"X-Something": "value", ...}
200
201 Or you can use the ``HTTPHeaderDict`` class to create multi-valued HTTP headers:
202
203 .. code-block:: python
204
205 import urllib3
206
207 # Create an HTTPHeaderDict and add headers
208 headers = urllib3.HTTPHeaderDict()
209 headers.add("Accept", "application/json")
210 headers.add("Accept", "text/plain")
211
212 # Make the request using the headers
213 resp = urllib3.request(
214 "GET",
215 "https://httpbin.org/headers",
216 headers=headers
217 )
218
219 print(resp.json()["headers"])
220 # {"Accept": "application/json, text/plain", ...}
221
222 Cookies
223 ~~~~~~~
224
225 Cookies are specified using the ``Cookie`` header with a string containing
226 the ``;`` delimited key-value pairs:
227
228 .. code-block:: python
229
230 import urllib3
231
232 resp = urllib3.request(
233 "GET",
234 "https://httpbin.org/cookies",
235 headers={
236 "Cookie": "session=f3efe9db; id=30"
237 }
238 )
239
240 print(resp.json())
241 # {"cookies": {"id": "30", "session": "f3efe9db"}}
242
243 Note that the ``Cookie`` header will be stripped if the server redirects to a
244 different host.
245
246 Cookies provided by the server are stored in the ``Set-Cookie`` header:
247
248 .. code-block:: python
249
250 import urllib3
251
252 resp = urllib3.request(
253 "GET",
254 "https://httpbin.org/cookies/set/session/f3efe9db",
255 redirect=False
256 )
257
258 print(resp.headers["Set-Cookie"])
259 # session=f3efe9db; Path=/
260
261 Query Parameters
262 ~~~~~~~~~~~~~~~~
263
264 For ``GET``, ``HEAD``, and ``DELETE`` requests, you can simply pass the
265 arguments as a dictionary in the ``fields`` argument to
266 :meth:`~urllib3.PoolManager.request`:
267
268 .. code-block:: python
269
270 import urllib3
271
272 resp = urllib3.request(
273 "GET",
274 "https://httpbin.org/get",
275 fields={"arg": "value"}
276 )
277
278 print(resp.json()["args"])
279 # {"arg": "value"}
280
281 For ``POST`` and ``PUT`` requests, you need to manually encode query parameters
282 in the URL:
283
284 .. code-block:: python
285
286 from urllib.parse import urlencode
287 import urllib3
288
289 # Encode the args into url grammar.
290 encoded_args = urlencode({"arg": "value"})
291
292 # Create a URL with args encoded.
293 url = "https://httpbin.org/post?" + encoded_args
294 resp = urllib3.request("POST", url)
295
296 print(resp.json()["args"])
297 # {"arg": "value"}
298
299
300 .. _form_data:
301
302 Form Data
303 ~~~~~~~~~
304
305 For ``PUT`` and ``POST`` requests, urllib3 will automatically form-encode the
306 dictionary in the ``fields`` argument provided to
307 :meth:`~urllib3.PoolManager.request`:
308
309 .. code-block:: python
310
311 import urllib3
312
313 resp = urllib3.request(
314 "POST",
315 "https://httpbin.org/post",
316 fields={"field": "value"}
317 )
318
319 print(resp.json()["form"])
320 # {"field": "value"}
321
322 .. _json:
323
324 JSON
325 ~~~~
326
327 To send JSON in the body of a request, provide the data in the ``json`` argument to
328 :meth:`~urllib3.PoolManager.request` and urllib3 will automatically encode the data
329 using the ``json`` module with ``UTF-8`` encoding.
330 In addition, when ``json`` is provided, the ``"Content-Type"`` in headers is set to
331 ``"application/json"`` if not specified otherwise.
332
333 .. code-block:: python
334
335 import urllib3
336
337 resp = urllib3.request(
338 "POST",
339 "https://httpbin.org/post",
340 json={"attribute": "value"},
341 headers={"Content-Type": "application/json"}
342 )
343
344 print(resp.json())
345 # {'headers': {'Content-Type': 'application/json', ...},
346 # 'data': '{"attribute":"value"}', 'json': {'attribute': 'value'}, ...}
347
348 Files & Binary Data
349 ~~~~~~~~~~~~~~~~~~~
350
351 For uploading files using ``multipart/form-data`` encoding you can use the same
352 approach as :ref:`form_data` and specify the file field as a tuple of
353 ``(file_name, file_data)``:
354
355 .. code-block:: python
356
357 import urllib3
358
359 # Reading the text file from local storage.
360 with open("example.txt") as fp:
361 file_data = fp.read()
362
363 # Sending the request.
364 resp = urllib3.request(
365 "POST",
366 "https://httpbin.org/post",
367 fields={
368 "filefield": ("example.txt", file_data),
369 }
370 )
371
372 print(resp.json()["files"])
373 # {"filefield": "..."}
374
375 While specifying the filename is not strictly required, it's recommended in
376 order to match browser behavior. You can also pass a third item in the tuple
377 to specify the file's MIME type explicitly:
378
379 .. code-block:: python
380
381 resp = urllib3.request(
382 "POST",
383 "https://httpbin.org/post",
384 fields={
385 "filefield": ("example.txt", file_data, "text/plain"),
386 }
387 )
388
389 For sending raw binary data simply specify the ``body`` argument. It's also
390 recommended to set the ``Content-Type`` header:
391
392 .. code-block:: python
393
394 import urllib3
395
396 with open("/home/samad/example.jpg", "rb") as fp:
397 binary_data = fp.read()
398
399 resp = urllib3.request(
400 "POST",
401 "https://httpbin.org/post",
402 body=binary_data,
403 headers={"Content-Type": "image/jpeg"}
404 )
405
406 print(resp.json()["data"])
407 # data:application/octet-stream;base64,...
408
409 .. _ssl:
410
411 Certificate Verification
412 ------------------------
413
414 .. note:: *New in version 1.25:*
415
416 HTTPS connections are now verified by default (``cert_reqs = "CERT_REQUIRED"``).
417
418 While you can disable certification verification by setting ``cert_reqs = "CERT_NONE"``, it is highly recommend to leave it on.
419
420 Unless otherwise specified urllib3 will try to load the default system certificate stores.
421 The most reliable cross-platform method is to use the `certifi <https://certifi.io/>`_
422 package which provides Mozilla's root certificate bundle:
423
424 .. code-block:: bash
425
426 $ python -m pip install certifi
427
428 Once you have certificates, you can create a :class:`~poolmanager.PoolManager`
429 that verifies certificates when making requests:
430
431 .. code-block:: python
432
433 import certifi
434 import urllib3
435
436 http = urllib3.PoolManager(
437 cert_reqs="CERT_REQUIRED",
438 ca_certs=certifi.where()
439 )
440
441 The :class:`~poolmanager.PoolManager` will automatically handle certificate
442 verification and will raise :class:`~exceptions.SSLError` if verification fails:
443
444 .. code-block:: python
445
446 import certifi
447 import urllib3
448
449 http = urllib3.PoolManager(
450 cert_reqs="CERT_REQUIRED",
451 ca_certs=certifi.where()
452 )
453
454 http.request("GET", "https://httpbin.org/")
455 # (No exception)
456
457 http.request("GET", "https://expired.badssl.com")
458 # urllib3.exceptions.SSLError ...
459
460 .. note:: You can use OS-provided certificates if desired. Just specify the full
461 path to the certificate bundle as the ``ca_certs`` argument instead of
462 ``certifi.where()``. For example, most Linux systems store the certificates
463 at ``/etc/ssl/certs/ca-certificates.crt``. Other operating systems can
464 be `difficult <https://stackoverflow.com/questions/10095676/openssl-reasonable-default-for-trusted-ca-certificates>`_.
465
466 Using Timeouts
467 --------------
468
469 Timeouts allow you to control how long (in seconds) requests are allowed to run
470 before being aborted. In simple cases, you can specify a timeout as a ``float``
471 to :meth:`~urllib3.PoolManager.request`:
472
473 .. code-block:: python
474
475 import urllib3
476
477 resp = urllib3.request(
478 "GET",
479 "https://httpbin.org/delay/3",
480 timeout=4.0
481 )
482
483 print(type(resp))
484 # <class "urllib3.response.HTTPResponse">
485
486 # This request will take more time to process than timeout.
487 urllib3.request(
488 "GET",
489 "https://httpbin.org/delay/3",
490 timeout=2.5
491 )
492 # MaxRetryError caused by ReadTimeoutError
493
494 For more granular control you can use a :class:`~util.timeout.Timeout`
495 instance which lets you specify separate connect and read timeouts:
496
497 .. code-block:: python
498
499 import urllib3
500
501 resp = urllib3.request(
502 "GET",
503 "https://httpbin.org/delay/3",
504 timeout=urllib3.Timeout(connect=1.0)
505 )
506
507 print(type(resp))
508 # <urllib3.response.HTTPResponse>
509
510 urllib3.request(
511 "GET",
512 "https://httpbin.org/delay/3",
513 timeout=urllib3.Timeout(connect=1.0, read=2.0)
514 )
515 # MaxRetryError caused by ReadTimeoutError
516
517
518 If you want all requests to be subject to the same timeout, you can specify
519 the timeout at the :class:`~urllib3.poolmanager.PoolManager` level:
520
521 .. code-block:: python
522
523 import urllib3
524
525 http = urllib3.PoolManager(timeout=3.0)
526
527 http = urllib3.PoolManager(
528 timeout=urllib3.Timeout(connect=1.0, read=2.0)
529 )
530
531 You still override this pool-level timeout by specifying ``timeout`` to
532 :meth:`~urllib3.PoolManager.request`.
533
534 Retrying Requests
535 -----------------
536
537 urllib3 can automatically retry idempotent requests. This same mechanism also
538 handles redirects. You can control the retries using the ``retries`` parameter
539 to :meth:`~urllib3.PoolManager.request`. By default, urllib3 will retry
540 requests 3 times and follow up to 3 redirects.
541
542 To change the number of retries just specify an integer:
543
544 .. code-block:: python
545
546 import urllib3
547
548 urllib3.request("GET", "https://httpbin.org/ip", retries=10)
549
550 To disable all retry and redirect logic specify ``retries=False``:
551
552 .. code-block:: python
553
554 import urllib3
555
556 urllib3.request(
557 "GET",
558 "https://nxdomain.example.com",
559 retries=False
560 )
561 # NewConnectionError
562
563 resp = urllib3.request(
564 "GET",
565 "https://httpbin.org/redirect/1",
566 retries=False
567 )
568
569 print(resp.status)
570 # 302
571
572 To disable redirects but keep the retrying logic, specify ``redirect=False``:
573
574 .. code-block:: python
575
576 resp = urllib3.request(
577 "GET",
578 "https://httpbin.org/redirect/1",
579 redirect=False
580 )
581
582 print(resp.status)
583 # 302
584
585 For more granular control you can use a :class:`~util.retry.Retry` instance.
586 This class allows you far greater control of how requests are retried.
587
588 For example, to do a total of 3 retries, but limit to only 2 redirects:
589
590 .. code-block:: python
591
592 urllib3.request(
593 "GET",
594 "https://httpbin.org/redirect/3",
595 retries=urllib3.Retry(3, redirect=2)
596 )
597 # MaxRetryError
598
599 You can also disable exceptions for too many redirects and just return the
600 ``302`` response:
601
602 .. code-block:: python
603
604 resp = urllib3.request(
605 "GET",
606 "https://httpbin.org/redirect/3",
607 retries=urllib3.Retry(
608 redirect=2,
609 raise_on_redirect=False
610 )
611 )
612
613 print(resp.status)
614 # 302
615
616 If you want all requests to be subject to the same retry policy, you can
617 specify the retry at the :class:`~urllib3.poolmanager.PoolManager` level:
618
619 .. code-block:: python
620
621 import urllib3
622
623 http = urllib3.PoolManager(retries=False)
624
625 http = urllib3.PoolManager(
626 retries=urllib3.Retry(5, redirect=2)
627 )
628
629 You still override this pool-level retry policy by specifying ``retries`` to
630 :meth:`~urllib3.PoolManager.request`.
631
632 Errors & Exceptions
633 -------------------
634
635 urllib3 wraps lower-level exceptions, for example:
636
637 .. code-block:: python
638
639 import urllib3
640
641 try:
642 urllib3.request("GET","https://nx.example.com", retries=False)
643
644 except urllib3.exceptions.NewConnectionError:
645 print("Connection failed.")
646 # Connection failed.
647
648 See :mod:`~urllib3.exceptions` for the full list of all exceptions.
649
650 Logging
651 -------
652
653 If you are using the standard library :mod:`logging` module urllib3 will
654 emit several logs. In some cases this can be undesirable. You can use the
655 standard logger interface to change the log level for urllib3's logger:
656
657 .. code-block:: python
658
659 logging.getLogger("urllib3").setLevel(logging.WARNING)