quickstart.rst
This file
Path
docs/user/quickstart.rst
558 lines · 17.9 KiB
Last changed by
Merge pull request #4676 from jdufresne/doc-py3Nate Prewittbefore adoption16fd7e0
History of this fileTake it
The walk stopped after 200 commits: lines older than 916d171 point at it.
Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 1–5why, one step back1.. _quickstart:23Quickstart4==========5Update quickstart.rstKenneth Reitzbefore adoption8af65a1
lines 6–7why, one step back6.. image:: https://farm5.staticflickr.com/4259/35163667010_8bfcaef274_k_d.jpg7Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 8–112why, one step back8.. module:: requests.models910Eager to get started? This page gives a good introduction in how to get started11with Requests.1213First, make sure that:1415* Requests is :ref:`installed <install>`16* Requests is :ref:`up-to-date <updates>`171819Let's get started with some simple examples.202122Make a Request23--------------2425Making a request with Requests is very simple.2627Begin by importing the Requests module::2829 >>> import requests3031Now, let's try to get a webpage. For this example, let's get GitHub's public32timeline::3334 >>> r = requests.get('https://api.github.com/events')3536Now, we have a :class:`Response <requests.Response>` object called ``r``. We can37get all the information we need from this object.3839Requests' simple API means that all forms of HTTP request are as obvious. For40example, this is how you make an HTTP POST request::4142 >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})4344Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and45OPTIONS? These are all just as simple::4647 >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})48 >>> r = requests.delete('http://httpbin.org/delete')49 >>> r = requests.head('http://httpbin.org/get')50 >>> r = requests.options('http://httpbin.org/get')5152That's all well and good, but it's also only the start of what Requests can53do.545556Passing Parameters In URLs57--------------------------5859You often want to send some sort of data in the URL's query string. If60you were constructing the URL by hand, this data would be given as key/value61pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.62Requests allows you to provide these arguments as a dictionary of strings,63using the ``params`` keyword argument. As an example, if you wanted to pass64``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the65following code::6667 >>> payload = {'key1': 'value1', 'key2': 'value2'}68 >>> r = requests.get('http://httpbin.org/get', params=payload)6970You can see that the URL has been correctly encoded by printing the URL::7172 >>> print(r.url)73 http://httpbin.org/get?key2=value2&key1=value17475Note that any dictionary key whose value is ``None`` will not be added to the76URL's query string.7778You can also pass a list of items as a value::7980 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}8182 >>> r = requests.get('http://httpbin.org/get', params=payload)83 >>> print(r.url)84 http://httpbin.org/get?key1=value1&key2=value2&key2=value38586Response Content87----------------8889We can read the content of the server's response. Consider the GitHub timeline90again::9192 >>> import requests9394 >>> r = requests.get('https://api.github.com/events')95 >>> r.text96 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9798Requests will automatically decode content from the server. Most unicode99charsets are seamlessly decoded.100101When you make a request, Requests makes educated guesses about the encoding of102the response based on the HTTP headers. The text encoding guessed by Requests103is used when you access ``r.text``. You can find out what encoding Requests is104using, and change it, using the ``r.encoding`` property::105106 >>> r.encoding107 'utf-8'108 >>> r.encoding = 'ISO-8859-1'109110If you change the encoding, Requests will use the new value of ``r.encoding``111whenever you call ``r.text``. You might want to do this in any situation where112you can apply special logic to work out what the encoding of the content willMerge pull request #4384 from taleinat/quickstart_doc_http_to_htmlIan Stapleton Cordascobefore adoption6d69f94
line 113why, one step back113be. For example, HTML and XML have the ability to specify their encoding inMerge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 114–173why, one step back114their body. In situations like this, you should use ``r.content`` to find the115encoding, and then set ``r.encoding``. This will let you use ``r.text`` with116the correct encoding.117118Requests will also use custom encodings in the event that you need them. If119you have created your own encoding and registered it with the ``codecs``120module, you can simply use the codec name as the value of ``r.encoding`` and121Requests will handle the decoding for you.122123Binary Response Content124-----------------------125126You can also access the response body as bytes, for non-text requests::127128 >>> r.content129 b'[{"repository":{"open_issues":0,"url":"https://github.com/...130131The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.132133For example, to create an image from binary data returned by a request, you can134use the following code::135136 >>> from PIL import Image137 >>> from io import BytesIO138139 >>> i = Image.open(BytesIO(r.content))140141142JSON Response Content143---------------------144145There's also a builtin JSON decoder, in case you're dealing with JSON data::146147 >>> import requests148149 >>> r = requests.get('https://api.github.com/events')150 >>> r.json()151 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...152153In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if154the response gets a 204 (No Content), or if the response contains invalid JSON,155attempting ``r.json()`` raises ``ValueError: No JSON object could be decoded``.156157It should be noted that the success of the call to ``r.json()`` does **not**158indicate the success of the response. Some servers may return a JSON object in a159failed response (e.g. error details with HTTP 500). Such JSON will be decoded160and returned. To check that a request is successful, use161``r.raise_for_status()`` or check ``r.status_code`` is what you expect.162163164Raw Response Content165--------------------166167In the rare case that you'd like to get the raw socket response from the168server, you can access ``r.raw``. If you want to do this, make sure you set169``stream=True`` in your initial request. Once you do, you can do this::170171 >>> r = requests.get('https://api.github.com/events', stream=True)172173 >>> r.rawMerge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption27aad36
line 174why, one step back174 <urllib3.response.HTTPResponse object at 0x101194810>Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 175–191why, one step back175176 >>> r.raw.read(10)177 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'178179In general, however, you should use a pattern like this to save what is being180streamed to a file::181182 with open(filename, 'wb') as fd:183 for chunk in r.iter_content(chunk_size=128):184 fd.write(chunk)185186Using ``Response.iter_content`` will handle a lot of what you would otherwise187have to handle when using ``Response.raw`` directly. When streaming a188download, the above is the preferred and recommended way to retrieve the189content. Note that ``chunk_size`` can be freely adjusted to a number that190may better fit your use cases.191Merge pull request #4387 from dave-shawley/clarify-docsCory Benfieldbefore adoptionc3f2553
lines 192–199why, one step back192.. note::193194 An important note about using ``Response.iter_content`` versus ``Response.raw``.195 ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``196 transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not197 transform the response content. If you really need access to the bytes as they198 were returned, use ``Response.raw``.199Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 200–283why, one step back200201Custom Headers202--------------203204If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the205``headers`` parameter.206207For example, we didn't specify our user-agent in the previous example::208209 >>> url = 'https://api.github.com/some/endpoint'210 >>> headers = {'user-agent': 'my-app/0.0.1'}211212 >>> r = requests.get(url, headers=headers)213214Note: Custom headers are given less precedence than more specific sources of information. For instance:215216* Authorization headers set with `headers=` will be overridden if credentials217 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``218 parameter.219* Authorization headers will be removed if you get redirected off-host.220* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.221* Content-Length headers will be overridden when we can determine the length of the content.222223Furthermore, 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.224225Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.226227More complicated POST requests228------------------------------229230Typically, you want to send some form-encoded data — much like an HTML form.231To do this, simply pass a dictionary to the ``data`` argument. Your232dictionary of data will automatically be form-encoded when the request is made::233234 >>> payload = {'key1': 'value1', 'key2': 'value2'}235236 >>> r = requests.post("http://httpbin.org/post", data=payload)237 >>> print(r.text)238 {239 ...240 "form": {241 "key2": "value2",242 "key1": "value1"243 },244 ...245 }246247You can also pass a list of tuples to the ``data`` argument. This is particularly248useful when the form has multiple elements that use the same key::249250 >>> payload = (('key1', 'value1'), ('key1', 'value2'))251 >>> r = requests.post('http://httpbin.org/post', data=payload)252 >>> print(r.text)253 {254 ...255 "form": {256 "key1": [257 "value1",258 "value2"259 ]260 },261 ...262 }263264There are times that you may want to send data that is not form-encoded. If265you pass in a ``string`` instead of a ``dict``, that data will be posted directly.266267For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::268269 >>> import json270271 >>> url = 'https://api.github.com/some/endpoint'272 >>> payload = {'some': 'data'}273274 >>> r = requests.post(url, data=json.dumps(payload))275276Instead of encoding the ``dict`` yourself, you can also pass it directly using277the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::278279 >>> url = 'https://api.github.com/some/endpoint'280 >>> payload = {'some': 'data'}281282 >>> r = requests.post(url, json=payload)283Merge pull request #4368 from danielroseman/patch-1Nate Prewittbefore adoptione68ef0e
line 284why, one step back284Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
line 285why, one step back285Merge pull request #4547 from Saraislet/json-kwarg-docsNate Prewittbefore adoptionb66908e
lines 286–287why, one step back286Using the ``json`` parameter in the request will change the ``Content-Type`` in the header to ``application/json``.287Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 288–350why, one step back288POST a Multipart-Encoded File289-----------------------------290291Requests makes it simple to upload Multipart-encoded files::292293 >>> url = 'http://httpbin.org/post'294 >>> files = {'file': open('report.xls', 'rb')}295296 >>> r = requests.post(url, files=files)297 >>> r.text298 {299 ...300 "files": {301 "file": "<censored...binary...data>"302 },303 ...304 }305306You can set the filename, content_type and headers explicitly::307308 >>> url = 'http://httpbin.org/post'309 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}310311 >>> r = requests.post(url, files=files)312 >>> r.text313 {314 ...315 "files": {316 "file": "<censored...binary...data>"317 },318 ...319 }320321If you want, you can send strings to be received as files::322323 >>> url = 'http://httpbin.org/post'324 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}325326 >>> r = requests.post(url, files=files)327 >>> r.text328 {329 ...330 "files": {331 "file": "some,data,to,send\\nanother,row,to,send\\n"332 },333 ...334 }335336In the event you are posting a very large file as a ``multipart/form-data``337request, you may want to stream the request. By default, ``requests`` does not338support this, but there is a separate package which does -339``requests-toolbelt``. You should read `the toolbelt's documentation340<https://toolbelt.readthedocs.io>`_ for more details about how to use it.341342For sending multiple files in one request refer to the :ref:`advanced <advanced>`343section.344345.. warning:: It is strongly recommended that you open files in `binary mode`_.346 This is because Requests may attempt to provide the347 ``Content-Length`` header for you, and if it does this value will348 be set to the number of *bytes* in the file. Errors may occur if349 you open the file in *text mode*.350Merge pull request #4676 from jdufresne/doc-py3Nate Prewittbefore adoption16fd7e0
line 351why, one step back351.. _binary mode: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-filesMerge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoption916d171
lines 352–558why, one step back352353354Response Status Codes355---------------------356357We can check the response status code::358359 >>> r = requests.get('http://httpbin.org/get')360 >>> r.status_code361 200362363Requests also comes with a built-in status code lookup object for easy364reference::365366 >>> r.status_code == requests.codes.ok367 True368369If we made a bad request (a 4XX client error or 5XX server error response), we370can raise it with371:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::372373 >>> bad_r = requests.get('http://httpbin.org/status/404')374 >>> bad_r.status_code375 404376377 >>> bad_r.raise_for_status()378 Traceback (most recent call last):379 File "requests/models.py", line 832, in raise_for_status380 raise http_error381 requests.exceptions.HTTPError: 404 Client Error382383But, since our ``status_code`` for ``r`` was ``200``, when we call384``raise_for_status()`` we get::385386 >>> r.raise_for_status()387 None388389All is well.390391392Response Headers393----------------394395We can view the server's response headers using a Python dictionary::396397 >>> r.headers398 {399 'content-encoding': 'gzip',400 'transfer-encoding': 'chunked',401 'connection': 'close',402 'server': 'nginx/1.0.4',403 'x-runtime': '148ms',404 'etag': '"e1ca502697e5c9317743dc078f67693f"',405 'content-type': 'application/json'406 }407408The dictionary is special, though: it's made just for HTTP headers. According to409`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names410are case-insensitive.411412So, we can access the headers using any capitalization we want::413414 >>> r.headers['Content-Type']415 'application/json'416417 >>> r.headers.get('content-type')418 'application/json'419420It is also special in that the server could have sent the same header multiple421times with different values, but requests combines them so they can be422represented in the dictionary within a single mapping, as per423`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:424425 A recipient MAY combine multiple header fields with the same field name426 into one "field-name: field-value" pair, without changing the semantics427 of the message, by appending each subsequent field value to the combined428 field value in order, separated by a comma.429430Cookies431-------432433If a response contains some Cookies, you can quickly access them::434435 >>> url = 'http://example.com/some/cookie/setting/url'436 >>> r = requests.get(url)437438 >>> r.cookies['example_cookie_name']439 'example_cookie_value'440441To send your own cookies to the server, you can use the ``cookies``442parameter::443444 >>> url = 'http://httpbin.org/cookies'445 >>> cookies = dict(cookies_are='working')446447 >>> r = requests.get(url, cookies=cookies)448 >>> r.text449 '{"cookies": {"cookies_are": "working"}}'450451Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,452which acts like a ``dict`` but also offers a more complete interface,453suitable for use over multiple domains or paths. Cookie jars can454also be passed in to requests::455456 >>> jar = requests.cookies.RequestsCookieJar()457 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')458 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')459 >>> url = 'http://httpbin.org/cookies'460 >>> r = requests.get(url, cookies=jar)461 >>> r.text462 '{"cookies": {"tasty_cookie": "yum"}}'463464465Redirection and History466-----------------------467468By default Requests will perform location redirection for all verbs except469HEAD.470471We can use the ``history`` property of the Response object to track redirection.472473The :attr:`Response.history <requests.Response.history>` list contains the474:class:`Response <requests.Response>` objects that were created in order to475complete the request. The list is sorted from the oldest to the most recent476response.477478For example, GitHub redirects all HTTP requests to HTTPS::479480 >>> r = requests.get('http://github.com')481482 >>> r.url483 'https://github.com/'484485 >>> r.status_code486 200487488 >>> r.history489 [<Response [301]>]490491492If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable493redirection handling with the ``allow_redirects`` parameter::494495 >>> r = requests.get('http://github.com', allow_redirects=False)496497 >>> r.status_code498 301499500 >>> r.history501 []502503If you're using HEAD, you can enable redirection as well::504505 >>> r = requests.head('http://github.com', allow_redirects=True)506507 >>> r.url508 'https://github.com/'509510 >>> r.history511 [<Response [301]>]512513514Timeouts515--------516517You can tell Requests to stop waiting for a response after a given number of518seconds with the ``timeout`` parameter. Nearly all production code should use519this parameter in nearly all requests. Failure to do so can cause your program520to hang indefinitely::521522 >>> requests.get('http://github.com', timeout=0.001)523 Traceback (most recent call last):524 File "<stdin>", line 1, in <module>525 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)526527528.. admonition:: Note529530 ``timeout`` is not a time limit on the entire response download;531 rather, an exception is raised if the server has not issued a532 response for ``timeout`` seconds (more precisely, if no bytes have been533 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do534 not time out.535536537Errors and Exceptions538---------------------539540In the event of a network problem (e.g. DNS failure, refused connection, etc),541Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.542543:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will544raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request545returned an unsuccessful status code.546547If a request times out, a :exc:`~requests.exceptions.Timeout` exception is548raised.549550If a request exceeds the configured number of maximum redirections, a551:exc:`~requests.exceptions.TooManyRedirects` exception is raised.552553All exceptions that Requests explicitly raises inherit from554:exc:`requests.exceptions.RequestException`.555556-----------------------557558Ready for more? Check out the :ref:`advanced <advanced>` section.