Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

565 lines · 18.3 KiB

Last changed by

programming quizKenneth Reitzbefore adoption63e7748

History of this file

Take it

The walk stopped after 200 commits: lines older than e4d214d point at it.

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 1–41why, one step back
1.. _quickstart:
23Quickstart4==========56.. image:: https://farm5.staticflickr.com/4259/35163667010_8bfcaef274_k_d.jpg78.. module:: requests.models910Eager to get started? This page gives a good introduction in how to get started11with Requests.1213First, make sure that:1415* Requests is :ref:`installed <install>`16* Requests is :ref:`up-to-date <updates>`171819Let's get started with some simple examples.202122Make a Request23--------------2425Making a request with Requests is very simple.2627Begin by importing the Requests module::2829 >>> import requests3031Now, let's try to get a webpage. For this example, let's get GitHub's public32timeline::3334 >>> r = requests.get('https://api.github.com/events')3536Now, we have a :class:`Response <requests.Response>` object called ``r``. We can37get all the information we need from this object.3839Requests' simple API means that all forms of HTTP request are as obvious. For40example, this is how you make an HTTP POST request::41

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 42why, one step back
42 >>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 43–46why, one step back
43
44Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and45OPTIONS? These are all just as simple::46

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

lines 47–50why, one step back
47 >>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})
48 >>> r = requests.delete('https://httpbin.org/delete')49 >>> r = requests.head('https://httpbin.org/get')50 >>> r = requests.options('https://httpbin.org/get')

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 51–67why, one step back
51
52That's all well and good, but it's also only the start of what Requests can53do.545556Passing Parameters In URLs57--------------------------5859You often want to send some sort of data in the URL's query string. If60you were constructing the URL by hand, this data would be given as key/value61pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.62Requests allows you to provide these arguments as a dictionary of strings,63using the ``params`` keyword argument. As an example, if you wanted to pass64``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the65following code::6667 >>> payload = {'key1': 'value1', 'key2': 'value2'}

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 68why, one step back
68 >>> r = requests.get('https://httpbin.org/get', params=payload)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 69–72why, one step back
69
70You can see that the URL has been correctly encoded by printing the URL::7172 >>> print(r.url)

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 73why, one step back
73 https://httpbin.org/get?key2=value2&key1=value1

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 74–81why, one step back
74
75Note that any dictionary key whose value is ``None`` will not be added to the76URL's query string.7778You can also pass a list of items as a value::7980 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}81

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 82why, one step back
82 >>> r = requests.get('https://httpbin.org/get', params=payload)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

line 83why, one step back
83 >>> print(r.url)

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 84why, one step back
84 https://httpbin.org/get?key1=value1&key2=value2&key2=value3

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 85–235why, one step back
85
86Response Content87----------------8889We can read the content of the server's response. Consider the GitHub timeline90again::9192 >>> import requests9394 >>> r = requests.get('https://api.github.com/events')95 >>> r.text96 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9798Requests will automatically decode content from the server. Most unicode99charsets are seamlessly decoded.100101When you make a request, Requests makes educated guesses about the encoding of102the response based on the HTTP headers. The text encoding guessed by Requests103is used when you access ``r.text``. You can find out what encoding Requests is104using, and change it, using the ``r.encoding`` property::105106 >>> r.encoding107 'utf-8'108 >>> r.encoding = 'ISO-8859-1'109110If you change the encoding, Requests will use the new value of ``r.encoding``111whenever you call ``r.text``. You might want to do this in any situation where112you can apply special logic to work out what the encoding of the content will113be. For example, HTML and XML have the ability to specify their encoding in114their body. In situations like this, you should use ``r.content`` to find the115encoding, and then set ``r.encoding``. This will let you use ``r.text`` with116the correct encoding.117118Requests will also use custom encodings in the event that you need them. If119you have created your own encoding and registered it with the ``codecs``120module, you can simply use the codec name as the value of ``r.encoding`` and121Requests will handle the decoding for you.122123Binary Response Content124-----------------------125126You can also access the response body as bytes, for non-text requests::127128 >>> r.content129 b'[{"repository":{"open_issues":0,"url":"https://github.com/...130131The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.132133For example, to create an image from binary data returned by a request, you can134use the following code::135136 >>> from PIL import Image137 >>> from io import BytesIO138139 >>> i = Image.open(BytesIO(r.content))140141142JSON Response Content143---------------------144145There's also a builtin JSON decoder, in case you're dealing with JSON data::146147 >>> import requests148149 >>> r = requests.get('https://api.github.com/events')150 >>> r.json()151 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...152153In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if154the response gets a 204 (No Content), or if the response contains invalid JSON,155attempting ``r.json()`` raises ``ValueError: No JSON object could be decoded``.156157It should be noted that the success of the call to ``r.json()`` does **not**158indicate the success of the response. Some servers may return a JSON object in a159failed response (e.g. error details with HTTP 500). Such JSON will be decoded160and returned. To check that a request is successful, use161``r.raise_for_status()`` or check ``r.status_code`` is what you expect.162163164Raw Response Content165--------------------166167In the rare case that you'd like to get the raw socket response from the168server, you can access ``r.raw``. If you want to do this, make sure you set169``stream=True`` in your initial request. Once you do, you can do this::170171 >>> r = requests.get('https://api.github.com/events', stream=True)172173 >>> r.raw174 <urllib3.response.HTTPResponse object at 0x101194810>175176 >>> r.raw.read(10)177 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'178179In general, however, you should use a pattern like this to save what is being180streamed to a file::181182 with open(filename, 'wb') as fd:183 for chunk in r.iter_content(chunk_size=128):184 fd.write(chunk)185186Using ``Response.iter_content`` will handle a lot of what you would otherwise187have to handle when using ``Response.raw`` directly. When streaming a188download, the above is the preferred and recommended way to retrieve the189content. Note that ``chunk_size`` can be freely adjusted to a number that190may better fit your use cases.191192.. note::193194 An important note about using ``Response.iter_content`` versus ``Response.raw``.195 ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``196 transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not197 transform the response content. If you really need access to the bytes as they198 were returned, use ``Response.raw``.199200201Custom Headers202--------------203204If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the205``headers`` parameter.206207For example, we didn't specify our user-agent in the previous example::208209 >>> url = 'https://api.github.com/some/endpoint'210 >>> headers = {'user-agent': 'my-app/0.0.1'}211212 >>> r = requests.get(url, headers=headers)213214Note: Custom headers are given less precedence than more specific sources of information. For instance:215216* Authorization headers set with `headers=` will be overridden if credentials217 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``218 parameter.219* Authorization headers will be removed if you get redirected off-host.220* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.221* Content-Length headers will be overridden when we can determine the length of the content.222223Furthermore, 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.224225Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.226227More complicated POST requests228------------------------------229230Typically, you want to send some form-encoded data — much like an HTML form.231To do this, simply pass a dictionary to the ``data`` argument. Your232dictionary of data will automatically be form-encoded when the request is made::233234 >>> payload = {'key1': 'value1', 'key2': 'value2'}235

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 236why, one step back
236 >>> r = requests.post("https://httpbin.org/post", data=payload)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 237–252why, one step back
237 >>> print(r.text)
238 {239 ...240 "form": {241 "key2": "value2",242 "key1": "value1"243 },244 ...245 }246247The ``data`` argument can also have multiple values for each key. This can be248done by making ``data`` either a list of tuples or a dictionary with lists249as values. This is particularly useful when the form has multiple elements that250use the same key::251252 >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 253why, one step back
253 >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

line 254why, one step back
254 >>> payload_dict = {'key1': ['value1', 'value2']}

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 255why, one step back
255 >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 256–298why, one step back
256 >>> print(r1.text)
257 {258 ...259 "form": {260 "key1": [261 "value1",262 "value2"263 ]264 },265 ...266 }267 >>> r1.text == r2.text268 True269270There are times that you may want to send data that is not form-encoded. If271you pass in a ``string`` instead of a ``dict``, that data will be posted directly.272273For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::274275 >>> import json276277 >>> url = 'https://api.github.com/some/endpoint'278 >>> payload = {'some': 'data'}279280 >>> r = requests.post(url, data=json.dumps(payload))281282Instead of encoding the ``dict`` yourself, you can also pass it directly using283the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::284285 >>> url = 'https://api.github.com/some/endpoint'286 >>> payload = {'some': 'data'}287288 >>> r = requests.post(url, json=payload)289290Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.291292Using the ``json`` parameter in the request will change the ``Content-Type`` in the header to ``application/json``.293294POST a Multipart-Encoded File295-----------------------------296297Requests makes it simple to upload Multipart-encoded files::298

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 299why, one step back
299 >>> url = 'https://httpbin.org/post'

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 300–313why, one step back
300 >>> files = {'file': open('report.xls', 'rb')}
301302 >>> r = requests.post(url, files=files)303 >>> r.text304 {305 ...306 "files": {307 "file": "<censored...binary...data>"308 },309 ...310 }311312You can set the filename, content_type and headers explicitly::313

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 314why, one step back
314 >>> url = 'https://httpbin.org/post'

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 315–328why, one step back
315 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
316317 >>> r = requests.post(url, files=files)318 >>> r.text319 {320 ...321 "files": {322 "file": "<censored...binary...data>"323 },324 ...325 }326327If you want, you can send strings to be received as files::328

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 329why, one step back
329 >>> url = 'https://httpbin.org/post'

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 330–350why, one step back
330 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
331332 >>> r = requests.post(url, files=files)333 >>> r.text334 {335 ...336 "files": {337 "file": "some,data,to,send\\nanother,row,to,send\\n"338 },339 ...340 }341342In the event you are posting a very large file as a ``multipart/form-data``343request, you may want to stream the request. By default, ``requests`` does not344support this, but there is a separate package which does -345``requests-toolbelt``. You should read `the toolbelt's documentation346<https://toolbelt.readthedocs.io>`_ for more details about how to use it.347348For sending multiple files in one request refer to the :ref:`advanced <advanced>`349section.350

Merge pull request #4678 from jdufresne/intersphinxNate Prewittbefore adoptiondffd5d4

lines 351–355why, one step back
351.. warning:: It is strongly recommended that you open files in :ref:`binary
352 mode <tut-files>`. This is because Requests may attempt to provide353 the ``Content-Length`` header for you, and if it does this value354 will be set to the number of *bytes* in the file. Errors may occur355 if you open the file in *text mode*.

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 356–362why, one step back
356
357358Response Status Codes359---------------------360361We can check the response status code::362

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 363why, one step back
363 >>> r = requests.get('https://httpbin.org/get')

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 364–376why, one step back
364 >>> r.status_code
365 200366367Requests also comes with a built-in status code lookup object for easy368reference::369370 >>> r.status_code == requests.codes.ok371 True372373If we made a bad request (a 4XX client error or 5XX server error response), we374can raise it with375:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::376

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 377why, one step back
377 >>> bad_r = requests.get('https://httpbin.org/status/404')

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 378–412why, one step back
378 >>> bad_r.status_code
379 404380381 >>> bad_r.raise_for_status()382 Traceback (most recent call last):383 File "requests/models.py", line 832, in raise_for_status384 raise http_error385 requests.exceptions.HTTPError: 404 Client Error386387But, since our ``status_code`` for ``r`` was ``200``, when we call388``raise_for_status()`` we get::389390 >>> r.raise_for_status()391 None392393All is well.394395396Response Headers397----------------398399We can view the server's response headers using a Python dictionary::400401 >>> r.headers402 {403 'content-encoding': 'gzip',404 'transfer-encoding': 'chunked',405 'connection': 'close',406 'server': 'nginx/1.0.4',407 'x-runtime': '148ms',408 'etag': '"e1ca502697e5c9317743dc078f67693f"',409 'content-type': 'application/json'410 }411412The dictionary is special, though: it's made just for HTTP headers. According to

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 413why, one step back
413`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 414–426why, one step back
414are case-insensitive.
415416So, we can access the headers using any capitalization we want::417418 >>> r.headers['Content-Type']419 'application/json'420421 >>> r.headers.get('content-type')422 'application/json'423424It is also special in that the server could have sent the same header multiple425times with different values, but requests combines them so they can be426represented in the dictionary within a single mapping, as per

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 427why, one step back
427`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 428–447why, one step back
428
429 A recipient MAY combine multiple header fields with the same field name430 into one "field-name: field-value" pair, without changing the semantics431 of the message, by appending each subsequent field value to the combined432 field value in order, separated by a comma.433434Cookies435-------436437If a response contains some Cookies, you can quickly access them::438439 >>> url = 'http://example.com/some/cookie/setting/url'440 >>> r = requests.get(url)441442 >>> r.cookies['example_cookie_name']443 'example_cookie_value'444445To send your own cookies to the server, you can use the ``cookies``446parameter::447

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 448why, one step back
448 >>> url = 'https://httpbin.org/cookies'

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 449–462why, one step back
449 >>> cookies = dict(cookies_are='working')
450451 >>> r = requests.get(url, cookies=cookies)452 >>> r.text453 '{"cookies": {"cookies_are": "working"}}'454455Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,456which acts like a ``dict`` but also offers a more complete interface,457suitable for use over multiple domains or paths. Cookie jars can458also be passed in to requests::459460 >>> jar = requests.cookies.RequestsCookieJar()461 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')462 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 463why, one step back
463 >>> url = 'https://httpbin.org/cookies'

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 464–483why, one step back
464 >>> r = requests.get(url, cookies=jar)
465 >>> r.text466 '{"cookies": {"tasty_cookie": "yum"}}'467468469Redirection and History470-----------------------471472By default Requests will perform location redirection for all verbs except473HEAD.474475We can use the ``history`` property of the Response object to track redirection.476477The :attr:`Response.history <requests.Response.history>` list contains the478:class:`Response <requests.Response>` objects that were created in order to479complete the request. The list is sorted from the oldest to the most recent480response.481482For example, GitHub redirects all HTTP requests to HTTPS::483

Merge pull request #4839 from rabdill/patch-1Nate Prewittbefore adoption7c812e9

line 484why, one step back
484 >>> r = requests.get('http://github.com/')

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 485–498why, one step back
485
486 >>> r.url487 'https://github.com/'488489 >>> r.status_code490 200491492 >>> r.history493 [<Response [301]>]494495496If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable497redirection handling with the ``allow_redirects`` parameter::498

Merge pull request #4839 from rabdill/patch-1Nate Prewittbefore adoption7c812e9

line 499why, one step back
499 >>> r = requests.get('http://github.com/', allow_redirects=False)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 500–508why, one step back
500
501 >>> r.status_code502 301503504 >>> r.history505 []506507If you're using HEAD, you can enable redirection as well::508

Merge pull request #4839 from rabdill/patch-1Nate Prewittbefore adoption7c812e9

line 509why, one step back
509 >>> r = requests.head('http://github.com/', allow_redirects=True)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 510–525why, one step back
510
511 >>> r.url512 'https://github.com/'513514 >>> r.history515 [<Response [301]>]516517518Timeouts519--------520521You can tell Requests to stop waiting for a response after a given number of522seconds with the ``timeout`` parameter. Nearly all production code should use523this parameter in nearly all requests. Failure to do so can cause your program524to hang indefinitely::525

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 526why, one step back
526 >>> requests.get('https://github.com/', timeout=0.001)

Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d

lines 527–562why, one step back
527 Traceback (most recent call last):
528 File "<stdin>", line 1, in <module>529 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)530531532.. admonition:: Note533534 ``timeout`` is not a time limit on the entire response download;535 rather, an exception is raised if the server has not issued a536 response for ``timeout`` seconds (more precisely, if no bytes have been537 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do538 not time out.539540541Errors and Exceptions542---------------------543544In the event of a network problem (e.g. DNS failure, refused connection, etc),545Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.546547:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will548raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request549returned an unsuccessful status code.550551If a request times out, a :exc:`~requests.exceptions.Timeout` exception is552raised.553554If a request exceeds the configured number of maximum redirections, a555:exc:`~requests.exceptions.TooManyRedirects` exception is raised.556557All exceptions that Requests explicitly raises inherit from558:exc:`requests.exceptions.RequestException`.559560-----------------------561562Ready for more? Check out the :ref:`advanced <advanced>` section.

programming quizKenneth Reitzbefore adoption63e7748

lines 563–565why, one step back
563
564565If you're on the job market, consider taking `this programming quiz <https://triplebyte.com/a/b1i2FB8/requests-docs-1>`_. A substantial donation will be made to this project, if you find a job through this platform.