Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

495 lines · 14.0 KiB

Last changed by

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

History of this file

Take it

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

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 1–26why, 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::

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

line 27why, one step back
27

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 28–39why, one step back
28 >>> import requests
2930Now, 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::

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

line 40why, one step back
40

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 41–44why, one step back
41 >>> 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::

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

line 45why, one step back
45

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 46–73why, one step back
46 >>> 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::7071 >>> print r.url72 u'http://httpbin.org/get?key2=value2&key1=value1'73

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

line 74why, one step back
74

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 75–88why, one step back
75Response Content
76----------------7778We can read the content of the server's response. Consider the GitHub timeline79again::8081 >>> import requests82 >>> r = requests.get('https://github.com/timeline.json')83 >>> r.text84 '[{"repository":{"open_issues":0,"url":"https://github.com/...8586Requests will automatically decode content from the server. Most unicode87charsets are seamlessly decoded.88

Merge pull request #772 from Lukasa/developKenneth Reitzbefore adoption6464618

lines 89–92why, one step back
89When you make a request, Requests makes educated guesses about the encoding of
90the response based on the HTTP headers. The text encoding guessed by Requests91is used when you access ``r.text``. You can find out what encoding Requests is92using, and change it, using the ``r.encoding`` property::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 93why, one step back
93

Merge pull request #772 from Lukasa/developKenneth Reitzbefore adoption6464618

lines 94–104why, one step back
94 >>> r.encoding
95 'utf-8'96 >>> r.encoding = 'ISO-8859-1'9798If you change the encoding, Requests will use the new value of ``r.encoding``99whenever you call ``r.text``.100101Requests will also use custom encodings in the event that you need them. If102you have created your own encoding and registered it with the ``codecs``103module, you can simply use the codec name as the value of ``r.encoding`` and104Requests will handle the decoding for you.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 105–139why, one step back
105
106Binary Response Content107-----------------------108109You can also access the response body as bytes, for non-text requests::110111 >>> r.content112 b'[{"repository":{"open_issues":0,"url":"https://github.com/...113114The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.115116For example, to create an image from binary data returned by a request, you can117use the following code:118119 >>> from PIL import Image120 >>> from StringIO import StringIO121 >>> i = Image.open(StringIO(r.content))122123124JSON Response Content125---------------------126127There's also a builtin JSON decoder, in case you're dealing with JSON data::128129 >>> import requests130 >>> r = requests.get('https://github.com/timeline.json')131 >>> r.json132 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...133134In case the JSON decoding fails, ``r.json`` simply returns ``None``.135136137Raw Response Content138--------------------139

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

lines 140–142why, one step back
140In the rare case that you'd like to get the raw socket response from the
141server, you can access ``r.raw``. If you want to do this, make sure you set142``prefetch=False`` in your initial request. Once you do, you can do this::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 143why, one step back
143

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

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

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 145–202why, one step back
145 >>> r.raw
146 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>147 >>> r.raw.read(10)148 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'149150151Custom Headers152--------------153154If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the155``headers`` parameter.156157For example, we didn't specify our content-type in the previous example::158159 >>> import json160 >>> url = 'https://api.github.com/some/endpoint'161 >>> payload = {'some': 'data'}162 >>> headers = {'content-type': 'application/json'}163164 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)165166167More complicated POST requests168------------------------------169170Typically, you want to send some form-encoded data — much like an HTML form.171To do this, simply pass a dictionary to the `data` argument. Your172dictionary of data will automatically be form-encoded when the request is made::173174 >>> payload = {'key1': 'value1', 'key2': 'value2'}175 >>> r = requests.post("http://httpbin.org/post", data=payload)176 >>> print r.text177 {178 // ...snip... //179 "form": {180 "key2": "value2",181 "key1": "value1"182 },183 // ...snip... //184 }185186There 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.187188For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::189190 >>> import json191 >>> url = 'https://api.github.com/some/endpoint'192 >>> payload = {'some': 'data'}193194 >>> r = requests.post(url, data=json.dumps(payload))195196197POST a Multipart-Encoded File198-----------------------------199200Requests makes it simple to upload Multipart-encoded files::201202 >>> url = 'http://httpbin.org/post'

Merge pull request #752 from anentropic/patch-1Kenneth Reitzbefore adoption54842cd

line 203why, one step back
203 >>> files = {'file': open('report.xls', 'rb')}

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 204–209why, one step back
204
205 >>> r = requests.post(url, files=files)206 >>> r.text207 {208 // ...snip... //209 "files": {

Merge pull request #752 from anentropic/patch-1Kenneth Reitzbefore adoption54842cd

line 210why, one step back
210 "file": "<censored...binary...data>"

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 211–232why, one step back
211 },
212 // ...snip... //213 }214215You can set the filename explicitly::216217 >>> url = 'http://httpbin.org/post'218 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}219220 >>> r = requests.post(url, files=files)221 >>> r.text222 {223 // ...snip... //224 "files": {225 "file": "<censored...binary...data>"226 },227 // ...snip... //228 }229230If you want, you can send strings to be received as files::231232 >>> url = 'http://httpbin.org/post'

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

line 233why, one step back
233 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 234–250why, one step back
234
235 >>> r = requests.post(url, files=files)236 >>> r.text237 {238 // ...snip... //239 "files": {240 "file": "some,data,to,send\\nanother,row,to,send\\n"241 },242 // ...snip... //243 }244245246Response Status Codes247---------------------248249We can check the response status code::250

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption6541ceb

line 251why, one step back
251 >>> r = requests.get('http://httpbin.org/get')

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 252–263why, one step back
252 >>> r.status_code
253 200254255Requests also comes with a built-in status code lookup object for easy256reference::257258 >>> r.status_code == requests.codes.ok259 True260261If we made a bad request (non-200 response), we can raise it with262:class:`Response.raise_for_status()`::263

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

lines 264–265why, one step back
264 >>> bad_r = requests.get('http://httpbin.org/status/404')
265 >>> bad_r.status_code

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 266–267why, one step back
266 404
267

Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8

line 268why, one step back
268 >>> bad_r.raise_for_status()

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 269why, one step back
269 Traceback (most recent call last):

Merge pull request #683 from jkleint/patch-1Kenneth Reitzbefore adoption38db8c2

lines 270–272why, one step back
270 File "requests/models.py", line 832, in raise_for_status
271 raise http_error272 requests.exceptions.HTTPError: 404 Client Error

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 273–342why, one step back
273
274But, since our ``status_code`` for ``r`` was ``200``, when we call275``raise_for_status()`` we get::276277 >>> r.raise_for_status()278 None279280All is well.281282283Response Headers284----------------285286We can view the server's response headers using a Python dictionary::287288 >>> r.headers289 {290 'status': '200 OK',291 'content-encoding': 'gzip',292 'transfer-encoding': 'chunked',293 'connection': 'close',294 'server': 'nginx/1.0.4',295 'x-runtime': '148ms',296 'etag': '"e1ca502697e5c9317743dc078f67693f"',297 'content-type': 'application/json; charset=utf-8'298 }299300The dictionary is special, though: it's made just for HTTP headers. According to301`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP302Headers are case-insensitive.303304So, we can access the headers using any capitalization we want::305306 >>> r.headers['Content-Type']307 'application/json; charset=utf-8'308309 >>> r.headers.get('content-type')310 'application/json; charset=utf-8'311312If a header doesn't exist in the Response, its value defaults to ``None``::313314 >>> r.headers['X-Random']315 None316317318Cookies319-------320321If a response contains some Cookies, you can get quick access to them::322323 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'324 >>> r = requests.get(url)325326 >>> r.cookies['requests-is']327 'awesome'328329To send your own cookies to the server, you can use the ``cookies``330parameter::331332 >>> url = 'http://httpbin.org/cookies'333 >>> cookies = dict(cookies_are='working')334335 >>> r = requests.get(url, cookies=cookies)336 >>> r.text337 '{"cookies": {"cookies_are": "working"}}'338339340Basic Authentication341--------------------342

Merge pull request #787 from kayzh/developKenneth Reitzbefore adoptionbbf1946

line 343why, one step back
343Many web services require authentication. There are many different types of

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 344–375why, one step back
344authentication, but the most common is HTTP Basic Auth.
345346Making requests with Basic Auth is extremely simple::347348 >>> from requests.auth import HTTPBasicAuth349 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))350 <Response [200]>351352Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for353this authentication method::354355 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))356 <Response [200]>357358Providing the credentials as a tuple in this fashion is functionally equivalent359to the ``HTTPBasicAuth`` example above.360361362Digest Authentication363---------------------364365Another popular form of web service protection is Digest Authentication::366367 >>> from requests.auth import HTTPDigestAuth368 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'369 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))370 <Response [200]>371372373OAuth Authentication374--------------------375

oauth awesomenessKenneth Reitzbefore adoptionf33a0aa

lines 376–377why, one step back
376Requests features robust, built-in OAuth support!
377

typo all the thingsKenneth Reitzbefore adoption9840966

line 378why, one step back
378OAuth takes many forms, so let's take a look at a few different forms::

oauth awesomenessKenneth Reitzbefore adoptionf33a0aa

lines 379–411why, one step back
379
380 import requests381 from requests.auth import OAuth1382383 url = u'https://api.twitter.com/1/account/settings.json'384385 client_key = u'...'386 client_secret = u'...'387 resource_owner_key = u'...'388 resource_owner_secret = u'...'389390391Query signing::392393 queryoauth = OAuth1(client_key, client_secret,394 resource_owner_key, resource_owner_secret,395 signature_type='query')396 r = requests.get(url, auth=queryoauth)397398Header signing::399400 headeroauth = OAuth1(client_key, client_secret,401 resource_owner_key, resource_owner_secret,402 signature_type='auth_header')403 r = requests.get(url, auth=headeroauth)404405Body signing::406407 bodyoauth = OAuth1(client_key, client_secret,408 resource_owner_key, resource_owner_secret,409 signature_type='body')410411 r = requests.post(url, auth=bodyoauth)

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 412–431why, one step back
412
413414Redirection and History415-----------------------416417Requests will automatically perform location redirection while using the GET418and OPTIONS verbs.419420GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method421of the Response object to track redirection. Let's see what Github does::422423 >>> r = requests.get('http://github.com')424 >>> r.url425 'https://github.com/'426 >>> r.status_code427 200428 >>> r.history429 [<Response [301]>]430431The :class:`Response.history` list contains a list of the

Merge pull request #721 from karlcow/developKenneth Reitzbefore adoptionc3ab38e

line 432why, one step back
432:class:`Request` objects that were created in order to complete the request. The list is sorted from the oldest to the most recent request.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 433–495why, one step back
433
434If you're using GET or OPTIONS, you can disable redirection handling with the435``allow_redirects`` parameter::436437 >>> r = requests.get('http://github.com', allow_redirects=False)438 >>> r.status_code439 301440 >>> r.history441 []442443If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable444redirection as well::445446 >>> r = requests.post('http://github.com', allow_redirects=True)447 >>> r.url448 'https://github.com/'449 >>> r.history450 [<Response [301]>]451452453Timeouts454--------455456You can tell requests to stop waiting for a response after a given number of457seconds with the ``timeout`` parameter::458459 >>> requests.get('http://github.com', timeout=0.001)460 Traceback (most recent call last):461 File "<stdin>", line 1, in <module>462 requests.exceptions.Timeout: Request timed out.463464.. admonition:: Note:465466 ``timeout`` only effects the connection process itself, not the467 downloading of the response body.468469470Errors and Exceptions471---------------------472473In the event of a network problem (e.g. DNS failure, refused connection, etc),474Requests will raise a :class:`ConnectionError` exception.475476In the event of the rare invalid HTTP response, Requests will raise477an :class:`HTTPError` exception.478479If a request times out, a :class:`Timeout` exception is raised.480481If a request exceeds the configured number of maximum redirections, a482:class:`TooManyRedirects` exception is raised.483484All exceptions that Requests explicitly raises inherit from485:class:`requests.exceptions.RequestException`.486487You can refer to :ref:`Configuration API Docs <configurations>` for immediate488raising of :class:`HTTPError` exceptions via the ``danger_mode`` option or489have Requests catch the majority of490:class:`requests.exceptions.RequestException` exceptions with the ``safe_mode``491option.492493-----------------------494495Ready for more? Check out the :ref:`advanced <advanced>` section.