Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

448 lines · 13.2 KiB

Last changed by

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

History of this file

Take it

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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.

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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')

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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.

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 36–83why, 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.757677Response Content78----------------7980We can read the content of the server's response. Consider the GitHub timeline81again::8283 >>> import requests

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 85–100why, one step back
85 >>> r.text
86 u'[{"repository":{"open_issues":0,"url":"https://github.com/...8788Requests will automatically decode content from the server. Most unicode89charsets are seamlessly decoded.9091When you make a request, Requests makes educated guesses about the encoding of92the response based on the HTTP headers. The text encoding guessed by Requests93is used when you access ``r.text``. You can find out what encoding Requests is94using, and change it, using the ``r.encoding`` property::9596 >>> r.encoding97 'utf-8'98 >>> r.encoding = 'ISO-8859-1'99100If you change the encoding, Requests will use the new value of ``r.encoding``

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 107–136why, one step back
107
108Requests will also use custom encodings in the event that you need them. If109you have created your own encoding and registered it with the ``codecs``110module, you can simply use the codec name as the value of ``r.encoding`` and111Requests will handle the decoding for you.112113Binary Response Content114-----------------------115116You can also access the response body as bytes, for non-text requests::117118 >>> r.content119 b'[{"repository":{"open_issues":0,"url":"https://github.com/...120121The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.122123For example, to create an image from binary data returned by a request, you can124use the following code::125126 >>> from PIL import Image127 >>> from StringIO import StringIO128 >>> i = Image.open(StringIO(r.content))129130131JSON Response Content132---------------------133134There's also a builtin JSON decoder, in case you're dealing with JSON data::135136 >>> import requests

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 138–152why, one step back
138 >>> r.json()
139 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...140141In case the JSON decoding fails, ``r.json`` raises an exception. For example, if142the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:143No JSON object could be decoded``144145146Raw Response Content147--------------------148149In the rare case that you'd like to get the raw socket response from the150server, you can access ``r.raw``. If you want to do this, make sure you set151``stream=True`` in your initial request. Once you do, you can do this::152

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 169–196why, one step back
169content.
170171172Custom Headers173--------------174175If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the176``headers`` parameter.177178For example, we didn't specify our content-type in the previous example::179180 >>> import json181 >>> url = 'https://api.github.com/some/endpoint'182 >>> payload = {'some': 'data'}183 >>> headers = {'content-type': 'application/json'}184185 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)186187188More complicated POST requests189------------------------------190191Typically, you want to send some form-encoded data — much like an HTML form.192To do this, simply pass a dictionary to the ``data`` argument. Your193dictionary of data will automatically be form-encoded when the request is made::194195 >>> payload = {'key1': 'value1', 'key2': 'value2'}196 >>> r = requests.post("http://httpbin.org/post", data=payload)

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 198–206why, one step back
198 {
199 ...200 "form": {201 "key2": "value2",202 "key1": "value1"203 },204 ...205 }206

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 209–236why, one step back
209
210For 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:

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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'})}

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

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 #2141 from esparta/masterCory Benfieldbefore adoptione66466a

lines 267–270why, 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 not269support this, but there is a separate package which does -270``requests-toolbelt``. You should read `the toolbelt's documentation

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

lines 271–272why, one step back
271<https://toolbelt.rtfd.org>`_ for more details about how to use it.
272

Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 276–291why, one step back
276
277Response Status Codes278---------------------279280We can check the response status code::281282 >>> r = requests.get('http://httpbin.org/get')283 >>> r.status_code284 200285286Requests also comes with a built-in status code lookup object for easy287reference::288289 >>> r.status_code == requests.codes.ok290 True291

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 295–331why, one step back
295
296 >>> bad_r = requests.get('http://httpbin.org/status/404')297 >>> bad_r.status_code298 404299300 >>> bad_r.raise_for_status()301 Traceback (most recent call last):302 File "requests/models.py", line 832, in raise_for_status303 raise http_error304 requests.exceptions.HTTPError: 404 Client Error305306But, since our ``status_code`` for ``r`` was ``200``, when we call307``raise_for_status()`` we get::308309 >>> r.raise_for_status()310 None311312All is well.313314315Response Headers316----------------317318We can view the server's response headers using a Python dictionary::319320 >>> r.headers321 {322 'content-encoding': 'gzip',323 'transfer-encoding': 'chunked',324 'connection': 'close',325 'server': 'nginx/1.0.4',326 'x-runtime': '148ms',327 'etag': '"e1ca502697e5c9317743dc078f67693f"',328 'content-type': 'application/json'329 }330331The dictionary is special, though: it's made just for HTTP headers. According to

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 334–346why, one step back
334
335So, we can access the headers using any capitalization we want::336337 >>> r.headers['Content-Type']338 'application/json'339340 >>> r.headers.get('content-type')341 'application/json'342343344Cookies345-------346

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 348–368why, one step back
348
349 >>> url = 'http://example.com/some/cookie/setting/url'350 >>> r = requests.get(url)351352 >>> r.cookies['example_cookie_name']353 'example_cookie_value'354355To send your own cookies to the server, you can use the ``cookies``356parameter::357358 >>> url = 'http://httpbin.org/cookies'359 >>> cookies = dict(cookies_are='working')360361 >>> r = requests.get(url, cookies=cookies)362 >>> r.text363 '{"cookies": {"cookies_are": "working"}}'364365366Redirection and History367-----------------------368

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 370–371why, one step back
370HEAD.
371

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

line 373why, one step back
373

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

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

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

line 375why, one step back
375: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 376why, one step back
376complete the request. The list is sorted from the oldest to the most recent

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

line 377why, one step back
377response.

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

lines 378–380why, one step back
378
379For example, GitHub redirects all HTTP requests to HTTPS::380

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 381–400why, one step back
381 >>> r = requests.get('http://github.com')
382 >>> r.url383 'https://github.com/'384 >>> r.status_code385 200386 >>> r.history387 [<Response [301]>]388389390If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable391redirection handling with the ``allow_redirects`` parameter::392393 >>> r = requests.get('http://github.com', allow_redirects=False)394 >>> r.status_code395 301396 >>> r.history397 []398399If you're using HEAD, you can enable redirection as well::400

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 402–433why, one step back
402 >>> r.url
403 'https://github.com/'404 >>> r.history405 [<Response [301]>]406407408Timeouts409--------410411You can tell Requests to stop waiting for a response after a given number of412seconds with the ``timeout`` parameter::413414 >>> requests.get('http://github.com', timeout=0.001)415 Traceback (most recent call last):416 File "<stdin>", line 1, in <module>417 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)418419420.. admonition:: Note421422 ``timeout`` is not a time limit on the entire response download;423 rather, an exception is raised if the server has not issued a424 response for ``timeout`` seconds (more precisely, if no bytes have been425 received on the underlying socket for ``timeout`` seconds).426427428Errors and Exceptions429---------------------430431In the event of a network problem (e.g. DNS failure, refused connection, etc),432Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.433

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

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

Revert "Merge pull request #1710 from jvantuyl/master"Kenneth Reitzbefore adoption0228851

lines 435–448why, one step back
435:class:`~requests.exceptions.HTTPError` exception.
436437If a request times out, a :class:`~requests.exceptions.Timeout` exception is438raised.439440If a request exceeds the configured number of maximum redirections, a441:class:`~requests.exceptions.TooManyRedirects` exception is raised.442443All exceptions that Requests explicitly raises inherit from444:class:`requests.exceptions.RequestException`.445446-----------------------447448Ready for more? Check out the :ref:`advanced <advanced>` section.