Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

399 lines · 11.1 KiB

Last changed by

r.textKenneth Reitzbefore adoption1bc377b

History of this file

Take it

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 1why, one step back
1.. _quickstart:

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 2why, one step back
2

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 3–4why, one step back
3Quickstart
4==========

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 5why, one step back
5

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 6why, one step back
6.. module:: requests.models

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 7why, one step back
7

Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158

lines 8–10why, one step back
8Eager to get started? This page gives a good introduction in how to get started
9with Requests. This assumes you already have Requests installed. If you do not,10head over to the :ref:`Installation <install>` section.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 11why, one step back
11

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 12why, one step back
12First, make sure that:

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 13why, one step back
13

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 14–15why, one step back
14* Requests is :ref:`installed <install>`
15* Requests is :ref:`up-to-date <updates>`

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 16–17why, one step back
16
17

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 18why, one step back
18Lets gets started with some simple use cases and examples.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 19–20why, one step back
19
20

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 21–22why, one step back
21Make a GET Request
22------------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 23why, one step back
23

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 24why, one step back
24Making a standard request with Requests is very simple.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 25why, one step back
25

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 26why, one step back
26Let's get GitHub's public timeline ::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 27why, one step back
27

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 29why, one step back
29

Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158

lines 30–31why, one step back
30Now, we have a :class:`Response` object called ``r``. We can get all the
31information we need from this.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 32–33why, one step back
32
33

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 34–35why, one step back
34Response Content
35----------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 36why, one step back
36

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 37why, one step back
37We can read the content of the server's response::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 38why, one step back
38

explain binary response dataKenneth Reitzbefore adoptiona89530a

line 39why, one step back
39 >>> r.text

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 41why, one step back
41

explain binary response dataKenneth Reitzbefore adoptiona89530a

lines 42–43why, one step back
42Requests will automatically decode content from the server. Most unicode
43charsets are seamlessly decoded.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 44why, one step back
44

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

line 45why, one step back
45When you make a request, ``r.encoding`` is set, based on the HTTP headers.

explain binary response dataKenneth Reitzbefore adoptiona89530a

lines 46–74why, one step back
46Requests will use that encoding when you access ``r.text``. If ``r.encoding``
47is ``None``, Requests will make an extremely educated guess of the encoding48of the response body. You can manually set ``r.encoding`` to any encoding49you'd like, and that charset will be used.505152Binary Response Content53-----------------------5455You can also access the response body as bytes, for non-text requests::5657 >>> r.content58 b'[{"repository":{"open_issues":0,"url":"https://github.com/...5960The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.616263Raw Response Content64--------------------6566In the rare case that you'd like to get the absolute raw socket response from the server,67you can access ``r.raw``::6869 >>> r.raw70 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>7172 >>> r.raw.read(10)73 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'74

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 75why, one step back
75

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

line 76why, one step back
76

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 77–85why, one step back
77Make a POST Request
78-------------------7980POST requests are equally simple::8182 r = requests.post("http://httpbin.org/post")838485Typically, you want to send some form-encoded data — much like an HTML form.

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

lines 86–87why, one step back
86To do this, simply pass a dictionary to the `data` argument. Your
87dictionary of data will automatically be form-encoded when the request is made::

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 88–90why, one step back
88
89 >>> payload = {'key1': 'value1', 'key2': 'value2'}90 >>> r = requests.post("http://httpbin.org/post", data=payload)

r.textKenneth Reitzbefore adoption1bc377b

line 91why, one step back
91 >>> print r.text

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 92–145why, one step back
92 {
93 "origin": "179.13.100.4",94 "files": {},95 "form": {96 "key2": "value2",97 "key1": "value1"98 },99 "url": "http://httpbin.org/post",100 "args": {},101 "headers": {102 "Content-Length": "23",103 "Accept-Encoding": "identity, deflate, compress, gzip",104 "Accept": "*/*",105 "User-Agent": "python-requests/0.8.0",106 "Host": "127.0.0.1:7077",107 "Content-Type": "application/x-www-form-urlencoded"108 },109 "data": ""110 }111112There 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.113114For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::115116 url = 'https://api.github.com/some/endpoint'117 payload = {'some': 'data'}118119 r = requests.post(url, data=json.dumps(payload))120121122Custom Headers123--------------124125If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the126``headers`` parameter.127128For example, we didn't specify our content-type in the previous example::129130 url = 'https://api.github.com/some/endpoint'131 payload = {'some': 'data'}132 headers = {'content-type': 'application/json'}133134 r = requests.post(url, data=json.dumps(payload), headers=headers)135136137POST a Multipart-Encoded File138-----------------------------139140Requests makes it simple to upload Multipart-encoded files::141142 >>> url = 'http://httpbin.org/post'143 >>> files = {'report.xls': open('report.xls', 'rb')}144145 >>> r = requests.post(url, files=files)

r.textKenneth Reitzbefore adoption1bc377b

line 146why, one step back
146 >>> r.text

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 147–149why, one step back
147 {
148 "origin": "179.13.100.4",149 "files": {

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

line 150why, one step back
150 "report.xls": "<censored...binary...data>"

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 151–165why, one step back
151 },
152 "form": {},153 "url": "http://httpbin.org/post",154 "args": {},155 "headers": {156 "Content-Length": "3196",157 "Accept-Encoding": "identity, deflate, compress, gzip",158 "Accept": "*/*",159 "User-Agent": "python-requests/0.8.0",160 "Host": "httpbin.org:80",161 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"162 },163 "data": ""164 }165

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

lines 166–171why, one step back
166Setting filename explicitly::
167168 >>> url = 'http://httpbin.org/post'169 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}170171 >>> r = requests.post(url, files=files)

r.textKenneth Reitzbefore adoption1bc377b

line 172why, one step back
172 >>> r.text

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

lines 173–190why, one step back
173 {
174 "origin": "179.13.100.4",175 "files": {176 "file": "<censored...binary...data>"177 },178 "form": {},179 "url": "http://httpbin.org/post",180 "args": {},181 "headers": {182 "Content-Length": "3196",183 "Accept-Encoding": "identity, deflate, compress, gzip",184 "Accept": "*/*",185 "User-Agent": "python-requests/0.8.0",186 "Host": "httpbin.org:80",187 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"188 },189 "data": ""190 }

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 191–192why, one step back
191
192

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 193–194why, one step back
193Response Status Codes
194---------------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 195why, one step back
195

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 196why, one step back
196We can check the response status code::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 197why, one step back
197

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 198–199why, one step back
198 >>> r.status_code
199 200

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 200why, one step back
200

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 201–202why, one step back
201Requests also comes with a built-in status code lookup object for easy
202reference::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 203why, one step back
203

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 204–205why, one step back
204 >>> r.status_code == requests.codes.ok
205 True

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 206why, one step back
206

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 207why, one step back
207If we made a bad request (non-200 response), we can raise it with

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 208why, one step back
208:class:`Response.raise_for_status()`::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 209why, one step back
209

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 210–212why, one step back
210 >>> _r = requests.get('http://httpbin.org/status/404')
211 >>> _r.status_code212 404

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 213why, one step back
213

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 214–218why, one step back
214 >>> _r.raise_for_status()
215 Traceback (most recent call last):216 File "requests/models.py", line 394, in raise_for_status217 raise self.error218 urllib2.HTTPError: HTTP Error 404: NOT FOUND

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 219why, one step back
219

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 220why, one step back
220But, since our ``status_code`` was ``200``, when we call it::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 221why, one step back
221

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 222–223why, one step back
222 >>> r.raise_for_status()
223 None

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 224why, one step back
224

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 225why, one step back
225All is well.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 226–227why, one step back
226
227

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 228–229why, one step back
228Response Headers
229----------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 230why, one step back
230

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 231–232why, one step back
231We can view the server's response headers with a simple Python dictionary
232interface::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 233why, one step back
233

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 234–244why, one step back
234 >>> r.headers
235 {236 'status': '200 OK',237 'content-encoding': 'gzip',238 'transfer-encoding': 'chunked',239 'connection': 'close',240 'server': 'nginx/1.0.4',241 'x-runtime': '148ms',242 'etag': '"e1ca502697e5c9317743dc078f67693f"',243 'content-type': 'application/json; charset=utf-8'244 }

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 245why, one step back
245

Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158

lines 246–247why, one step back
246The dictionary is special, though: it's made just for HTTP headers. According to
247`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 248why, one step back
248Headers are case-insensitive.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 249why, one step back
249

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 250why, one step back
250So, we can access the headers using any capitalization we want::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 251why, one step back
251

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 252–281why, one step back
252 >>> r.headers['Content-Type']
253 'application/json; charset=utf-8'254255 >>> r.headers.get('content-type')256 'application/json; charset=utf-8'257258If a header doesn't exist in the Response, its value defaults to ``None``::259260 >>> r.headers['X-Random']261 None262263264Cookies265-------266267If a response contains some Cookies, you can get quick access to them::268269 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'270 >>> r = requests.get(url)271272 >>> print r.cookies273 {'requests-is': 'awesome'}274275To send your own cookies to the server, you can use the ``cookies``276parameter::277278 >>> url = 'http://httpbin.org/cookies'279 >>> cookies = dict(cookies_are='working')280281 >>> r = requests.get(url, cookies=cookies)

r.textKenneth Reitzbefore adoption1bc377b

line 282why, one step back
282 >>> r.text

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 283why, one step back
283 '{"cookies": {"cookies_are": "working"}}'

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 284–289why, one step back
284
285286Basic Authentication287--------------------288289Most web services require authentication. There many different types of

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 290why, one step back
290authentication, but the most common is HTTP Basic Auth.

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 291why, one step back
291

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 292why, one step back
292Making requests with Basic Auth is extremely simple::

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 293why, one step back
293

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

lines 294–300why, one step back
294 >>> from requests.auth import HTTPBasicAuth
295 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))296 <Response [200]>297298Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for299this authentication method::300

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 301–303why, one step back
301 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
302 <Response [200]>303

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

lines 304–305why, one step back
304Providing the credentials as a tuple in this fashion is functionally equivalent
305to the ``HTTPBasicAuth`` example above.

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 306why, one step back
306

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

line 307why, one step back
307

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 308–310why, one step back
308Digest Authentication
309---------------------310

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 311why, one step back
311Another popular form of web service protection is Digest Authentication::

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 312why, one step back
312

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

line 313why, one step back
313 >>> from requests.auth import HTTPDigestAuth

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 314why, one step back
314 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

line 315why, one step back
315 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 316why, one step back
316 <Response [200]>

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

lines 317–323why, one step back
317
318319OAuth Authentication320--------------------321322Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for323establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 324why, one step back
324

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 325–328why, one step back
325
326Redirection and History327-----------------------328

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

line 329why, one step back
329Requests will automatically perform location redirection while using idempotent methods.

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 330–332why, one step back
330
331GitHub redirects all HTTP requests to HTTPS. Let's see what happens::332

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

line 333why, one step back
333 >>> r = requests.get('http://github.com')

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 334–344why, one step back
334 >>> r.url
335 'https://github.com/'336 >>> r.status_code337 200338 >>> r.history339 [<Response [301]>]340341The :class:`Response.history` list contains a list of the342:class:`Request` objects that were created in order to complete the request.343344If you're using GET, HEAD, or OPTIONS, you can disable redirection

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

line 345why, one step back
345handling with the ``allow_redirects`` parameter::

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 346why, one step back
346

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

line 347why, one step back
347 >>> r = requests.get('http://github.com', allow_redirects=False)

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 348–354why, one step back
348 >>> r.status_code
349 301350 >>> r.history351 []352353If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::354

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 356–373why, one step back
356 >>> r.url
357 'https://github.com/'358 >>> r.history359 [<Response [301]>]360361362Timeouts363--------364365You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::366367 >>> requests.get('http://github.com', timeout=0.001)368 Traceback (most recent call last):369 File "<stdin>", line 1, in <module>370 requests.exceptions.Timeout: Request timed out.371372.. admonition:: Note373

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

line 374why, one step back
374 ``timeout`` only effects the connection process itself, not the downloading of the response body.

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 375–391why, one step back
375
376377Errors and Exceptions378---------------------379380In the event of a network problem (e.g. DNS failure, refused connection, etc),381Requests will raise a :class:`ConnectionError` exception.382383In the event of the rare invalid HTTP response, Requests will raise384an :class:`HTTPError` exception.385386If a request times out, a :class:`Timeout` exception is raised.387388If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.389390All exceptions that Requests explicitly raises inherit from391:class:`requests.exceptions.RequestException`.

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 392why, one step back
392

Merge pull request #333 from bryanhelmig/developKenneth Reitzbefore adoption281e059

lines 393–396why, one step back
393You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions
394via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions395with the ``safe_mode`` option.396

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 397–398why, one step back
397-----------------------
398

Merge branch 'develop'Kenneth Reitzbefore adoptiond0b96f8

line 399why, one step back
399Ready for more? Check out the :ref:`advanced <advanced>` section.