Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

509 lines · 15.8 KiB

Last changed by

Merge pull request #3136 from Natim/readthedocs.ioCory Benfieldbefore adoption252bfa7

History of this file

Take it

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

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 1–39why, 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::39

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

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

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

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

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

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

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 49–65why, one step back
49
50That'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, using the61``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'}

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

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

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 67–78why, one step back
67
68You can see that the URL has been correctly encoded by printing the URL::6970 >>> print(r.url)71 http://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']}

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

lines 79–80why, one step back
79
80 >>> r = requests.get('http://httpbin.org/get', params=payload)

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 81–90why, one step back
81 >>> print(r.url)
82 http://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 requests

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 91why, one step back
91

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 92–135why, one step back
92 >>> r = requests.get('https://api.github.com/events')
93 >>> r.text94 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9596Requests 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, HTTP 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 StringIO import StringIO

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 136why, one step back
136

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 137–145why, one step back
137 >>> i = Image.open(StringIO(r.content))
138139140JSON Response Content141---------------------142143There's also a builtin JSON decoder, in case you're dealing with JSON data::144145 >>> import requests

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 146why, one step back
146

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 147–151why, one step back
147 >>> r = requests.get('https://api.github.com/events')
148 >>> r.json()149 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...150151In case the JSON decoding fails, ``r.json`` raises an exception. For example, if

Merge branch 'hosamaly-master'Cory Benfieldbefore adoptionf7a43e2

lines 152–159why, one step back
152the response gets a 204 (No Content), or if the response contains invalid JSON,
153attempting ``r.json`` raises ``ValueError: No JSON object could be decoded``.154155It should be noted that the success of the call to ``r.json`` does **not**156indicate the success of the response. Some servers may return a JSON object in a157failed response (e.g. error details with HTTP 500). Such JSON will be decoded158and returned. To check that a request is successful, use159``r.raise_for_status()`` or check ``r.status_code`` is what you expect.

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 160–169why, one step back
160
161162Raw Response Content163--------------------164165In the rare case that you'd like to get the raw socket response from the166server, you can access ``r.raw``. If you want to do this, make sure you set167``stream=True`` in your initial request. Once you do, you can do this::168169 >>> r = requests.get('https://api.github.com/events', stream=True)

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 170why, one step back
170

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 171–172why, one step back
171 >>> r.raw
172 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 173why, one step back
173

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 174–204why, one step back
174 >>> r.raw.read(10)
175 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'176177In general, however, you should use a pattern like this to save what is being178streamed to a file::179180 with open(filename, 'wb') as fd:181 for chunk in r.iter_content(chunk_size):182 fd.write(chunk)183184Using ``Response.iter_content`` will handle a lot of what you would otherwise185have to handle when using ``Response.raw`` directly. When streaming a186download, the above is the preferred and recommended way to retrieve the187content.188189190Custom Headers191--------------192193If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the194``headers`` parameter.195196For example, we didn't specify our user-agent in the previous example::197198 >>> url = 'https://api.github.com/some/endpoint'199 >>> headers = {'user-agent': 'my-app/0.0.1'}200201 >>> r = requests.get(url, headers=headers)202203Note: Custom headers are given less precedence than more specific sources of information. For instance:204

Merge pull request #2945 from ibnIrshad/fixdocs-2062Cory Benfieldbefore adoptiona1c9b84

line 205why, one step back
205* Authorization headers set with `headers=` will be overridden if credentials

Merge pull request #2985 from homeworkprod/patch-1Cory Benfieldbefore adoption3f725bc

lines 206–207why, one step back
206 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``
207 parameter.

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 208–222why, one step back
208* Authorization headers will be removed if you get redirected off-host.
209* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.210* Content-Length headers will be overridden when we can determine the length of the content.211212Furthermore, 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.213214215More complicated POST requests216------------------------------217218Typically, you want to send some form-encoded data — much like an HTML form.219To do this, simply pass a dictionary to the ``data`` argument. Your220dictionary of data will automatically be form-encoded when the request is made::221222 >>> payload = {'key1': 'value1', 'key2': 'value2'}

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 223why, one step back
223

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 224–240why, one step back
224 >>> r = requests.post("http://httpbin.org/post", data=payload)
225 >>> print(r.text)226 {227 ...228 "form": {229 "key2": "value2",230 "key1": "value1"231 },232 ...233 }234235There are many times that you want to send data that is not form-encoded. If236you pass in a ``string`` instead of a ``dict``, that data will be posted directly.237238For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::239240 >>> import json

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 241why, one step back
241

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 242–245why, one step back
242 >>> url = 'https://api.github.com/some/endpoint'
243 >>> payload = {'some': 'data'}244245 >>> r = requests.post(url, data=json.dumps(payload))

Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb

line 246why, one step back
246

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

line 247why, one step back
247Instead of encoding the ``dict`` yourself, you can also pass it directly using

Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb

line 248why, one step back
248the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 249–273why, one step back
249
250 >>> url = 'https://api.github.com/some/endpoint'251 >>> payload = {'some': 'data'}252253 >>> r = requests.post(url, json=payload)254255256POST a Multipart-Encoded File257-----------------------------258259Requests makes it simple to upload Multipart-encoded files::260261 >>> url = 'http://httpbin.org/post'262 >>> files = {'file': open('report.xls', 'rb')}263264 >>> r = requests.post(url, files=files)265 >>> r.text266 {267 ...268 "files": {269 "file": "<censored...binary...data>"270 },271 ...272 }273

Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb

line 274why, one step back
274You can set the filename, content_type and headers explicitly::

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 275–307why, one step back
275
276 >>> url = 'http://httpbin.org/post'277 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}278279 >>> r = requests.post(url, files=files)280 >>> r.text281 {282 ...283 "files": {284 "file": "<censored...binary...data>"285 },286 ...287 }288289If you want, you can send strings to be received as files::290291 >>> url = 'http://httpbin.org/post'292 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}293294 >>> r = requests.post(url, files=files)295 >>> r.text296 {297 ...298 "files": {299 "file": "some,data,to,send\\nanother,row,to,send\\n"300 },301 ...302 }303304In the event you are posting a very large file as a ``multipart/form-data``305request, you may want to stream the request. By default, ``requests`` does not306support this, but there is a separate package which does -307``requests-toolbelt``. You should read `the toolbelt's documentation

Merge pull request #3136 from Natim/readthedocs.ioCory Benfieldbefore adoption252bfa7

line 308why, one step back
308<https://toolbelt.readthedocs.io>`_ for more details about how to use it.

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 309–312why, one step back
309
310For sending multiple files in one request refer to the :ref:`advanced <advanced>`311section.312

Merge pull request #2825 from Lukasa/universal_newlinesIan Cordascobefore adoptiond290a9b

lines 313–320why, one step back
313.. warning:: It is strongly recommended that you open files in `binary mode`_.
314 This is because Requests may attempt to provide the315 ``Content-Length`` header for you, and if it does this value will316 be set to the number of *bytes* in the file. Errors may occur if317 you open the file in *text mode*.318319.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files320

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 321–392why, one step back
321
322Response Status Codes323---------------------324325We can check the response status code::326327 >>> r = requests.get('http://httpbin.org/get')328 >>> r.status_code329 200330331Requests also comes with a built-in status code lookup object for easy332reference::333334 >>> r.status_code == requests.codes.ok335 True336337If we made a bad request (a 4XX client error or 5XX server error response), we338can raise it with339:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::340341 >>> bad_r = requests.get('http://httpbin.org/status/404')342 >>> bad_r.status_code343 404344345 >>> bad_r.raise_for_status()346 Traceback (most recent call last):347 File "requests/models.py", line 832, in raise_for_status348 raise http_error349 requests.exceptions.HTTPError: 404 Client Error350351But, since our ``status_code`` for ``r`` was ``200``, when we call352``raise_for_status()`` we get::353354 >>> r.raise_for_status()355 None356357All is well.358359360Response Headers361----------------362363We can view the server's response headers using a Python dictionary::364365 >>> r.headers366 {367 'content-encoding': 'gzip',368 'transfer-encoding': 'chunked',369 'connection': 'close',370 'server': 'nginx/1.0.4',371 'x-runtime': '148ms',372 'etag': '"e1ca502697e5c9317743dc078f67693f"',373 'content-type': 'application/json'374 }375376The dictionary is special, though: it's made just for HTTP headers. According to377`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names378are case-insensitive.379380So, we can access the headers using any capitalization we want::381382 >>> r.headers['Content-Type']383 'application/json'384385 >>> r.headers.get('content-type')386 'application/json'387388It is also special in that the server could have sent the same header multiple389times with different values, but requests combines them so they can be390represented in the dictionary within a single mapping, as per391`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:392

Merge pull request #2758 from mhils/patch-1Cory Benfieldbefore adoption14ee84b

lines 393–396why, one step back
393 A recipient MAY combine multiple header fields with the same field name
394 into one "field-name: field-value" pair, without changing the semantics395 of the message, by appending each subsequent field value to the combined396 field value in order, separated by a comma.

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 397–435why, one step back
397
398Cookies399-------400401If a response contains some Cookies, you can quickly access them::402403 >>> url = 'http://example.com/some/cookie/setting/url'404 >>> r = requests.get(url)405406 >>> r.cookies['example_cookie_name']407 'example_cookie_value'408409To send your own cookies to the server, you can use the ``cookies``410parameter::411412 >>> url = 'http://httpbin.org/cookies'413 >>> cookies = dict(cookies_are='working')414415 >>> r = requests.get(url, cookies=cookies)416 >>> r.text417 '{"cookies": {"cookies_are": "working"}}'418419420Redirection and History421-----------------------422423By default Requests will perform location redirection for all verbs except424HEAD.425426We can use the ``history`` property of the Response object to track redirection.427428The :meth:`Response.history <requests.Response.history>` list contains the429:class:`Response <requests.Response>` objects that were created in order to430complete the request. The list is sorted from the oldest to the most recent431response.432433For example, GitHub redirects all HTTP requests to HTTPS::434435 >>> r = requests.get('http://github.com')

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 436why, one step back
436

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 437–438why, one step back
437 >>> r.url
438 'https://github.com/'

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 439why, one step back
439

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 440–441why, one step back
440 >>> r.status_code
441 200

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 442why, one step back
442

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 443–450why, one step back
443 >>> r.history
444 [<Response [301]>]445446447If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable448redirection handling with the ``allow_redirects`` parameter::449450 >>> r = requests.get('http://github.com', allow_redirects=False)

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 451why, one step back
451

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 452–453why, one step back
452 >>> r.status_code
453 301

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 454why, one step back
454

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 455–460why, one step back
455 >>> r.history
456 []457458If you're using HEAD, you can enable redirection as well::459460 >>> r = requests.head('http://github.com', allow_redirects=True)

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 461why, one step back
461

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 462–463why, one step back
462 >>> r.url
463 'https://github.com/'

cleanup quickstartKenneth Reitzbefore adoptionbf8c831

line 464why, one step back
464

Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4

lines 465–509why, one step back
465 >>> r.history
466 [<Response [301]>]467468469Timeouts470--------471472You can tell Requests to stop waiting for a response after a given number of473seconds with the ``timeout`` parameter::474475 >>> requests.get('http://github.com', timeout=0.001)476 Traceback (most recent call last):477 File "<stdin>", line 1, in <module>478 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)479480481.. admonition:: Note482483 ``timeout`` is not a time limit on the entire response download;484 rather, an exception is raised if the server has not issued a485 response for ``timeout`` seconds (more precisely, if no bytes have been486 received on the underlying socket for ``timeout`` seconds).487488489Errors and Exceptions490---------------------491492In the event of a network problem (e.g. DNS failure, refused connection, etc),493Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.494495In the rare event of an invalid HTTP response, Requests will raise an496:class:`~requests.exceptions.HTTPError` exception.497498If a request times out, a :class:`~requests.exceptions.Timeout` exception is499raised.500501If a request exceeds the configured number of maximum redirections, a502:class:`~requests.exceptions.TooManyRedirects` exception is raised.503504All exceptions that Requests explicitly raises inherit from505:class:`requests.exceptions.RequestException`.506507-----------------------508509Ready for more? Check out the :ref:`advanced <advanced>` section.