Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

415 lines · 11.6 KiB

Last changed by

Merge pull request #1234 from Vassius/issue-1225Kenneth Reitzbefore adoption13de692

History of this file

Take it

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

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

lines 1–21why, 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 Request

update docsKenneth Reitzbefore adoption5b5ff69

line 22why, one step back
22--------------

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

lines 23–130why, one step back
23
24Making a request with Requests is very simple.2526Begin by importing the Requests module::2728 >>> import requests2930Now, 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::4041 >>> 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::4546 >>> 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'737475Response Content76----------------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.8889When you make a request, Requests makes educated guesses about the encoding of90the 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::9394 >>> r.encoding95 '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.105106Binary 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')

Merge pull request #1022 from kisielk/masterKenneth Reitzbefore adoptiond0f2382

line 131why, one step back
131 >>> r.json()

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

lines 132–133why, one step back
132 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
133

Merge pull request #1022 from kisielk/masterKenneth Reitzbefore adoptiond0f2382

line 134why, one step back
134In case the JSON decoding fails, ``r.json`` raises an exception.

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

lines 135–141why, one step back
135
136137Raw Response Content138--------------------139140In the rare case that you'd like to get the raw socket response from the141server, you can access ``r.raw``. If you want to do this, make sure you set

update docsKenneth Reitzbefore adoption1451ba0

line 142why, one step back
142``stream=True`` in your initial request. Once you do, you can do this::

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

line 143why, one step back
143

Merge pull request #1230 from davidfischer/trivial-docs-fixKenneth Reitzbefore adoption98ff29f

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

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

lines 145–177why, 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 {

update docsKenneth Reitzbefore adoption5b5ff69

line 178why, one step back
178 ...

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

lines 179–182why, one step back
179 "form": {
180 "key2": "value2",181 "key1": "value1"182 },

update docsKenneth Reitzbefore adoption5b5ff69

line 183why, one step back
183 ...

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

lines 184–207why, one step back
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'203 >>> files = {'file': open('report.xls', 'rb')}204205 >>> r = requests.post(url, files=files)206 >>> r.text207 {

update docsKenneth Reitzbefore adoption5b5ff69

line 208why, one step back
208 ...

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

lines 209–211why, one step back
209 "files": {
210 "file": "<censored...binary...data>"211 },

update docsKenneth Reitzbefore adoption5b5ff69

line 212why, one step back
212 ...

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

lines 213–222why, one step back
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 {

update docsKenneth Reitzbefore adoption5b5ff69

line 223why, one step back
223 ...

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

lines 224–226why, one step back
224 "files": {
225 "file": "<censored...binary...data>"226 },

update docsKenneth Reitzbefore adoption5b5ff69

line 227why, one step back
227 ...

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

lines 228–237why, one step back
228 }
229230If you want, you can send strings to be received as files::231232 >>> url = 'http://httpbin.org/post'233 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}234235 >>> r = requests.post(url, files=files)236 >>> r.text237 {

update docsKenneth Reitzbefore adoption5b5ff69

line 238why, one step back
238 ...

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

lines 239–241why, one step back
239 "files": {
240 "file": "some,data,to,send\\nanother,row,to,send\\n"241 },

update docsKenneth Reitzbefore adoption5b5ff69

line 242why, one step back
242 ...

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

lines 243–321why, one step back
243 }
244245246Response Status Codes247---------------------248249We can check the response status code::250251 >>> r = requests.get('http://httpbin.org/get')252 >>> r.status_code253 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()`::263264 >>> bad_r = requests.get('http://httpbin.org/status/404')265 >>> bad_r.status_code266 404267268 >>> bad_r.raise_for_status()269 Traceback (most recent call last):270 File "requests/models.py", line 832, in raise_for_status271 raise http_error272 requests.exceptions.HTTPError: 404 Client Error273274But, 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 'content-encoding': 'gzip',291 'transfer-encoding': 'chunked',292 'connection': 'close',293 'server': 'nginx/1.0.4',294 'x-runtime': '148ms',295 'etag': '"e1ca502697e5c9317743dc078f67693f"',296 'content-type': 'application/json; charset=utf-8'297 }298299The dictionary is special, though: it's made just for HTTP headers. According to300`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP301Headers are case-insensitive.302303So, we can access the headers using any capitalization we want::304305 >>> r.headers['Content-Type']306 'application/json; charset=utf-8'307308 >>> r.headers.get('content-type')309 'application/json; charset=utf-8'310311If a header doesn't exist in the Response, its value defaults to ``None``::312313 >>> r.headers['X-Random']314 None315316317Cookies318-------319320If a response contains some Cookies, you can get quick access to them::321

Merge pull request #1107 from Lukasa/masterKenneth Reitzbefore adoptionf038f68

line 322why, one step back
322 >>> url = 'http://example.com/some/cookie/setting/url'

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

lines 323–324why, one step back
323 >>> r = requests.get(url)
324

Merge pull request #1107 from Lukasa/masterKenneth Reitzbefore adoptionf038f68

lines 325–326why, one step back
325 >>> r.cookies['example_cookie_name']
326 'example_cookie_value'

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

lines 327–386why, one step back
327
328To send your own cookies to the server, you can use the ``cookies``329parameter::330331 >>> url = 'http://httpbin.org/cookies'332 >>> cookies = dict(cookies_are='working')333334 >>> r = requests.get(url, cookies=cookies)335 >>> r.text336 '{"cookies": {"cookies_are": "working"}}'337338339Redirection and History340-----------------------341342Requests will automatically perform location redirection while using the GET343and OPTIONS verbs.344345GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method346of the Response object to track redirection. Let's see what Github does::347348 >>> r = requests.get('http://github.com')349 >>> r.url350 'https://github.com/'351 >>> r.status_code352 200353 >>> r.history354 [<Response [301]>]355356The :class:`Response.history` list contains a list of the357:class:`Request` objects that were created in order to complete the request. The list is sorted from the oldest to the most recent request.358359If you're using GET or OPTIONS, you can disable redirection handling with the360``allow_redirects`` parameter::361362 >>> r = requests.get('http://github.com', allow_redirects=False)363 >>> r.status_code364 301365 >>> r.history366 []367368If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable369redirection as well::370371 >>> r = requests.post('http://github.com', allow_redirects=True)372 >>> r.url373 'https://github.com/'374 >>> r.history375 [<Response [301]>]376377378Timeouts379--------380381You can tell requests to stop waiting for a response after a given number of382seconds with the ``timeout`` parameter::383384 >>> requests.get('http://github.com', timeout=0.001)385 Traceback (most recent call last):386 File "<stdin>", line 1, in <module>

timeoutKenneth Reitzbefore adoptionf1d51aa

lines 387–388why, one step back
387 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
388

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

lines 389–415why, one step back
389
390.. admonition:: Note:391392 ``timeout`` only effects the connection process itself, not the393 downloading of the response body.394395396Errors and Exceptions397---------------------398399In the event of a network problem (e.g. DNS failure, refused connection, etc),400Requests will raise a :class:`ConnectionError` exception.401402In the event of the rare invalid HTTP response, Requests will raise403an :class:`HTTPError` exception.404405If a request times out, a :class:`Timeout` exception is raised.406407If a request exceeds the configured number of maximum redirections, a408:class:`TooManyRedirects` exception is raised.409410All exceptions that Requests explicitly raises inherit from411:class:`requests.exceptions.RequestException`.412413-----------------------414415Ready for more? Check out the :ref:`advanced <advanced>` section.