quickstart.rst
This file
Path
docs/user/quickstart.rst
571 lines · 18.8 KiB
Last changed by
Response.raw.read() returns bytes (#6365)Boris Verkhovskiybefore adoption4618825
History of this fileTake it
The walk stopped after 200 commits: lines older than d2590ee point at it.
Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 1–39why, one step back1.. _quickstart:23Quickstart4==========56.. module:: requests.models78Eager to get started? This page gives a good introduction in how to get started9with Requests.1011First, make sure that:1213* Requests is :ref:`installed <install>`14* Requests is :ref:`up-to-date <updates>`151617Let's get started with some simple examples.181920Make a Request21--------------2223Making a request with Requests is very simple.2425Begin by importing the Requests module::2627 >>> import requests2829Now, let's try to get a webpage. For this example, let's get GitHub's public30timeline::3132 >>> r = requests.get('https://api.github.com/events')3334Now, we have a :class:`Response <requests.Response>` object called ``r``. We can35get all the information we need from this object.3637Requests' simple API means that all forms of HTTP request are as obvious. For38example, this is how you make an HTTP POST request::39Formatting (#5910)Борис Верховскийbefore adoption827b87b
line 40why, one step back40 >>> r = requests.post('https://httpbin.org/post', data={'key': 'value'})Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 41–44why, one step back4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::44Formatting (#5910)Борис Верховскийbefore adoption827b87b
line 45why, one step back45 >>> r = requests.put('https://httpbin.org/put', data={'key': 'value'})Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 46–93why, one step back46 >>> r = requests.delete('https://httpbin.org/delete')47 >>> r = requests.head('https://httpbin.org/get')48 >>> r = requests.options('https://httpbin.org/get')4950That's all well and good, but it's also only the start of what Requests can51do.525354Passing Parameters In URLs55--------------------------5657You often want to send some sort of data in the URL's query string. If58you were constructing the URL by hand, this data would be given as key/value59pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.60Requests allows you to provide these arguments as a dictionary of strings,61using the ``params`` keyword argument. As an example, if you wanted to pass62``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the63following code::6465 >>> payload = {'key1': 'value1', 'key2': 'value2'}66 >>> r = requests.get('https://httpbin.org/get', params=payload)6768You can see that the URL has been correctly encoded by printing the URL::6970 >>> print(r.url)71 https://httpbin.org/get?key2=value2&key1=value17273Note that any dictionary key whose value is ``None`` will not be added to the74URL's query string.7576You can also pass a list of items as a value::7778 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}7980 >>> r = requests.get('https://httpbin.org/get', params=payload)81 >>> print(r.url)82 https://httpbin.org/get?key1=value1&key2=value2&key2=value38384Response Content85----------------8687We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requests9192 >>> r = requests.get('https://api.github.com/events')93 >>> r.textRemove explicit unicode literal in README.md and doc (#5336)Alessio Izzobefore adoptionbebf525
line 94why, one step back94 '[{"repository":{"open_issues":0,"url":"https://github.com/...Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 95–130why, one step back9596Requests will automatically decode content from the server. Most unicode97charsets are seamlessly decoded.9899When you make a request, Requests makes educated guesses about the encoding of100the response based on the HTTP headers. The text encoding guessed by Requests101is used when you access ``r.text``. You can find out what encoding Requests is102using, and change it, using the ``r.encoding`` property::103104 >>> r.encoding105 'utf-8'106 >>> r.encoding = 'ISO-8859-1'107108If you change the encoding, Requests will use the new value of ``r.encoding``109whenever you call ``r.text``. You might want to do this in any situation where110you can apply special logic to work out what the encoding of the content will111be. For example, HTML and XML have the ability to specify their encoding in112their body. In situations like this, you should use ``r.content`` to find the113encoding, and then set ``r.encoding``. This will let you use ``r.text`` with114the correct encoding.115116Requests will also use custom encodings in the event that you need them. If117you have created your own encoding and registered it with the ``codecs``118module, you can simply use the codec name as the value of ``r.encoding`` and119Requests will handle the decoding for you.120121Binary Response Content122-----------------------123124You can also access the response body as bytes, for non-text requests::125126 >>> r.content127 b'[{"repository":{"open_issues":0,"url":"https://github.com/...128129The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.130Add support for brotli decoding (#5783)Дилян Палаузовbefore adoption5351469
line 131why, one step back131The ``br`` transfer-encoding is automatically decoded for you if a Brotli libraryUpdate quickstart.rst : fixing brotlicffi link (#6044)Chavithrabefore adoption24dfbfd
line 132why, one step back132like `brotli <https://pypi.org/project/brotli>`_ or `brotlicffi <https://pypi.org/project/brotlicffi>`_ is installed.Add support for brotli decoding (#5783)Дилян Палаузовbefore adoption5351469
line 133why, one step back133Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 134–151why, one step back134For example, to create an image from binary data returned by a request, you can135use the following code::136137 >>> from PIL import Image138 >>> from io import BytesIO139140 >>> i = Image.open(BytesIO(r.content))141142143JSON Response Content144---------------------145146There's also a builtin JSON decoder, in case you're dealing with JSON data::147148 >>> import requests149150 >>> r = requests.get('https://api.github.com/events')151 >>> r.json()Remove explicit unicode literal in README.md and doc (#5336)Alessio Izzobefore adoptionbebf525
line 152why, one step back152 [{'repository': {'open_issues': 0, 'url': 'https://github.com/...Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 153–155why, one step back153154In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if155the response gets a 204 (No Content), or if the response contains invalid JSON,Fix inconsistent exception type in response.json() method (#5856)Steve Berdybefore adoptiondb575ee
lines 156–158why, one step back156attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception157provides interoperability for multiple exceptions that may be thrown by different158python versions and json serialization libraries.Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 159–179why, one step back159160It should be noted that the success of the call to ``r.json()`` does **not**161indicate the success of the response. Some servers may return a JSON object in a162failed response (e.g. error details with HTTP 500). Such JSON will be decoded163and returned. To check that a request is successful, use164``r.raise_for_status()`` or check ``r.status_code`` is what you expect.165166167Raw Response Content168--------------------169170In the rare case that you'd like to get the raw socket response from the171server, you can access ``r.raw``. If you want to do this, make sure you set172``stream=True`` in your initial request. Once you do, you can do this::173174 >>> r = requests.get('https://api.github.com/events', stream=True)175176 >>> r.raw177 <urllib3.response.HTTPResponse object at 0x101194810>178179 >>> r.raw.read(10)Response.raw.read() returns bytes (#6365)Boris Verkhovskiybefore adoption4618825
line 180why, one step back180 b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 181–220why, one step back181182In general, however, you should use a pattern like this to save what is being183streamed to a file::184185 with open(filename, 'wb') as fd:186 for chunk in r.iter_content(chunk_size=128):187 fd.write(chunk)188189Using ``Response.iter_content`` will handle a lot of what you would otherwise190have to handle when using ``Response.raw`` directly. When streaming a191download, the above is the preferred and recommended way to retrieve the192content. Note that ``chunk_size`` can be freely adjusted to a number that193may better fit your use cases.194195.. note::196197 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 not200 transform the response content. If you really need access to the bytes as they201 were returned, use ``Response.raw``.202203204Custom Headers205--------------206207If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the208``headers`` parameter.209210For example, we didn't specify our user-agent in the previous example::211212 >>> url = 'https://api.github.com/some/endpoint'213 >>> headers = {'user-agent': 'my-app/0.0.1'}214215 >>> r = requests.get(url, headers=headers)216217Note: Custom headers are given less precedence than more specific sources of information. For instance:218219* Authorization headers set with `headers=` will be overridden if credentials220 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``Merge pull request #5643 from tarmath/netrcNate Prewittbefore adoption2f70990
lines 221–222why, one step back221 parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,222 or at the path specified by the `NETRC` environment variable.Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 223–239why, one step back223* Authorization headers will be removed if you get redirected off-host.224* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.225* Content-Length headers will be overridden when we can determine the length of the content.226227Furthermore, 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.228229Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.230231More complicated POST requests232------------------------------233234Typically, you want to send some form-encoded data — much like an HTML form.235To do this, simply pass a dictionary to the ``data`` argument. Your236dictionary of data will automatically be form-encoded when the request is made::237238 >>> payload = {'key1': 'value1', 'key2': 'value2'}239Response.raw.read() returns bytes (#6365)Boris Verkhovskiybefore adoption4618825
line 240why, one step back240 >>> r = requests.post('https://httpbin.org/post', data=payload)Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 241–285why, one step back241 >>> print(r.text)242 {243 ...244 "form": {245 "key2": "value2",246 "key1": "value1"247 },248 ...249 }250251The ``data`` argument can also have multiple values for each key. This can be252done by making ``data`` either a list of tuples or a dictionary with lists253as values. This is particularly useful when the form has multiple elements that254use the same key::255256 >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]257 >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)258 >>> payload_dict = {'key1': ['value1', 'value2']}259 >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)260 >>> print(r1.text)261 {262 ...263 "form": {264 "key1": [265 "value1",266 "value2"267 ]268 },269 ...270 }271 >>> r1.text == r2.text272 True273274There are times that you may want to send data that is not form-encoded. If275you pass in a ``string`` instead of a ``dict``, that data will be posted directly.276277For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::278279 >>> import json280281 >>> url = 'https://api.github.com/some/endpoint'282 >>> payload = {'some': 'data'}283284 >>> r = requests.post(url, data=json.dumps(payload))285Make the `data` vs `json` parameters more clear (#5382)Greg Dubickibefore adoptionab38e2c
lines 286–287why, one step back286Please note that the above code will NOT add the ``Content-Type`` header287(so in particular it will NOT set it to ``application/json``).Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
line 288why, one step back288Make the `data` vs `json` parameters more clear (#5382)Greg Dubickibefore adoptionab38e2c
lines 289–292why, one step back289If you need that header set and you don't want to encode the ``dict`` yourself,290you can also pass it directly using the ``json`` parameter (added in version 2.4.2)291and it will be encoded automatically:292Change documentation website to requests.readthedocs.io (#5236)Sorin Sbarneabefore adoptiond2590ee
lines 293–571why, one step back293 >>> url = 'https://api.github.com/some/endpoint'294 >>> payload = {'some': 'data'}295296 >>> r = requests.post(url, json=payload)297298Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.299300POST a Multipart-Encoded File301-----------------------------302303Requests makes it simple to upload Multipart-encoded files::304305 >>> url = 'https://httpbin.org/post'306 >>> files = {'file': open('report.xls', 'rb')}307308 >>> r = requests.post(url, files=files)309 >>> r.text310 {311 ...312 "files": {313 "file": "<censored...binary...data>"314 },315 ...316 }317318You can set the filename, content_type and headers explicitly::319320 >>> url = 'https://httpbin.org/post'321 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}322323 >>> r = requests.post(url, files=files)324 >>> r.text325 {326 ...327 "files": {328 "file": "<censored...binary...data>"329 },330 ...331 }332333If you want, you can send strings to be received as files::334335 >>> url = 'https://httpbin.org/post'336 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}337338 >>> r = requests.post(url, files=files)339 >>> r.text340 {341 ...342 "files": {343 "file": "some,data,to,send\\nanother,row,to,send\\n"344 },345 ...346 }347348In the event you are posting a very large file as a ``multipart/form-data``349request, you may want to stream the request. By default, ``requests`` does not350support this, but there is a separate package which does -351``requests-toolbelt``. You should read `the toolbelt's documentation352<https://toolbelt.readthedocs.io>`_ for more details about how to use it.353354For sending multiple files in one request refer to the :ref:`advanced <advanced>`355section.356357.. warning:: It is strongly recommended that you open files in :ref:`binary358 mode <tut-files>`. This is because Requests may attempt to provide359 the ``Content-Length`` header for you, and if it does this value360 will be set to the number of *bytes* in the file. Errors may occur361 if you open the file in *text mode*.362363364Response Status Codes365---------------------366367We can check the response status code::368369 >>> r = requests.get('https://httpbin.org/get')370 >>> r.status_code371 200372373Requests also comes with a built-in status code lookup object for easy374reference::375376 >>> r.status_code == requests.codes.ok377 True378379If we made a bad request (a 4XX client error or 5XX server error response), we380can raise it with381:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::382383 >>> bad_r = requests.get('https://httpbin.org/status/404')384 >>> bad_r.status_code385 404386387 >>> bad_r.raise_for_status()388 Traceback (most recent call last):389 File "requests/models.py", line 832, in raise_for_status390 raise http_error391 requests.exceptions.HTTPError: 404 Client Error392393But, since our ``status_code`` for ``r`` was ``200``, when we call394``raise_for_status()`` we get::395396 >>> r.raise_for_status()397 None398399All is well.400401402Response Headers403----------------404405We can view the server's response headers using a Python dictionary::406407 >>> r.headers408 {409 'content-encoding': 'gzip',410 'transfer-encoding': 'chunked',411 'connection': 'close',412 'server': 'nginx/1.0.4',413 'x-runtime': '148ms',414 'etag': '"e1ca502697e5c9317743dc078f67693f"',415 'content-type': 'application/json'416 }417418The dictionary is special, though: it's made just for HTTP headers. According to419`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names420are case-insensitive.421422So, we can access the headers using any capitalization we want::423424 >>> r.headers['Content-Type']425 'application/json'426427 >>> r.headers.get('content-type')428 'application/json'429430It is also special in that the server could have sent the same header multiple431times with different values, but requests combines them so they can be432represented in the dictionary within a single mapping, as per433`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:434435 A recipient MAY combine multiple header fields with the same field name436 into one "field-name: field-value" pair, without changing the semantics437 of the message, by appending each subsequent field value to the combined438 field value in order, separated by a comma.439440Cookies441-------442443If a response contains some Cookies, you can quickly access them::444445 >>> url = 'http://example.com/some/cookie/setting/url'446 >>> r = requests.get(url)447448 >>> r.cookies['example_cookie_name']449 'example_cookie_value'450451To send your own cookies to the server, you can use the ``cookies``452parameter::453454 >>> url = 'https://httpbin.org/cookies'455 >>> cookies = dict(cookies_are='working')456457 >>> r = requests.get(url, cookies=cookies)458 >>> r.text459 '{"cookies": {"cookies_are": "working"}}'460461Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,462which acts like a ``dict`` but also offers a more complete interface,463suitable for use over multiple domains or paths. Cookie jars can464also be passed in to requests::465466 >>> jar = requests.cookies.RequestsCookieJar()467 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')468 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')469 >>> url = 'https://httpbin.org/cookies'470 >>> r = requests.get(url, cookies=jar)471 >>> r.text472 '{"cookies": {"tasty_cookie": "yum"}}'473474475Redirection and History476-----------------------477478By default Requests will perform location redirection for all verbs except479HEAD.480481We can use the ``history`` property of the Response object to track redirection.482483The :attr:`Response.history <requests.Response.history>` list contains the484:class:`Response <requests.Response>` objects that were created in order to485complete the request. The list is sorted from the oldest to the most recent486response.487488For example, GitHub redirects all HTTP requests to HTTPS::489490 >>> r = requests.get('http://github.com/')491492 >>> r.url493 'https://github.com/'494495 >>> r.status_code496 200497498 >>> r.history499 [<Response [301]>]500501502If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable503redirection handling with the ``allow_redirects`` parameter::504505 >>> r = requests.get('http://github.com/', allow_redirects=False)506507 >>> r.status_code508 301509510 >>> r.history511 []512513If you're using HEAD, you can enable redirection as well::514515 >>> r = requests.head('http://github.com/', allow_redirects=True)516517 >>> r.url518 'https://github.com/'519520 >>> r.history521 [<Response [301]>]522523524Timeouts525--------526527You can tell Requests to stop waiting for a response after a given number of528seconds with the ``timeout`` parameter. Nearly all production code should use529this parameter in nearly all requests. Failure to do so can cause your program530to hang indefinitely::531532 >>> requests.get('https://github.com/', timeout=0.001)533 Traceback (most recent call last):534 File "<stdin>", line 1, in <module>535 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)536537538.. admonition:: Note539540 ``timeout`` is not a time limit on the entire response download;541 rather, an exception is raised if the server has not issued a542 response for ``timeout`` seconds (more precisely, if no bytes have been543 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do544 not time out.545546547Errors and Exceptions548---------------------549550In the event of a network problem (e.g. DNS failure, refused connection, etc),551Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.552553:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will554raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request555returned an unsuccessful status code.556557If a request times out, a :exc:`~requests.exceptions.Timeout` exception is558raised.559560If a request exceeds the configured number of maximum redirections, a561:exc:`~requests.exceptions.TooManyRedirects` exception is raised.562563All exceptions that Requests explicitly raises inherit from564:exc:`requests.exceptions.RequestException`.565566-----------------------567568Ready for more? Check out the :ref:`advanced <advanced>` section.569570571If 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.