quickstart.rst
This file
Path
docs/user/quickstart.rst
486 lines · 15.3 KiB
Last changed by
Merge branch 'hosamaly-master'Cory Benfieldbefore adoptionf7a43e2
History of this fileTake it
The walk stopped after 200 commits: lines older than e25fbc8 point at it.
Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 1–8why, one step back1.. _quickstart:23Quickstart4==========56.. module:: requests.models78Eager to get started? This page gives a good introduction in how to get startedMerge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515
line 9why, one step back9with Requests.Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 10–31why, one step back1011First, 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 ::31Merge pull request #2183 from Lukasa/docupdateKenneth Reitzbefore adoption7e24176
line 32why, one step back32 >>> r = requests.get('https://api.github.com/events')Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 33why, one step back33Merge pull request #2213 from kennethreitz/req-rspCory Benfieldbefore adoption2416e23
line 34why, one step back34Now, we have a :class:`Response <requests.Response>` object called ``r``. We canMerge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515
line 35why, one step back35get all the information we need from this object.Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 36–75why, one step back3637Requests' simple API means that all forms of HTTP request are as obvious. For38example, this is how you make an HTTP POST request::3940 >>> r = requests.post("http://httpbin.org/post")4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::4445 >>> r = requests.put("http://httpbin.org/put")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.75Merge pull request #2680 from peplin/patch-1Cory Benfieldbefore adoption9648301
line 76why, one step back76You 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 back77Merge pull request #2680 from peplin/patch-1Cory Benfieldbefore adoption9648301
line 78why, one step back78 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}Merge pull request #2437 from tomscytale/docs_query_param_arrayCory Benfieldbefore adoptionc7beb70
lines 79–80why, one step back79 >>> 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 back81 http://httpbin.org/get?key1=value1&key2=value2&key2=value3Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 82–89why, one step back8283Response Content84----------------8586We can read the content of the server's response. Consider the GitHub timeline87again::8889 >>> import requestsFixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f
line 90why, one step back90 >>> r = requests.get('https://api.github.com/events')Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 91–142why, one step back91 >>> 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 requestsFixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f
line 143why, one step back143 >>> r = requests.get('https://api.github.com/events')Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 144–147why, one step back144 >>> 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, ifMerge branch 'hosamaly-master'Cory Benfieldbefore adoptionf7a43e2
lines 148–155why, one step back148the 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 #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 156–164why, one step back156157158Raw 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::164Fixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f
line 165why, one step back165 >>> r = requests.get('https://api.github.com/events', stream=True)Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 166–189why, one step back166 >>> 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.189Merge pull request #2672 from petedmarsh/fix-custom-headers-exampleIan Cordascobefore adoption0be38a0
line 190why, one step back190For example, we didn't specify our user-agent in the previous example::Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 191–193why, one step back191192 >>> import json193 >>> url = 'https://api.github.com/some/endpoint'Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb
line 194why, one step back194 >>> headers = {'user-agent': 'my-app/0.0.1'}Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 195why, one step back195Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb
line 196why, one step back196 >>> r = requests.get(url, headers=headers)Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 197why, one step back197Merge pull request #2525 from benjaminran/issue2062Cory Benfieldbefore adoptiond294de3
lines 198–199why, one step back198Note: Custom headers are given less precedence than more specific sources of information. For instance:199Merge pull request #2531 from benjaminran/issue2062Cory Benfieldbefore adoption18e678c
line 200why, one step back200* Authorization headers will be overridden if credentials are passed via the ``auth`` parameter or are specified in a ``.netrc`` accessible in the environment.Merge pull request #2525 from benjaminran/issue2062Cory Benfieldbefore adoptiond294de3
lines 201–206why, one step back201* Authorization headers will be removed if you get redirected off-host.202* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.203* Content-Length headers will be overridden when we can determine the length of the content.204205Furthermore, 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.206Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 207–216why, one step back207208More complicated POST requests209------------------------------210211Typically, you want to send some form-encoded data — much like an HTML form.212To do this, simply pass a dictionary to the ``data`` argument. Your213dictionary of data will automatically be form-encoded when the request is made::214215 >>> payload = {'key1': 'value1', 'key2': 'value2'}216 >>> r = requests.post("http://httpbin.org/post", data=payload)Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 217why, one step back217 >>> print(r.text)Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 218–226why, one step back218 {219 ...220 "form": {221 "key2": "value2",222 "key1": "value1"223 },224 ...225 }226Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 227–228why, one step back227There are many times that you want to send data that is not form-encoded. If228you pass in a ``string`` instead of a ``dict``, that data will be posted directly.Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 229–236why, one step back229230For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::231232 >>> import json233 >>> url = 'https://api.github.com/some/endpoint'234 >>> payload = {'some': 'data'}235236 >>> r = requests.post(url, data=json.dumps(payload))Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb
line 237why, one step back237Merge pull request #2724 from smiley/masterCory Benfieldbefore adoption98a59e4
line 238why, one step back238Instead of encoding the ``dict`` yourself, you can also pass it directly usingMerge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb
line 239why, one step back239the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::Merge pull request #2724 from smiley/masterCory Benfieldbefore adoption98a59e4
lines 240–245why, one step back240241 >>> import json242 >>> url = 'https://api.github.com/some/endpoint'243 >>> payload = {'some': 'data'}244245 >>> r = requests.post(url, json=payload)Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 246–265why, one step back246247248POST a Multipart-Encoded File249-----------------------------250251Requests makes it simple to upload Multipart-encoded files::252253 >>> url = 'http://httpbin.org/post'254 >>> files = {'file': open('report.xls', 'rb')}255256 >>> r = requests.post(url, files=files)257 >>> r.text258 {259 ...260 "files": {261 "file": "<censored...binary...data>"262 },263 ...264 }265Merge pull request #2730 from bmispelon/doc-codeblock-fixIan Cordascobefore adoptionc7c26fb
line 266why, one step back266You can set the filename, content_type and headers explicitly::Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 267–295why, one step back267268 >>> url = 'http://httpbin.org/post'269 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}270271 >>> r = requests.post(url, files=files)272 >>> r.text273 {274 ...275 "files": {276 "file": "<censored...binary...data>"277 },278 ...279 }280281If you want, you can send strings to be received as files::282283 >>> url = 'http://httpbin.org/post'284 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}285286 >>> r = requests.post(url, files=files)287 >>> r.text288 {289 ...290 "files": {291 "file": "some,data,to,send\\nanother,row,to,send\\n"292 },293 ...294 }295Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
lines 296–299why, one step back296In the event you are posting a very large file as a ``multipart/form-data``297request, you may want to stream the request. By default, ``requests`` does not298support this, but there is a separate package which does -299``requests-toolbelt``. You should read `the toolbelt's documentationMerge pull request #2440 from aquarion/patch-1Ian Cordascobefore adoption69d9594
line 300why, one step back300<https://toolbelt.readthedocs.org>`_ for more details about how to use it.Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 301why, one step back301Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0
lines 302–304why, one step back302For sending multiple files in one request refer to the :ref:`advanced <advanced>`303section.304Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 305–320why, one step back305306Response Status Codes307---------------------308309We can check the response status code::310311 >>> r = requests.get('http://httpbin.org/get')312 >>> r.status_code313 200314315Requests also comes with a built-in status code lookup object for easy316reference::317318 >>> r.status_code == requests.codes.ok319 True320Merge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515
lines 321–323why, one step back321If we made a bad request (a 4XX client error or 5XX server error response), we322can raise it with323:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 324–371why, one step back324325 >>> bad_r = requests.get('http://httpbin.org/status/404')326 >>> bad_r.status_code327 404328329 >>> bad_r.raise_for_status()330 Traceback (most recent call last):331 File "requests/models.py", line 832, in raise_for_status332 raise http_error333 requests.exceptions.HTTPError: 404 Client Error334335But, since our ``status_code`` for ``r`` was ``200``, when we call336``raise_for_status()`` we get::337338 >>> r.raise_for_status()339 None340341All is well.342343344Response Headers345----------------346347We can view the server's response headers using a Python dictionary::348349 >>> r.headers350 {351 'content-encoding': 'gzip',352 'transfer-encoding': 'chunked',353 'connection': 'close',354 'server': 'nginx/1.0.4',355 'x-runtime': '148ms',356 'etag': '"e1ca502697e5c9317743dc078f67693f"',357 'content-type': 'application/json'358 }359360The dictionary is special, though: it's made just for HTTP headers. According to361`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names362are case-insensitive.363364So, we can access the headers using any capitalization we want::365366 >>> r.headers['Content-Type']367 'application/json'368369 >>> r.headers.get('content-type')370 'application/json'371Merge pull request #2453 from requiredfield/masterCory Benfieldbefore adoption6f3c91b
lines 372–376why, one step back372It is also special in that the server could have sent the same header multiple373times with different values, but requests combines them so they can be374represented in the dictionary within a single mapping, as per375`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:376Merge pull request #2758 from mhils/patch-1Cory Benfieldbefore adoption14ee84b
lines 377–380why, one step back377 A recipient MAY combine multiple header fields with the same field name378 into one "field-name: field-value" pair, without changing the semantics379 of the message, by appending each subsequent field value to the combined380 field value in order, separated by a comma.Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 381–412why, one step back381382Cookies383-------384385If a response contains some Cookies, you can quickly access them::386387 >>> url = 'http://example.com/some/cookie/setting/url'388 >>> r = requests.get(url)389390 >>> r.cookies['example_cookie_name']391 'example_cookie_value'392393To send your own cookies to the server, you can use the ``cookies``394parameter::395396 >>> url = 'http://httpbin.org/cookies'397 >>> cookies = dict(cookies_are='working')398399 >>> r = requests.get(url, cookies=cookies)400 >>> r.text401 '{"cookies": {"cookies_are": "working"}}'402403404Redirection and History405-----------------------406407By default Requests will perform location redirection for all verbs except408HEAD.409410We can use the ``history`` property of the Response object to track redirection.411412The :meth:`Response.history <requests.Response.history>` list contains theMerge pull request #2245 from sigmavirus24/doc-fixCory Benfieldbefore adoptione0d88c2
line 413why, one step back413:class:`Response <requests.Response>` objects that were created in order toMerge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 414why, one step back414complete the request. The list is sorted from the oldest to the most recentMerge pull request #2245 from sigmavirus24/doc-fixCory Benfieldbefore adoptione0d88c2
line 415why, one step back415response.Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
lines 416–486why, one step back416417For example, GitHub redirects all HTTP requests to HTTPS::418419 >>> r = requests.get('http://github.com')420 >>> r.url421 'https://github.com/'422 >>> r.status_code423 200424 >>> r.history425 [<Response [301]>]426427428If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable429redirection handling with the ``allow_redirects`` parameter::430431 >>> r = requests.get('http://github.com', allow_redirects=False)432 >>> r.status_code433 301434 >>> r.history435 []436437If you're using HEAD, you can enable redirection as well::438439 >>> r = requests.head('http://github.com', allow_redirects=True)440 >>> r.url441 'https://github.com/'442 >>> r.history443 [<Response [301]>]444445446Timeouts447--------448449You can tell Requests to stop waiting for a response after a given number of450seconds with the ``timeout`` parameter::451452 >>> requests.get('http://github.com', timeout=0.001)453 Traceback (most recent call last):454 File "<stdin>", line 1, in <module>455 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)456457458.. admonition:: Note459460 ``timeout`` is not a time limit on the entire response download;461 rather, an exception is raised if the server has not issued a462 response for ``timeout`` seconds (more precisely, if no bytes have been463 received on the underlying socket for ``timeout`` seconds).464465466Errors and Exceptions467---------------------468469In the event of a network problem (e.g. DNS failure, refused connection, etc),470Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.471472In the rare event of an invalid HTTP response, Requests will raise an473:class:`~requests.exceptions.HTTPError` exception.474475If a request times out, a :class:`~requests.exceptions.Timeout` exception is476raised.477478If a request exceeds the configured number of maximum redirections, a479:class:`~requests.exceptions.TooManyRedirects` exception is raised.480481All exceptions that Requests explicitly raises inherit from482:class:`requests.exceptions.RequestException`.483484-----------------------485486Ready for more? Check out the :ref:`advanced <advanced>` section.