Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

443 lines · 13.1 KiB

Last changed by

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

History of this file

Take it

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

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 1–70why, 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. This assumes you already have Requests installed. If you do not,10head over to the :ref:`Installation <install>` section.1112First, make sure that:1314* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`161718Let's get started with some simple examples.192021Make a Request22--------------2324Making a request with Requests is very simple.2526Begin by importing the Requests module::2728 >>> import requests2930Now, let's try to get a webpage. For this example, let's get GitHub's public31timeline ::3233 >>> r = requests.get('https://github.com/timeline.json')3435Now, we have a :class:`Response` object called ``r``. We can get all the36information we need from this object.3738Requests' simple API means that all forms of HTTP request are as obvious. For39example, this is how you make an HTTP POST request::4041 >>> r = requests.post("http://httpbin.org/post")4243Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44OPTIONS? These are all just as simple::4546 >>> r = requests.put("http://httpbin.org/put")47 >>> r = requests.delete("http://httpbin.org/delete")48 >>> r = requests.head("http://httpbin.org/get")49 >>> r = requests.options("http://httpbin.org/get")5051That's all well and good, but it's also only the start of what Requests can52do.535455Passing Parameters In URLs56--------------------------5758You often want to send some sort of data in the URL's query string. If59you were constructing the URL by hand, this data would be given as key/value60pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.61Requests allows you to provide these arguments as a dictionary, using the62``params`` keyword argument. As an example, if you wanted to pass63``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the64following code::6566 >>> payload = {'key1': 'value1', 'key2': 'value2'}67 >>> r = requests.get("http://httpbin.org/get", params=payload)6869You can see that the URL has been correctly encoded by printing the URL::70

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da

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

Merge pull request #1466 from s7v7nislands/fix_docCory Benfieldbefore adoptione0df4b5

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

v1.2.1Kenneth Reitzbefore adoption569b59f

line 73why, one step back
73

Merge pull request #1464 from dpursehouse/document-none-not-sentCory Benfieldbefore adoption3229365

lines 74–76why, one step back
74Note that any dictionary key whose value is ``None`` will not be added to the
75URL's query string.76

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 77–86why, one step back
77
78Response Content79----------------8081We can read the content of the server's response. Consider the GitHub timeline82again::8384 >>> import requests85 >>> r = requests.get('https://github.com/timeline.json')86 >>> r.text

Merge pull request #1466 from s7v7nislands/fix_docCory Benfieldbefore adoptione0df4b5

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

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 88–101why, one step back
88
89Requests will automatically decode content from the server. Most unicode90charsets are seamlessly decoded.9192When you make a request, Requests makes educated guesses about the encoding of93the response based on the HTTP headers. The text encoding guessed by Requests94is used when you access ``r.text``. You can find out what encoding Requests is95using, and change it, using the ``r.encoding`` property::9697 >>> r.encoding98 'utf-8'99 >>> r.encoding = 'ISO-8859-1'100101If you change the encoding, Requests will use the new value of ``r.encoding``

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 102–107why, one step back
102whenever you call ``r.text``. You might want to do this in any situation where
103you can apply special logic to work out what the encoding of the content will104be. For example, HTTP and XML have the ability to specify their encoding in105their body. In situations like this, you should use ``r.content`` to find the106encoding, and then set ``r.encoding``. This will let you use ``r.text`` with107the correct encoding.

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 108–124why, one step back
108
109Requests will also use custom encodings in the event that you need them. If110you have created your own encoding and registered it with the ``codecs``111module, you can simply use the codec name as the value of ``r.encoding`` and112Requests will handle the decoding for you.113114Binary Response Content115-----------------------116117You can also access the response body as bytes, for non-text requests::118119 >>> r.content120 b'[{"repository":{"open_issues":0,"url":"https://github.com/...121122The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.123124For example, to create an image from binary data returned by a request, you can

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

line 125why, one step back
125use the following code::

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 126–159why, one step back
126
127 >>> from PIL import Image128 >>> from StringIO import StringIO129 >>> i = Image.open(StringIO(r.content))130131132JSON Response Content133---------------------134135There's also a builtin JSON decoder, in case you're dealing with JSON data::136137 >>> import requests138 >>> r = requests.get('https://github.com/timeline.json')139 >>> r.json()140 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...141142In case the JSON decoding fails, ``r.json`` raises an exception. For example, if143the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:144No JSON object could be decoded``145146147Raw Response Content148--------------------149150In the rare case that you'd like to get the raw socket response from the151server, you can access ``r.raw``. If you want to do this, make sure you set152``stream=True`` in your initial request. Once you do, you can do this::153154 >>> r = requests.get('https://github.com/timeline.json', stream=True)155 >>> r.raw156 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>157 >>> r.raw.read(10)158 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'159

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

line 160why, one step back
160In general, however, you should use a pattern like this to save what is being

Merge pull request #1695 from sigmavirus24/docsCory Benfieldbefore adoptionff2b496

lines 161–166why, one step back
161streamed to a file::
162163 with open(filename, 'wb') as fd:164 for chunk in r.iter_content(chunk_size):165 fd.write(chunk)166

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 167–169why, one step back
167Using ``Response.iter_content`` will handle a lot of what you would otherwise
168have to handle when using ``Response.raw`` directly. When streaming a169download, the above is the preferred and recommended way to retrieve the

Merge pull request #1695 from sigmavirus24/docsCory Benfieldbefore adoptionff2b496

lines 170–171why, one step back
170content.
171

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 172–192why, one step back
172
173Custom Headers174--------------175176If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the177``headers`` parameter.178179For example, we didn't specify our content-type in the previous example::180181 >>> import json182 >>> url = 'https://api.github.com/some/endpoint'183 >>> payload = {'some': 'data'}184 >>> headers = {'content-type': 'application/json'}185186 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)187188189More complicated POST requests190------------------------------191192Typically, you want to send some form-encoded data — much like an HTML form.

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

line 193why, one step back
193To do this, simply pass a dictionary to the ``data`` argument. Your

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 194–236why, one step back
194dictionary of data will automatically be form-encoded when the request is made::
195196 >>> payload = {'key1': 'value1', 'key2': 'value2'}197 >>> r = requests.post("http://httpbin.org/post", data=payload)198 >>> print r.text199 {200 ...201 "form": {202 "key2": "value2",203 "key1": "value1"204 },205 ...206 }207208There are many times that you want to send data that is not form-encoded. If you pass in a ``string`` instead of a ``dict``, that data will be posted directly.209210For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::211212 >>> import json213 >>> url = 'https://api.github.com/some/endpoint'214 >>> payload = {'some': 'data'}215216 >>> r = requests.post(url, data=json.dumps(payload))217218219POST a Multipart-Encoded File220-----------------------------221222Requests makes it simple to upload Multipart-encoded files::223224 >>> url = 'http://httpbin.org/post'225 >>> files = {'file': open('report.xls', 'rb')}226227 >>> r = requests.post(url, files=files)228 >>> r.text229 {230 ...231 "files": {232 "file": "<censored...binary...data>"233 },234 ...235 }236

Merge pull request #1886 from meteozond/patch-1Cory Benfieldbefore adoption19756d5

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

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 238–239why, one step back
238
239 >>> url = 'http://httpbin.org/post'

Merge pull request #1886 from meteozond/patch-1Cory Benfieldbefore adoption19756d5

line 240why, one step back
240 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 241–266why, one step back
241
242 >>> r = requests.post(url, files=files)243 >>> r.text244 {245 ...246 "files": {247 "file": "<censored...binary...data>"248 },249 ...250 }251252If you want, you can send strings to be received as files::253254 >>> url = 'http://httpbin.org/post'255 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}256257 >>> r = requests.post(url, files=files)258 >>> r.text259 {260 ...261 "files": {262 "file": "some,data,to,send\\nanother,row,to,send\\n"263 },264 ...265 }266

Merge pull request #1870 from sigmavirus24/add-toolbelt-to-docsKenneth Reitzbefore adoption7773b27

lines 267–272why, one step back
267In the event you are posting a very large file as a ``multipart/form-data``
268request, you may want to stream the request. By default, ``requests`` does not 269support this, but there is a separate package which does - 270``requests-toolbelt``. You should read `the toolbelt's documentation 271<https://toolbelt.rtfd.org>`_ for more details about how to use it.272

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 273–288why, one step back
273
274Response Status Codes275---------------------276277We can check the response status code::278279 >>> r = requests.get('http://httpbin.org/get')280 >>> r.status_code281 200282283Requests also comes with a built-in status code lookup object for easy284reference::285286 >>> r.status_code == requests.codes.ok287 True288

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216

line 289why, one step back
289If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 290–323why, one step back
290:class:`Response.raise_for_status()`::
291292 >>> bad_r = requests.get('http://httpbin.org/status/404')293 >>> bad_r.status_code294 404295296 >>> bad_r.raise_for_status()297 Traceback (most recent call last):298 File "requests/models.py", line 832, in raise_for_status299 raise http_error300 requests.exceptions.HTTPError: 404 Client Error301302But, since our ``status_code`` for ``r`` was ``200``, when we call303``raise_for_status()`` we get::304305 >>> r.raise_for_status()306 None307308All is well.309310311Response Headers312----------------313314We can view the server's response headers using a Python dictionary::315316 >>> r.headers317 {318 'content-encoding': 'gzip',319 'transfer-encoding': 'chunked',320 'connection': 'close',321 'server': 'nginx/1.0.4',322 'x-runtime': '148ms',323 'etag': '"e1ca502697e5c9317743dc078f67693f"',

Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c

line 324why, one step back
324 'content-type': 'application/json'

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 325–327why, one step back
325 }
326327The dictionary is special, though: it's made just for HTTP headers. According to

Merge pull request #2087 from Lukasa/2616Ian Cordascobefore adoption326f6ad

lines 328–329why, one step back
328`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names
329are case-insensitive.

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 330–333why, one step back
330
331So, we can access the headers using any capitalization we want::332333 >>> r.headers['Content-Type']

Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c

line 334why, one step back
334 'application/json'

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 335–336why, one step back
335
336 >>> r.headers.get('content-type')

Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c

line 337why, one step back
337 'application/json'

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 338–342why, one step back
338
339340Cookies341-------342

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

line 343why, one step back
343If a response contains some Cookies, you can quickly access them::

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 344–364why, one step back
344
345 >>> url = 'http://example.com/some/cookie/setting/url'346 >>> r = requests.get(url)347348 >>> r.cookies['example_cookie_name']349 'example_cookie_value'350351To send your own cookies to the server, you can use the ``cookies``352parameter::353354 >>> url = 'http://httpbin.org/cookies'355 >>> cookies = dict(cookies_are='working')356357 >>> r = requests.get(url, cookies=cookies)358 >>> r.text359 '{"cookies": {"cookies_are": "working"}}'360361362Redirection and History363-----------------------364

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

line 365why, one step back
365By default Requests will perform location redirection for all verbs except

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da

line 366why, one step back
366HEAD.

v1.2.1Kenneth Reitzbefore adoption569b59f

line 367why, one step back
367

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

line 368why, one step back
368We can use the ``history`` property of the Response object to track redirection.

v1.2.1Kenneth Reitzbefore adoption569b59f

line 369why, one step back
369

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

lines 370–375why, one step back
370The :meth:`Response.history` list contains the :class:`Request` objects that
371were created in order to complete the request. The list is sorted from the372oldest to the most recent request.373374For example, GitHub redirects all HTTP requests to HTTPS::375

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 376–384why, one step back
376 >>> r = requests.get('http://github.com')
377 >>> r.url378 'https://github.com/'379 >>> r.status_code380 200381 >>> r.history382 [<Response [301]>]383384

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da

lines 385–386why, one step back
385If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
386redirection handling with the ``allow_redirects`` parameter::

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 387–393why, one step back
387
388 >>> r = requests.get('http://github.com', allow_redirects=False)389 >>> r.status_code390 301391 >>> r.history392 []393

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da

line 394why, one step back
394If you're using HEAD, you can enable redirection as well::

v1.2.1Kenneth Reitzbefore adoption569b59f

line 395why, one step back
395

Merge pull request #2112 from np-csu/patch-1Ian Cordascobefore adoptionde2cd2e

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

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 397–405why, one step back
397 >>> r.url
398 'https://github.com/'399 >>> r.history400 [<Response [301]>]401402403Timeouts404--------405

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

line 406why, one step back
406You can tell Requests to stop waiting for a response after a given number of

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 407–414why, one step back
407seconds with the ``timeout`` parameter::
408409 >>> requests.get('http://github.com', timeout=0.001)410 Traceback (most recent call last):411 File "<stdin>", line 1, in <module>412 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)413414

Merge pull request #1538 from enkore/patch-1Cory Benfieldbefore adoption0f40290

line 415why, one step back
415.. admonition:: Note

v1.2.1Kenneth Reitzbefore adoption569b59f

line 416why, one step back
416

Merge pull request #1579 from yang/patch-1Cory Benfieldbefore adoptionc1eb702

lines 417–420why, one step back
417 ``timeout`` is not a time limit on the entire response download;
418 rather, an exception is raised if the server has not issued a419 response for ``timeout`` seconds (more precisely, if no bytes have been420 received on the underlying socket for ``timeout`` seconds).

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 421–426why, one step back
421
422423Errors and Exceptions424---------------------425426In the event of a network problem (e.g. DNS failure, refused connection, etc),

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216

line 427why, one step back
427Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.

v1.2.1Kenneth Reitzbefore adoption569b59f

line 428why, one step back
428

Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a

line 429why, one step back
429In the rare event of an invalid HTTP response, Requests will raise an

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216

line 430why, one step back
430:class:`~requests.exceptions.HTTPError` exception.

v1.2.1Kenneth Reitzbefore adoption569b59f

line 431why, one step back
431

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216

lines 432–433why, one step back
432If a request times out, a :class:`~requests.exceptions.Timeout` exception is
433raised.

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 434–435why, one step back
434
435If a request exceeds the configured number of maximum redirections, a

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216

line 436why, one step back
436:class:`~requests.exceptions.TooManyRedirects` exception is raised.

v1.2.1Kenneth Reitzbefore adoption569b59f

lines 437–443why, one step back
437
438All exceptions that Requests explicitly raises inherit from439:class:`requests.exceptions.RequestException`.440441-----------------------442443Ready for more? Check out the :ref:`advanced <advanced>` section.