Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

566 lines · 18.5 KiB

Last changed by

Merge pull request #5777 from cclauss/patch-1Ian Stapleton Cordascobefore adoption5433656

History of this file

Take it

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

Merge pull request #5127 from Unit03/head-allow-redirects-docstringkobayashibefore adoption0b6c110

lines 1–93why, one step back
1.. _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::3940 >>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::4445 >>> 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')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.text

Remove explicit unicode literal in README.md and doc (#5336)Alessio Izzobefore adoptionbebf525

line 94why, one step back
94 '[{"repository":{"open_issues":0,"url":"https://github.com/...

Merge pull request #5127 from Unit03/head-allow-redirects-docstringkobayashibefore adoption0b6c110

lines 95–148why, one step back
95
96Requests 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.130131For example, to create an image from binary data returned by a request, you can132use the following code::133134 >>> from PIL import Image135 >>> from io import BytesIO136137 >>> i = Image.open(BytesIO(r.content))138139140JSON Response Content141---------------------142143There's also a builtin JSON decoder, in case you're dealing with JSON data::144145 >>> import requests146147 >>> r = requests.get('https://api.github.com/events')148 >>> r.json()

Remove explicit unicode literal in README.md and doc (#5336)Alessio Izzobefore adoptionbebf525

line 149why, one step back
149 [{'repository': {'open_issues': 0, 'url': 'https://github.com/...

Merge pull request #5127 from Unit03/head-allow-redirects-docstringkobayashibefore adoption0b6c110

lines 150–152why, one step back
150
151In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if152the response gets a 204 (No Content), or if the response contains invalid JSON,

Merge pull request #5777 from cclauss/patch-1Ian Stapleton Cordascobefore adoption5433656

lines 153–155why, one step back
153attempting ``r.json()`` raises ``simplejson.JSONDecodeError`` if simplejson is
154installed or raises ``ValueError: No JSON object could be decoded`` on Python 2 or155``json.JSONDecodeError`` on Python 3.

Merge pull request #5127 from Unit03/head-allow-redirects-docstringkobayashibefore adoption0b6c110

lines 156–217why, one step back
156
157It 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=``

Merge pull request #5643 from tarmath/netrcNate Prewittbefore adoption2f70990

lines 218–219why, one step back
218 parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,
219 or at the path specified by the `NETRC` environment variable.

Merge pull request #5127 from Unit03/head-allow-redirects-docstringkobayashibefore adoption0b6c110

lines 220–566why, one step back
220* Authorization headers will be removed if you get redirected off-host.
221* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.222* Content-Length headers will be overridden when we can determine the length of the content.223224Furthermore, 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.225226Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.227228More complicated POST requests229------------------------------230231Typically, you want to send some form-encoded data — much like an HTML form.232To do this, simply pass a dictionary to the ``data`` argument. Your233dictionary of data will automatically be form-encoded when the request is made::234235 >>> payload = {'key1': 'value1', 'key2': 'value2'}236237 >>> r = requests.post("https://httpbin.org/post", data=payload)238 >>> print(r.text)239 {240 ...241 "form": {242 "key2": "value2",243 "key1": "value1"244 },245 ...246 }247248The ``data`` argument can also have multiple values for each key. This can be249done by making ``data`` either a list of tuples or a dictionary with lists250as values. This is particularly useful when the form has multiple elements that251use the same key::252253 >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]254 >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)255 >>> payload_dict = {'key1': ['value1', 'value2']}256 >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)257 >>> print(r1.text)258 {259 ...260 "form": {261 "key1": [262 "value1",263 "value2"264 ]265 },266 ...267 }268 >>> r1.text == r2.text269 True270271There are times that you may want to send data that is not form-encoded. If272you pass in a ``string`` instead of a ``dict``, that data will be posted directly.273274For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::275276 >>> import json277278 >>> url = 'https://api.github.com/some/endpoint'279 >>> payload = {'some': 'data'}280281 >>> r = requests.post(url, data=json.dumps(payload))282283Instead of encoding the ``dict`` yourself, you can also pass it directly using284the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::285286 >>> url = 'https://api.github.com/some/endpoint'287 >>> payload = {'some': 'data'}288289 >>> r = requests.post(url, json=payload)290291Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.292293Using the ``json`` parameter in the request will change the ``Content-Type`` in the header to ``application/json``.294295POST a Multipart-Encoded File296-----------------------------297298Requests makes it simple to upload Multipart-encoded files::299300 >>> url = 'https://httpbin.org/post'301 >>> files = {'file': open('report.xls', 'rb')}302303 >>> r = requests.post(url, files=files)304 >>> r.text305 {306 ...307 "files": {308 "file": "<censored...binary...data>"309 },310 ...311 }312313You can set the filename, content_type and headers explicitly::314315 >>> url = 'https://httpbin.org/post'316 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}317318 >>> r = requests.post(url, files=files)319 >>> r.text320 {321 ...322 "files": {323 "file": "<censored...binary...data>"324 },325 ...326 }327328If you want, you can send strings to be received as files::329330 >>> url = 'https://httpbin.org/post'331 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}332333 >>> r = requests.post(url, files=files)334 >>> r.text335 {336 ...337 "files": {338 "file": "some,data,to,send\\nanother,row,to,send\\n"339 },340 ...341 }342343In the event you are posting a very large file as a ``multipart/form-data``344request, you may want to stream the request. By default, ``requests`` does not345support this, but there is a separate package which does -346``requests-toolbelt``. You should read `the toolbelt's documentation347<https://toolbelt.readthedocs.io>`_ for more details about how to use it.348349For sending multiple files in one request refer to the :ref:`advanced <advanced>`350section.351352.. warning:: It is strongly recommended that you open files in :ref:`binary353 mode <tut-files>`. This is because Requests may attempt to provide354 the ``Content-Length`` header for you, and if it does this value355 will be set to the number of *bytes* in the file. Errors may occur356 if you open the file in *text mode*.357358359Response Status Codes360---------------------361362We can check the response status code::363364 >>> r = requests.get('https://httpbin.org/get')365 >>> r.status_code366 200367368Requests also comes with a built-in status code lookup object for easy369reference::370371 >>> r.status_code == requests.codes.ok372 True373374If we made a bad request (a 4XX client error or 5XX server error response), we375can raise it with376:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::377378 >>> bad_r = requests.get('https://httpbin.org/status/404')379 >>> bad_r.status_code380 404381382 >>> bad_r.raise_for_status()383 Traceback (most recent call last):384 File "requests/models.py", line 832, in raise_for_status385 raise http_error386 requests.exceptions.HTTPError: 404 Client Error387388But, since our ``status_code`` for ``r`` was ``200``, when we call389``raise_for_status()`` we get::390391 >>> r.raise_for_status()392 None393394All is well.395396397Response Headers398----------------399400We can view the server's response headers using a Python dictionary::401402 >>> r.headers403 {404 'content-encoding': 'gzip',405 'transfer-encoding': 'chunked',406 'connection': 'close',407 'server': 'nginx/1.0.4',408 'x-runtime': '148ms',409 'etag': '"e1ca502697e5c9317743dc078f67693f"',410 'content-type': 'application/json'411 }412413The dictionary is special, though: it's made just for HTTP headers. According to414`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names415are case-insensitive.416417So, we can access the headers using any capitalization we want::418419 >>> r.headers['Content-Type']420 'application/json'421422 >>> r.headers.get('content-type')423 'application/json'424425It is also special in that the server could have sent the same header multiple426times with different values, but requests combines them so they can be427represented in the dictionary within a single mapping, as per428`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:429430 A recipient MAY combine multiple header fields with the same field name431 into one "field-name: field-value" pair, without changing the semantics432 of the message, by appending each subsequent field value to the combined433 field value in order, separated by a comma.434435Cookies436-------437438If a response contains some Cookies, you can quickly access them::439440 >>> url = 'http://example.com/some/cookie/setting/url'441 >>> r = requests.get(url)442443 >>> r.cookies['example_cookie_name']444 'example_cookie_value'445446To send your own cookies to the server, you can use the ``cookies``447parameter::448449 >>> url = 'https://httpbin.org/cookies'450 >>> cookies = dict(cookies_are='working')451452 >>> r = requests.get(url, cookies=cookies)453 >>> r.text454 '{"cookies": {"cookies_are": "working"}}'455456Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,457which acts like a ``dict`` but also offers a more complete interface,458suitable for use over multiple domains or paths. Cookie jars can459also be passed in to requests::460461 >>> jar = requests.cookies.RequestsCookieJar()462 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')463 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')464 >>> url = 'https://httpbin.org/cookies'465 >>> r = requests.get(url, cookies=jar)466 >>> r.text467 '{"cookies": {"tasty_cookie": "yum"}}'468469470Redirection and History471-----------------------472473By default Requests will perform location redirection for all verbs except474HEAD.475476We can use the ``history`` property of the Response object to track redirection.477478The :attr:`Response.history <requests.Response.history>` list contains the479:class:`Response <requests.Response>` objects that were created in order to480complete the request. The list is sorted from the oldest to the most recent481response.482483For example, GitHub redirects all HTTP requests to HTTPS::484485 >>> r = requests.get('http://github.com/')486487 >>> r.url488 'https://github.com/'489490 >>> r.status_code491 200492493 >>> r.history494 [<Response [301]>]495496497If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable498redirection handling with the ``allow_redirects`` parameter::499500 >>> r = requests.get('http://github.com/', allow_redirects=False)501502 >>> r.status_code503 301504505 >>> r.history506 []507508If you're using HEAD, you can enable redirection as well::509510 >>> r = requests.head('http://github.com/', allow_redirects=True)511512 >>> r.url513 'https://github.com/'514515 >>> r.history516 [<Response [301]>]517518519Timeouts520--------521522You can tell Requests to stop waiting for a response after a given number of523seconds with the ``timeout`` parameter. Nearly all production code should use524this parameter in nearly all requests. Failure to do so can cause your program525to hang indefinitely::526527 >>> requests.get('https://github.com/', timeout=0.001)528 Traceback (most recent call last):529 File "<stdin>", line 1, in <module>530 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)531532533.. admonition:: Note534535 ``timeout`` is not a time limit on the entire response download;536 rather, an exception is raised if the server has not issued a537 response for ``timeout`` seconds (more precisely, if no bytes have been538 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do539 not time out.540541542Errors and Exceptions543---------------------544545In the event of a network problem (e.g. DNS failure, refused connection, etc),546Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.547548:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will549raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request550returned an unsuccessful status code.551552If a request times out, a :exc:`~requests.exceptions.Timeout` exception is553raised.554555If a request exceeds the configured number of maximum redirections, a556:exc:`~requests.exceptions.TooManyRedirects` exception is raised.557558All exceptions that Requests explicitly raises inherit from559:exc:`requests.exceptions.RequestException`.560561-----------------------562563Ready for more? Check out the :ref:`advanced <advanced>` section.564565566If 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.