Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

430 lines · 12.4 KiB

Last changed by

Merge pull request #1695 from sigmavirus24/docsCory Benfieldbefore adoptionff2b496

History of this file

Take it

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

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/...

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 88–119why, 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``102whenever you call ``r.text``.103104Requests will also use custom encodings in the event that you need them. If105you have created your own encoding and registered it with the ``codecs``106module, you can simply use the codec name as the value of ``r.encoding`` and107Requests will handle the decoding for you.108109Binary Response Content110-----------------------111112You can also access the response body as bytes, for non-text requests::113114 >>> r.content115 b'[{"repository":{"open_issues":0,"url":"https://github.com/...116117The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.118119For example, to create an image from binary data returned by a request, you can

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 121–136why, one step back
121
122 >>> from PIL import Image123 >>> from StringIO import StringIO124 >>> i = Image.open(StringIO(r.content))125126127JSON Response Content128---------------------129130There's also a builtin JSON decoder, in case you're dealing with JSON data::131132 >>> import requests133 >>> r = requests.get('https://github.com/timeline.json')134 >>> r.json()135 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...136

Merge pull request #1296 from sursh/masterKenneth Reitzbefore adoption5b937b3

lines 137–139why, one step back
137In case the JSON decoding fails, ``r.json`` raises an exception. For example, if
138the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:139No JSON object could be decoded``

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 140–148why, one step back
140
141142Raw Response Content143--------------------144145In the rare case that you'd like to get the raw socket response from the146server, you can access ``r.raw``. If you want to do this, make sure you set147``stream=True`` in your initial request. Once you do, you can do this::148

Merge pull request #1230 from davidfischer/trivial-docs-fixKenneth Reitzbefore adoption98ff29f

line 149why, one step back
149 >>> r = requests.get('https://github.com/timeline.json', stream=True)

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 150–154why, one step back
150 >>> r.raw
151 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>152 >>> r.raw.read(10)153 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'154

Merge pull request #1695 from sigmavirus24/docsCory Benfieldbefore adoptionff2b496

lines 155–166why, one step back
155In general, however, you should use a pattern like this to save what is being
156streamed to a file::157158 with open(filename, 'wb') as fd:159 for chunk in r.iter_content(chunk_size):160 fd.write(chunk)161162Using ``Response.iter_content`` will handle a lot of what you would otherwise 163have to handle when using ``Response.raw`` directly. When streaming a 164download, the above is the preferred and recommended way to retrieve the 165content.166

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 167–187why, one step back
167
168Custom Headers169--------------170171If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the172``headers`` parameter.173174For example, we didn't specify our content-type in the previous example::175176 >>> import json177 >>> url = 'https://api.github.com/some/endpoint'178 >>> payload = {'some': 'data'}179 >>> headers = {'content-type': 'application/json'}180181 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)182183184More complicated POST requests185------------------------------186187Typically, you want to send some form-encoded data — much like an HTML form.

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 189–277why, one step back
189dictionary of data will automatically be form-encoded when the request is made::
190191 >>> payload = {'key1': 'value1', 'key2': 'value2'}192 >>> r = requests.post("http://httpbin.org/post", data=payload)193 >>> print r.text194 {195 ...196 "form": {197 "key2": "value2",198 "key1": "value1"199 },200 ...201 }202203There 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.204205For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::206207 >>> import json208 >>> url = 'https://api.github.com/some/endpoint'209 >>> payload = {'some': 'data'}210211 >>> r = requests.post(url, data=json.dumps(payload))212213214POST a Multipart-Encoded File215-----------------------------216217Requests makes it simple to upload Multipart-encoded files::218219 >>> url = 'http://httpbin.org/post'220 >>> files = {'file': open('report.xls', 'rb')}221222 >>> r = requests.post(url, files=files)223 >>> r.text224 {225 ...226 "files": {227 "file": "<censored...binary...data>"228 },229 ...230 }231232You can set the filename explicitly::233234 >>> url = 'http://httpbin.org/post'235 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}236237 >>> r = requests.post(url, files=files)238 >>> r.text239 {240 ...241 "files": {242 "file": "<censored...binary...data>"243 },244 ...245 }246247If you want, you can send strings to be received as files::248249 >>> url = 'http://httpbin.org/post'250 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}251252 >>> r = requests.post(url, files=files)253 >>> r.text254 {255 ...256 "files": {257 "file": "some,data,to,send\\nanother,row,to,send\\n"258 },259 ...260 }261262263Response Status Codes264---------------------265266We can check the response status code::267268 >>> r = requests.get('http://httpbin.org/get')269 >>> r.status_code270 200271272Requests also comes with a built-in status code lookup object for easy273reference::274275 >>> r.status_code == requests.codes.ok276 True277

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 279–312why, one step back
279:class:`Response.raise_for_status()`::
280281 >>> bad_r = requests.get('http://httpbin.org/status/404')282 >>> bad_r.status_code283 404284285 >>> bad_r.raise_for_status()286 Traceback (most recent call last):287 File "requests/models.py", line 832, in raise_for_status288 raise http_error289 requests.exceptions.HTTPError: 404 Client Error290291But, since our ``status_code`` for ``r`` was ``200``, when we call292``raise_for_status()`` we get::293294 >>> r.raise_for_status()295 None296297All is well.298299300Response Headers301----------------302303We can view the server's response headers using a Python dictionary::304305 >>> r.headers306 {307 'content-encoding': 'gzip',308 'transfer-encoding': 'chunked',309 'connection': 'close',310 'server': 'nginx/1.0.4',311 'x-runtime': '148ms',312 'etag': '"e1ca502697e5c9317743dc078f67693f"',

Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 314–322why, one step back
314 }
315316The dictionary is special, though: it's made just for HTTP headers. According to317`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP318Headers are case-insensitive.319320So, we can access the headers using any capitalization we want::321322 >>> r.headers['Content-Type']

Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

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

Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 327–353why, one step back
327
328329Cookies330-------331332If a response contains some Cookies, you can get quick access to them::333334 >>> url = 'http://example.com/some/cookie/setting/url'335 >>> r = requests.get(url)336337 >>> r.cookies['example_cookie_name']338 'example_cookie_value'339340To send your own cookies to the server, you can use the ``cookies``341parameter::342343 >>> url = 'http://httpbin.org/cookies'344 >>> cookies = dict(cookies_are='working')345346 >>> r = requests.get(url, cookies=cookies)347 >>> r.text348 '{"cookies": {"cookies_are": "working"}}'349350351Redirection and History352-----------------------353

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

lines 354–355why, one step back
354Requests will automatically perform location redirection for all verbs except
355HEAD.

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 356–357why, one step back
356
357GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

line 358why, one step back
358of the Response object to track redirection. Let's see what GitHub does::

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 359–367why, one step back
359
360 >>> r = requests.get('http://github.com')361 >>> r.url362 'https://github.com/'363 >>> r.status_code364 200365 >>> r.history366 [<Response [301]>]367

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

lines 368–370why, one step back
368The :class:`Response.history` list contains the :class:`Request` objects that
369were created in order to complete the request. The list is sorted from the370oldest to the most recent request.

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

line 371why, one step back
371

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 374–380why, one step back
374
375 >>> r = requests.get('http://github.com', allow_redirects=False)376 >>> r.status_code377 301378 >>> r.history379 []380

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 382–392why, one step back
382
383 >>> r = requests.post('http://github.com', allow_redirects=True)384 >>> r.url385 'https://github.com/'386 >>> r.history387 [<Response [301]>]388389390Timeouts391--------392

Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 394–401why, one step back
394seconds with the ``timeout`` parameter::
395396 >>> requests.get('http://github.com', timeout=0.001)397 Traceback (most recent call last):398 File "<stdin>", line 1, in <module>399 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)400401

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

line 403why, one step back
403

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 408–413why, one step back
408
409410Errors and Exceptions411---------------------412413In the event of a network problem (e.g. DNS failure, refused connection, etc),

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

line 415why, one step back
415

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

lines 416–417why, one step back
416In the event of the rare invalid HTTP response, Requests will raise an
417:class:`~requests.exceptions.HTTPError` exception.

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

line 418why, one step back
418

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

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

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

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

Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680

lines 424–430why, one step back
424
425All exceptions that Requests explicitly raises inherit from426:class:`requests.exceptions.RequestException`.427428-----------------------429430Ready for more? Check out the :ref:`advanced <advanced>` section.