Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

464 lines · 14.1 KiB

Last changed by

Merge pull request #2453 from requiredfield/masterCory Benfieldbefore adoption6f3c91b

History of this file

Take it

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 1–8why, one step back
1.. _quickstart:
23Quickstart4==========56.. module:: requests.models78Eager to get started? This page gives a good introduction in how to get started

Merge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515

line 9why, one step back
9with Requests.

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 10–31why, one step back
10
11First, 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 ::31

Merge pull request #2183 from Lukasa/docupdateKenneth Reitzbefore adoption7e24176

line 32why, one step back
32 >>> r = requests.get('https://api.github.com/events')

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

line 33why, one step back
33

Merge pull request #2213 from kennethreitz/req-rspCory Benfieldbefore adoption2416e23

line 34why, one step back
34Now, we have a :class:`Response <requests.Response>` object called ``r``. We can

Merge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515

line 35why, one step back
35get all the information we need from this object.

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 36–75why, one step back
36
37Requests' 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("http://httpbin.org/post")4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::4445 >>> r = requests.put("http://httpbin.org/put")46 >>> r = requests.delete("http://httpbin.org/delete")47 >>> r = requests.head("http://httpbin.org/get")48 >>> r = requests.options("http://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, 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'}66 >>> r = requests.get("http://httpbin.org/get", params=payload)6768You 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.75

Merge pull request #2437 from tomscytale/docs_query_param_arrayCory Benfieldbefore adoptionc7beb70

lines 76–82why, one step back
76In order to pass a list of items as a value you must mark the key as
77referring to a list like string by appending ``[]`` to the key::7879 >>> payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}80 >>> r = requests.get("http://httpbin.org/get", params=payload)81 >>> print(r.url)82 http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 83–90why, one step back
83
84Response Content85----------------8687We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requests

Fixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f

line 91why, one step back
91 >>> r = requests.get('https://api.github.com/events')

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 92–143why, one step back
92 >>> r.text
93 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9495Requests will automatically decode content from the server. Most unicode96charsets are seamlessly decoded.9798When you make a request, Requests makes educated guesses about the encoding of99the response based on the HTTP headers. The text encoding guessed by Requests100is used when you access ``r.text``. You can find out what encoding Requests is101using, and change it, using the ``r.encoding`` property::102103 >>> r.encoding104 'utf-8'105 >>> r.encoding = 'ISO-8859-1'106107If you change the encoding, Requests will use the new value of ``r.encoding``108whenever you call ``r.text``. You might want to do this in any situation where109you can apply special logic to work out what the encoding of the content will110be. For example, HTTP and XML have the ability to specify their encoding in111their body. In situations like this, you should use ``r.content`` to find the112encoding, and then set ``r.encoding``. This will let you use ``r.text`` with113the correct encoding.114115Requests will also use custom encodings in the event that you need them. If116you have created your own encoding and registered it with the ``codecs``117module, you can simply use the codec name as the value of ``r.encoding`` and118Requests will handle the decoding for you.119120Binary Response Content121-----------------------122123You can also access the response body as bytes, for non-text requests::124125 >>> r.content126 b'[{"repository":{"open_issues":0,"url":"https://github.com/...127128The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.129130For example, to create an image from binary data returned by a request, you can131use the following code::132133 >>> from PIL import Image134 >>> from StringIO import StringIO135 >>> i = Image.open(StringIO(r.content))136137138JSON Response Content139---------------------140141There's also a builtin JSON decoder, in case you're dealing with JSON data::142143 >>> import requests

Fixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f

line 144why, one step back
144 >>> r = requests.get('https://api.github.com/events')

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 145–159why, one step back
145 >>> r.json()
146 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...147148In case the JSON decoding fails, ``r.json`` raises an exception. For example, if149the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:150No JSON object could be decoded``151152153Raw Response Content154--------------------155156In the rare case that you'd like to get the raw socket response from the157server, you can access ``r.raw``. If you want to do this, make sure you set158``stream=True`` in your initial request. Once you do, you can do this::159

Fixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f

line 160why, one step back
160 >>> r = requests.get('https://api.github.com/events', stream=True)

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 161–203why, one step back
161 >>> r.raw
162 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>163 >>> r.raw.read(10)164 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'165166In general, however, you should use a pattern like this to save what is being167streamed to a file::168169 with open(filename, 'wb') as fd:170 for chunk in r.iter_content(chunk_size):171 fd.write(chunk)172173Using ``Response.iter_content`` will handle a lot of what you would otherwise174have to handle when using ``Response.raw`` directly. When streaming a175download, the above is the preferred and recommended way to retrieve the176content.177178179Custom Headers180--------------181182If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the183``headers`` parameter.184185For example, we didn't specify our content-type in the previous example::186187 >>> import json188 >>> url = 'https://api.github.com/some/endpoint'189 >>> payload = {'some': 'data'}190 >>> headers = {'content-type': 'application/json'}191192 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)193194195More complicated POST requests196------------------------------197198Typically, you want to send some form-encoded data — much like an HTML form.199To do this, simply pass a dictionary to the ``data`` argument. Your200dictionary of data will automatically be form-encoded when the request is made::201202 >>> payload = {'key1': 'value1', 'key2': 'value2'}203 >>> r = requests.post("http://httpbin.org/post", data=payload)

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 204why, one step back
204 >>> print(r.text)

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 205–213why, one step back
205 {
206 ...207 "form": {208 "key2": "value2",209 "key1": "value1"210 },211 ...212 }213

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 214–215why, one step back
214There are many times that you want to send data that is not form-encoded. If
215you pass in a ``string`` instead of a ``dict``, that data will be posted directly.

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 216–243why, one step back
216
217For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::218219 >>> import json220 >>> url = 'https://api.github.com/some/endpoint'221 >>> payload = {'some': 'data'}222223 >>> r = requests.post(url, data=json.dumps(payload))224225226POST a Multipart-Encoded File227-----------------------------228229Requests makes it simple to upload Multipart-encoded files::230231 >>> url = 'http://httpbin.org/post'232 >>> files = {'file': open('report.xls', 'rb')}233234 >>> r = requests.post(url, files=files)235 >>> r.text236 {237 ...238 "files": {239 "file": "<censored...binary...data>"240 },241 ...242 }243

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

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

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 248–273why, one step back
248
249 >>> r = requests.post(url, files=files)250 >>> r.text251 {252 ...253 "files": {254 "file": "<censored...binary...data>"255 },256 ...257 }258259If you want, you can send strings to be received as files::260261 >>> url = 'http://httpbin.org/post'262 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}263264 >>> r = requests.post(url, files=files)265 >>> r.text266 {267 ...268 "files": {269 "file": "some,data,to,send\\nanother,row,to,send\\n"270 },271 ...272 }273

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

lines 274–277why, one step back
274In the event you are posting a very large file as a ``multipart/form-data``
275request, you may want to stream the request. By default, ``requests`` does not276support this, but there is a separate package which does -277``requests-toolbelt``. You should read `the toolbelt's documentation

Merge pull request #2440 from aquarion/patch-1Ian Cordascobefore adoption69d9594

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

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

line 279why, one step back
279

Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0

lines 280–282why, one step back
280For sending multiple files in one request refer to the :ref:`advanced <advanced>`
281section.282

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 283–298why, one step back
283
284Response Status Codes285---------------------286287We can check the response status code::288289 >>> r = requests.get('http://httpbin.org/get')290 >>> r.status_code291 200292293Requests also comes with a built-in status code lookup object for easy294reference::295296 >>> r.status_code == requests.codes.ok297 True298

Merge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515

lines 299–301why, one step back
299If we made a bad request (a 4XX client error or 5XX server error response), we
300can raise it with301:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 302–338why, one step back
302
303 >>> bad_r = requests.get('http://httpbin.org/status/404')304 >>> bad_r.status_code305 404306307 >>> bad_r.raise_for_status()308 Traceback (most recent call last):309 File "requests/models.py", line 832, in raise_for_status310 raise http_error311 requests.exceptions.HTTPError: 404 Client Error312313But, since our ``status_code`` for ``r`` was ``200``, when we call314``raise_for_status()`` we get::315316 >>> r.raise_for_status()317 None318319All is well.320321322Response Headers323----------------324325We can view the server's response headers using a Python dictionary::326327 >>> r.headers328 {329 'content-encoding': 'gzip',330 'transfer-encoding': 'chunked',331 'connection': 'close',332 'server': 'nginx/1.0.4',333 'x-runtime': '148ms',334 'etag': '"e1ca502697e5c9317743dc078f67693f"',335 'content-type': 'application/json'336 }337338The dictionary is special, though: it's made just for HTTP headers. According to

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 341–349why, one step back
341
342So, we can access the headers using any capitalization we want::343344 >>> r.headers['Content-Type']345 'application/json'346347 >>> r.headers.get('content-type')348 'application/json'349

Merge pull request #2453 from requiredfield/masterCory Benfieldbefore adoption6f3c91b

lines 350–358why, one step back
350It is also special in that the server could have sent the same header multiple
351times with different values, but requests combines them so they can be352represented in the dictionary within a single mapping, as per353`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:354355 > A recipient MAY combine multiple header fields with the same field name356 > into one "field-name: field-value" pair, without changing the semantics357 > of the message, by appending each subsequent field value to the combined358 > field value in order, separated by a comma.

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 359–362why, one step back
359
360Cookies361-------362

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 364–384why, one step back
364
365 >>> url = 'http://example.com/some/cookie/setting/url'366 >>> r = requests.get(url)367368 >>> r.cookies['example_cookie_name']369 'example_cookie_value'370371To send your own cookies to the server, you can use the ``cookies``372parameter::373374 >>> url = 'http://httpbin.org/cookies'375 >>> cookies = dict(cookies_are='working')376377 >>> r = requests.get(url, cookies=cookies)378 >>> r.text379 '{"cookies": {"cookies_are": "working"}}'380381382Redirection and History383-----------------------384

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 386–387why, one step back
386HEAD.
387

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

line 389why, one step back
389

Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8

line 390why, one step back
390The :meth:`Response.history <requests.Response.history>` list contains the

Merge pull request #2245 from sigmavirus24/doc-fixCory Benfieldbefore adoptione0d88c2

line 391why, one step back
391:class:`Response <requests.Response>` objects that were created in order to

Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8

line 392why, one step back
392complete the request. The list is sorted from the oldest to the most recent

Merge pull request #2245 from sigmavirus24/doc-fixCory Benfieldbefore adoptione0d88c2

line 393why, one step back
393response.

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

lines 394–396why, one step back
394
395For example, GitHub redirects all HTTP requests to HTTPS::396

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 397–416why, one step back
397 >>> r = requests.get('http://github.com')
398 >>> r.url399 'https://github.com/'400 >>> r.status_code401 200402 >>> r.history403 [<Response [301]>]404405406If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable407redirection handling with the ``allow_redirects`` parameter::408409 >>> r = requests.get('http://github.com', allow_redirects=False)410 >>> r.status_code411 301412 >>> r.history413 []414415If you're using HEAD, you can enable redirection as well::416

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 418–449why, one step back
418 >>> r.url
419 'https://github.com/'420 >>> r.history421 [<Response [301]>]422423424Timeouts425--------426427You can tell Requests to stop waiting for a response after a given number of428seconds with the ``timeout`` parameter::429430 >>> requests.get('http://github.com', timeout=0.001)431 Traceback (most recent call last):432 File "<stdin>", line 1, in <module>433 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)434435436.. admonition:: Note437438 ``timeout`` is not a time limit on the entire response download;439 rather, an exception is raised if the server has not issued a440 response for ``timeout`` seconds (more precisely, if no bytes have been441 received on the underlying socket for ``timeout`` seconds).442443444Errors and Exceptions445---------------------446447In the event of a network problem (e.g. DNS failure, refused connection, etc),448Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.449

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

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

Update changelog for 2.2.1.Cory Benfieldbefore adoption2a6b835

lines 451–464why, one step back
451:class:`~requests.exceptions.HTTPError` exception.
452453If a request times out, a :class:`~requests.exceptions.Timeout` exception is454raised.455456If a request exceeds the configured number of maximum redirections, a457:class:`~requests.exceptions.TooManyRedirects` exception is raised.458459All exceptions that Requests explicitly raises inherit from460:class:`requests.exceptions.RequestException`.461462-----------------------463464Ready for more? Check out the :ref:`advanced <advanced>` section.