Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

495 lines · 15.8 KiB

Last changed by

Merge pull request #2945 from ibnIrshad/fixdocs-2062Cory Benfieldbefore adoptiona1c9b84

History of this file

Take it

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

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 1–39why, 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.1011First, 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 ::3132 >>> r = requests.get('https://api.github.com/events')3334Now, we have a :class:`Response <requests.Response>` object called ``r``. We can35get all the information we need from this object.3637Requests' simple API means that all forms of HTTP request are as obvious. For38example, this is how you make an HTTP POST request::39

Merge pull request #2831 from shagunsodhani/proposed-fix-for-#2826Cory Benfieldbefore adoption13ea739

line 40why, one step back
40 >>> r = requests.post("http://httpbin.org/post", data = {"key":"value"})

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 41–44why, one step back
41
42Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::44

Merge pull request #2831 from shagunsodhani/proposed-fix-for-#2826Cory Benfieldbefore adoption13ea739

line 45why, one step back
45 >>> r = requests.put("http://httpbin.org/put", data = {"key":"value"})

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 46–75why, one step back
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.75

Merge pull request #2680 from peplin/patch-1Cory Benfieldbefore adoption9648301

line 76why, one step back
76You can also pass a list of items as a value::

Merge pull request #2437 from tomscytale/docs_query_param_arrayCory Benfieldbefore adoptionc7beb70

line 77why, one step back
77

Merge pull request #2680 from peplin/patch-1Cory Benfieldbefore adoption9648301

line 78why, one step back
78 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

Merge pull request #2437 from tomscytale/docs_query_param_arrayCory Benfieldbefore adoptionc7beb70

lines 79–80why, one step back
79 >>> r = requests.get("http://httpbin.org/get", params=payload)
80 >>> print(r.url)

Merge pull request #2680 from peplin/patch-1Cory Benfieldbefore adoption9648301

line 81why, one step back
81 http://httpbin.org/get?key1=value1&key2=value2&key2=value3

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 82–147why, one step back
82
83Response Content84----------------8586We can read the content of the server's response. Consider the GitHub timeline87again::8889 >>> import requests90 >>> r = requests.get('https://api.github.com/events')91 >>> r.text92 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9394Requests will automatically decode content from the server. Most unicode95charsets are seamlessly decoded.9697When you make a request, Requests makes educated guesses about the encoding of98the response based on the HTTP headers. The text encoding guessed by Requests99is used when you access ``r.text``. You can find out what encoding Requests is100using, and change it, using the ``r.encoding`` property::101102 >>> r.encoding103 'utf-8'104 >>> r.encoding = 'ISO-8859-1'105106If you change the encoding, Requests will use the new value of ``r.encoding``107whenever you call ``r.text``. You might want to do this in any situation where108you can apply special logic to work out what the encoding of the content will109be. For example, HTTP and XML have the ability to specify their encoding in110their body. In situations like this, you should use ``r.content`` to find the111encoding, and then set ``r.encoding``. This will let you use ``r.text`` with112the correct encoding.113114Requests will also use custom encodings in the event that you need them. If115you have created your own encoding and registered it with the ``codecs``116module, you can simply use the codec name as the value of ``r.encoding`` and117Requests will handle the decoding for you.118119Binary Response Content120-----------------------121122You can also access the response body as bytes, for non-text requests::123124 >>> r.content125 b'[{"repository":{"open_issues":0,"url":"https://github.com/...126127The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.128129For example, to create an image from binary data returned by a request, you can130use the following code::131132 >>> from PIL import Image133 >>> from StringIO import StringIO134 >>> i = Image.open(StringIO(r.content))135136137JSON Response Content138---------------------139140There's also a builtin JSON decoder, in case you're dealing with JSON data::141142 >>> import requests143 >>> r = requests.get('https://api.github.com/events')144 >>> r.json()145 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...146147In case the JSON decoding fails, ``r.json`` raises an exception. For example, if

Merge branch 'hosamaly-master'Cory Benfieldbefore adoptionf7a43e2

lines 148–155why, one step back
148the response gets a 204 (No Content), or if the response contains invalid JSON,
149attempting ``r.json`` raises ``ValueError: No JSON object could be decoded``.150151It should be noted that the success of the call to ``r.json`` does **not**152indicate the success of the response. Some servers may return a JSON object in a153failed response (e.g. error details with HTTP 500). Such JSON will be decoded154and returned. To check that a request is successful, use155``r.raise_for_status()`` or check ``r.status_code`` is what you expect.

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 156–189why, one step back
156
157158Raw Response Content159--------------------160161In the rare case that you'd like to get the raw socket response from the162server, you can access ``r.raw``. If you want to do this, make sure you set163``stream=True`` in your initial request. Once you do, you can do this::164165 >>> r = requests.get('https://api.github.com/events', stream=True)166 >>> r.raw167 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>168 >>> r.raw.read(10)169 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'170171In general, however, you should use a pattern like this to save what is being172streamed to a file::173174 with open(filename, 'wb') as fd:175 for chunk in r.iter_content(chunk_size):176 fd.write(chunk)177178Using ``Response.iter_content`` will handle a lot of what you would otherwise179have to handle when using ``Response.raw`` directly. When streaming a180download, the above is the preferred and recommended way to retrieve the181content.182183184Custom Headers185--------------186187If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the188``headers`` parameter.189

Merge pull request #2672 from petedmarsh/fix-custom-headers-exampleIan Cordascobefore adoption0be38a0

line 190why, one step back
190For example, we didn't specify our user-agent in the previous example::

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 191–193why, one step back
191
192 >>> import json193 >>> url = 'https://api.github.com/some/endpoint'

Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb

line 194why, one step back
194 >>> headers = {'user-agent': 'my-app/0.0.1'}

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

line 195why, one step back
195

Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb

line 196why, one step back
196 >>> r = requests.get(url, headers=headers)

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

line 197why, one step back
197

Merge pull request #2525 from benjaminran/issue2062Cory Benfieldbefore adoptiond294de3

lines 198–199why, one step back
198Note: Custom headers are given less precedence than more specific sources of information. For instance:
199

Merge pull request #2945 from ibnIrshad/fixdocs-2062Cory Benfieldbefore adoptiona1c9b84

lines 200–202why, one step back
200* Authorization headers set with `headers=` will be overridden if credentials
201are specified in ``.netrc``, which in turn will be overridden by the ``auth=``202parameter.

Merge pull request #2525 from benjaminran/issue2062Cory Benfieldbefore adoptiond294de3

lines 203–208why, one step back
203* Authorization headers will be removed if you get redirected off-host.
204* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.205* Content-Length headers will be overridden when we can determine the length of the content.206207Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.208

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 209–238why, one step back
209
210More complicated POST requests211------------------------------212213Typically, you want to send some form-encoded data — much like an HTML form.214To do this, simply pass a dictionary to the ``data`` argument. Your215dictionary of data will automatically be form-encoded when the request is made::216217 >>> payload = {'key1': 'value1', 'key2': 'value2'}218 >>> r = requests.post("http://httpbin.org/post", data=payload)219 >>> print(r.text)220 {221 ...222 "form": {223 "key2": "value2",224 "key1": "value1"225 },226 ...227 }228229There are many times that you want to send data that is not form-encoded. If230you pass in a ``string`` instead of a ``dict``, that data will be posted directly.231232For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::233234 >>> import json235 >>> url = 'https://api.github.com/some/endpoint'236 >>> payload = {'some': 'data'}237238 >>> r = requests.post(url, data=json.dumps(payload))

Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb

line 239why, one step back
239

Merge pull request #2724 from smiley/masterCory Benfieldbefore adoption98a59e4

line 240why, one step back
240Instead of encoding the ``dict`` yourself, you can also pass it directly using

Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb

line 241why, one step back
241the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::

Merge pull request #2724 from smiley/masterCory Benfieldbefore adoption98a59e4

lines 242–246why, one step back
242
243 >>> url = 'https://api.github.com/some/endpoint'244 >>> payload = {'some': 'data'}245246 >>> r = requests.post(url, json=payload)

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 247–266why, one step back
247
248249POST a Multipart-Encoded File250-----------------------------251252Requests makes it simple to upload Multipart-encoded files::253254 >>> url = 'http://httpbin.org/post'255 >>> files = {'file': open('report.xls', 'rb')}256257 >>> r = requests.post(url, files=files)258 >>> r.text259 {260 ...261 "files": {262 "file": "<censored...binary...data>"263 },264 ...265 }266

Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb

line 267why, one step back
267You can set the filename, content_type and headers explicitly::

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 268–300why, one step back
268
269 >>> url = 'http://httpbin.org/post'270 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}271272 >>> r = requests.post(url, files=files)273 >>> r.text274 {275 ...276 "files": {277 "file": "<censored...binary...data>"278 },279 ...280 }281282If you want, you can send strings to be received as files::283284 >>> url = 'http://httpbin.org/post'285 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}286287 >>> r = requests.post(url, files=files)288 >>> r.text289 {290 ...291 "files": {292 "file": "some,data,to,send\\nanother,row,to,send\\n"293 },294 ...295 }296297In the event you are posting a very large file as a ``multipart/form-data``298request, you may want to stream the request. By default, ``requests`` does not299support this, but there is a separate package which does -300``requests-toolbelt``. You should read `the toolbelt's documentation

Merge pull request #2440 from aquarion/patch-1Ian Cordascobefore adoption69d9594

line 301why, one step back
301<https://toolbelt.readthedocs.org>`_ for more details about how to use it.

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 302–305why, one step back
302
303For sending multiple files in one request refer to the :ref:`advanced <advanced>`304section.305

Merge pull request #2825 from Lukasa/universal_newlinesIan Cordascobefore adoptiond290a9b

lines 306–313why, one step back
306.. warning:: It is strongly recommended that you open files in `binary mode`_.
307 This is because Requests may attempt to provide the308 ``Content-Length`` header for you, and if it does this value will309 be set to the number of *bytes* in the file. Errors may occur if310 you open the file in *text mode*.311312.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files313

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 314–380why, one step back
314
315Response Status Codes316---------------------317318We can check the response status code::319320 >>> r = requests.get('http://httpbin.org/get')321 >>> r.status_code322 200323324Requests also comes with a built-in status code lookup object for easy325reference::326327 >>> r.status_code == requests.codes.ok328 True329330If we made a bad request (a 4XX client error or 5XX server error response), we331can raise it with332:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::333334 >>> bad_r = requests.get('http://httpbin.org/status/404')335 >>> bad_r.status_code336 404337338 >>> bad_r.raise_for_status()339 Traceback (most recent call last):340 File "requests/models.py", line 832, in raise_for_status341 raise http_error342 requests.exceptions.HTTPError: 404 Client Error343344But, since our ``status_code`` for ``r`` was ``200``, when we call345``raise_for_status()`` we get::346347 >>> r.raise_for_status()348 None349350All is well.351352353Response Headers354----------------355356We can view the server's response headers using a Python dictionary::357358 >>> r.headers359 {360 'content-encoding': 'gzip',361 'transfer-encoding': 'chunked',362 'connection': 'close',363 'server': 'nginx/1.0.4',364 'x-runtime': '148ms',365 'etag': '"e1ca502697e5c9317743dc078f67693f"',366 'content-type': 'application/json'367 }368369The dictionary is special, though: it's made just for HTTP headers. According to370`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names371are case-insensitive.372373So, we can access the headers using any capitalization we want::374375 >>> r.headers['Content-Type']376 'application/json'377378 >>> r.headers.get('content-type')379 'application/json'380

Merge pull request #2453 from requiredfield/masterCory Benfieldbefore adoption6f3c91b

lines 381–385why, one step back
381It is also special in that the server could have sent the same header multiple
382times with different values, but requests combines them so they can be383represented in the dictionary within a single mapping, as per384`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:385

Merge pull request #2758 from mhils/patch-1Cory Benfieldbefore adoption14ee84b

lines 386–389why, one step back
386 A recipient MAY combine multiple header fields with the same field name
387 into one "field-name: field-value" pair, without changing the semantics388 of the message, by appending each subsequent field value to the combined389 field value in order, separated by a comma.

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

lines 390–495why, one step back
390
391Cookies392-------393394If a response contains some Cookies, you can quickly access them::395396 >>> url = 'http://example.com/some/cookie/setting/url'397 >>> r = requests.get(url)398399 >>> r.cookies['example_cookie_name']400 'example_cookie_value'401402To send your own cookies to the server, you can use the ``cookies``403parameter::404405 >>> url = 'http://httpbin.org/cookies'406 >>> cookies = dict(cookies_are='working')407408 >>> r = requests.get(url, cookies=cookies)409 >>> r.text410 '{"cookies": {"cookies_are": "working"}}'411412413Redirection and History414-----------------------415416By default Requests will perform location redirection for all verbs except417HEAD.418419We can use the ``history`` property of the Response object to track redirection.420421The :meth:`Response.history <requests.Response.history>` list contains the422:class:`Response <requests.Response>` objects that were created in order to423complete the request. The list is sorted from the oldest to the most recent424response.425426For example, GitHub redirects all HTTP requests to HTTPS::427428 >>> r = requests.get('http://github.com')429 >>> r.url430 'https://github.com/'431 >>> r.status_code432 200433 >>> r.history434 [<Response [301]>]435436437If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable438redirection handling with the ``allow_redirects`` parameter::439440 >>> r = requests.get('http://github.com', allow_redirects=False)441 >>> r.status_code442 301443 >>> r.history444 []445446If you're using HEAD, you can enable redirection as well::447448 >>> r = requests.head('http://github.com', allow_redirects=True)449 >>> r.url450 'https://github.com/'451 >>> r.history452 [<Response [301]>]453454455Timeouts456--------457458You can tell Requests to stop waiting for a response after a given number of459seconds with the ``timeout`` parameter::460461 >>> requests.get('http://github.com', timeout=0.001)462 Traceback (most recent call last):463 File "<stdin>", line 1, in <module>464 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)465466467.. admonition:: Note468469 ``timeout`` is not a time limit on the entire response download;470 rather, an exception is raised if the server has not issued a471 response for ``timeout`` seconds (more precisely, if no bytes have been472 received on the underlying socket for ``timeout`` seconds).473474475Errors and Exceptions476---------------------477478In the event of a network problem (e.g. DNS failure, refused connection, etc),479Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.480481In the rare event of an invalid HTTP response, Requests will raise an482:class:`~requests.exceptions.HTTPError` exception.483484If a request times out, a :class:`~requests.exceptions.Timeout` exception is485raised.486487If a request exceeds the configured number of maximum redirections, a488:class:`~requests.exceptions.TooManyRedirects` exception is raised.489490All exceptions that Requests explicitly raises inherit from491:class:`requests.exceptions.RequestException`.492493-----------------------494495Ready for more? Check out the :ref:`advanced <advanced>` section.