Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

373 lines · 10.5 KiB

Last changed by

Merge pull request #333 from bryanhelmig/developKenneth Reitzbefore adoption281e059

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

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 39–40why, one step back
39 >>> r.content
40 '[{"repository":{"open_issues":0,"url":"https://github.com/...

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 41why, one step back
41

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

lines 42–43why, one step back
42Requests does its best to decode content from the server. Most unicode
43charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 44why, one step back
44

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

lines 45–48why, one step back
45When you make a request, ``r.encoding`` is set, based on the HTTP headers.
46Requests will attempt to use that encoding when you access ``r.content``. You47can manually set ``r.encoding`` to any encoding you'd like (including ``None``),48and that charset will be used.

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 49why, one step back
49

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

line 50why, one step back
50

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 51–59why, one step back
51Make a POST Request
52-------------------5354POST requests are equally simple::5556 r = requests.post("http://httpbin.org/post")575859Typically, you want to send some form-encoded data — much like an HTML form.

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 62–123why, one step back
62
63 >>> payload = {'key1': 'value1', 'key2': 'value2'}64 >>> r = requests.post("http://httpbin.org/post", data=payload)65 >>> print r.content66 {67 "origin": "179.13.100.4",68 "files": {},69 "form": {70 "key2": "value2",71 "key1": "value1"72 },73 "url": "http://httpbin.org/post",74 "args": {},75 "headers": {76 "Content-Length": "23",77 "Accept-Encoding": "identity, deflate, compress, gzip",78 "Accept": "*/*",79 "User-Agent": "python-requests/0.8.0",80 "Host": "127.0.0.1:7077",81 "Content-Type": "application/x-www-form-urlencoded"82 },83 "data": ""84 }8586There 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.8788For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8990 url = 'https://api.github.com/some/endpoint'91 payload = {'some': 'data'}9293 r = requests.post(url, data=json.dumps(payload))949596Custom Headers97--------------9899If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the100``headers`` parameter.101102For example, we didn't specify our content-type in the previous example::103104 url = 'https://api.github.com/some/endpoint'105 payload = {'some': 'data'}106 headers = {'content-type': 'application/json'}107108 r = requests.post(url, data=json.dumps(payload), headers=headers)109110111POST a Multipart-Encoded File112-----------------------------113114Requests makes it simple to upload Multipart-encoded files::115116 >>> url = 'http://httpbin.org/post'117 >>> files = {'report.xls': open('report.xls', 'rb')}118119 >>> r = requests.post(url, files=files)120 >>> r.content121 {122 "origin": "179.13.100.4",123 "files": {

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 125–139why, one step back
125 },
126 "form": {},127 "url": "http://httpbin.org/post",128 "args": {},129 "headers": {130 "Content-Length": "3196",131 "Accept-Encoding": "identity, deflate, compress, gzip",132 "Accept": "*/*",133 "User-Agent": "python-requests/0.8.0",134 "Host": "httpbin.org:80",135 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"136 },137 "data": ""138 }139

Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae

lines 140–164why, one step back
140Setting filename explicitly::
141142 >>> url = 'http://httpbin.org/post'143 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}144145 >>> r = requests.post(url, files=files)146 >>> r.content147 {148 "origin": "179.13.100.4",149 "files": {150 "file": "<censored...binary...data>"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 }

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 165–166why, one step back
165
166

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 167–168why, one step back
167Response Status Codes
168---------------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 169why, one step back
169

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 171why, one step back
171

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 172–173why, one step back
172 >>> r.status_code
173 200

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 174why, one step back
174

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 177why, one step back
177

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 180why, one step back
180

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

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

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 183why, one step back
183

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 184–186why, one step back
184 >>> _r = requests.get('http://httpbin.org/status/404')
185 >>> _r.status_code186 404

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 187why, one step back
187

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 188–192why, one step back
188 >>> _r.raise_for_status()
189 Traceback (most recent call last):190 File "requests/models.py", line 394, in raise_for_status191 raise self.error192 urllib2.HTTPError: HTTP Error 404: NOT FOUND

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 193why, one step back
193

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 195why, one step back
195

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 196–197why, one step back
196 >>> r.raise_for_status()
197 None

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 198why, one step back
198

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 200–201why, one step back
200
201

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 202–203why, one step back
202Response Headers
203----------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 204why, one step back
204

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 207why, one step back
207

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 208–218why, one step back
208 >>> r.headers
209 {210 'status': '200 OK',211 'content-encoding': 'gzip',212 'transfer-encoding': 'chunked',213 'connection': 'close',214 'server': 'nginx/1.0.4',215 'x-runtime': '148ms',216 'etag': '"e1ca502697e5c9317743dc078f67693f"',217 'content-type': 'application/json; charset=utf-8'218 }

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 219why, one step back
219

Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158

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

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 223why, one step back
223

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

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

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 225why, one step back
225

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 226–257why, one step back
226 >>> r.headers['Content-Type']
227 'application/json; charset=utf-8'228229 >>> r.headers.get('content-type')230 'application/json; charset=utf-8'231232If a header doesn't exist in the Response, its value defaults to ``None``::233234 >>> r.headers['X-Random']235 None236237238Cookies239-------240241If a response contains some Cookies, you can get quick access to them::242243 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'244 >>> r = requests.get(url)245246 >>> print r.cookies247 {'requests-is': 'awesome'}248249To send your own cookies to the server, you can use the ``cookies``250parameter::251252 >>> url = 'http://httpbin.org/cookies'253 >>> cookies = dict(cookies_are='working')254255 >>> r = requests.get(url, cookies=cookies)256 >>> r.content257 '{"cookies": {"cookies_are": "working"}}'

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 258–263why, one step back
258
259260Basic Authentication261--------------------262263Most web services require authentication. There many different types of

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 265why, one step back
265

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 267why, one step back
267

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

lines 268–274why, one step back
268 >>> from requests.auth import HTTPBasicAuth
269 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))270 <Response [200]>271272Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for273this authentication method::274

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

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

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 280why, one step back
280

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

line 281why, one step back
281

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 282–284why, one step back
282Digest Authentication
283---------------------284

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 286why, one step back
286

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

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

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

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

Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02

lines 291–297why, one step back
291
292293OAuth Authentication294--------------------295296Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for297establishing 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 298why, one step back
298

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 299–302why, one step back
299
300Redirection and History301-----------------------302

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 304–306why, one step back
304
305GitHub redirects all HTTP requests to HTTPS. Let's see what happens::306

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 308–318why, one step back
308 >>> r.url
309 'https://github.com/'310 >>> r.status_code311 200312 >>> r.history313 [<Response [301]>]314315The :class:`Response.history` list contains a list of the316:class:`Request` objects that were created in order to complete the request.317318If you're using GET, HEAD, or OPTIONS, you can disable redirection

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

line 320why, one step back
320

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 322–328why, one step back
322 >>> r.status_code
323 301324 >>> r.history325 []326327If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::328

Merge branch 'develop'Kenneth Reitzbefore adoption1165bec

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 330–347why, one step back
330 >>> r.url
331 'https://github.com/'332 >>> r.history333 [<Response [301]>]334335336Timeouts337--------338339You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::340341 >>> requests.get('http://github.com', timeout=0.001)342 Traceback (most recent call last):343 File "<stdin>", line 1, in <module>344 requests.exceptions.Timeout: Request timed out.345346.. admonition:: Note347

Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d

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

Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09

lines 349–365why, one step back
349
350351Errors and Exceptions352---------------------353354In the event of a network problem (e.g. DNS failure, refused connection, etc),355Requests will raise a :class:`ConnectionError` exception.356357In the event of the rare invalid HTTP response, Requests will raise358an :class:`HTTPError` exception.359360If a request times out, a :class:`Timeout` exception is raised.361362If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.363364All exceptions that Requests explicitly raises inherit from365:class:`requests.exceptions.RequestException`.

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

line 366why, one step back
366

Merge pull request #333 from bryanhelmig/developKenneth Reitzbefore adoption281e059

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

Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05

lines 371–372why, one step back
371-----------------------
372

Merge branch 'develop'Kenneth Reitzbefore adoptiond0b96f8

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