quickstart.rst
This file
Path
docs/user/quickstart.rst
545 lines · 17.3 KiB
Last changed by
improvementsKenneth Reitzbefore adoptionb9a004a
History of this fileTake it
The walk stopped after 200 commits: lines older than 5a280a1 point at it.
we don't support python 3.2Kenneth Reitzbefore adoption5a280a1
lines 1–59why, one step back1.. _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::3940 >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})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', data = {'key':'value'})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``.Merge pull request #3857 from Lukasa/params-docsIan Cordascobefore adoption0bea453
lines 60–61why, one step back60Requests allows you to provide these arguments as a dictionary of strings,61using the ``params`` keyword argument. As an example, if you wanted to passwe don't support python 3.2Kenneth Reitzbefore adoption5a280a1
lines 62–236why, one step back62``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.7576You can also pass a list of items as a value::7778 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}7980 >>> r = requests.get('http://httpbin.org/get', params=payload)81 >>> print(r.url)82 http://httpbin.org/get?key1=value1&key2=value2&key2=value38384Response Content85----------------8687We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requests9192 >>> r = requests.get('https://api.github.com/events')93 >>> r.text94 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9596Requests will automatically decode content from the server. Most unicode97charsets are seamlessly decoded.9899When you make a request, Requests makes educated guesses about the encoding of100the response based on the HTTP headers. The text encoding guessed by Requests101is used when you access ``r.text``. You can find out what encoding Requests is102using, and change it, using the ``r.encoding`` property::103104 >>> r.encoding105 'utf-8'106 >>> r.encoding = 'ISO-8859-1'107108If you change the encoding, Requests will use the new value of ``r.encoding``109whenever you call ``r.text``. You might want to do this in any situation where110you can apply special logic to work out what the encoding of the content will111be. For example, HTTP and XML have the ability to specify their encoding in112their body. In situations like this, you should use ``r.content`` to find the113encoding, and then set ``r.encoding``. This will let you use ``r.text`` with114the correct encoding.115116Requests will also use custom encodings in the event that you need them. If117you have created your own encoding and registered it with the ``codecs``118module, you can simply use the codec name as the value of ``r.encoding`` and119Requests will handle the decoding for you.120121Binary Response Content122-----------------------123124You can also access the response body as bytes, for non-text requests::125126 >>> r.content127 b'[{"repository":{"open_issues":0,"url":"https://github.com/...128129The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.130131For example, to create an image from binary data returned by a request, you can132use the following code::133134 >>> from PIL import Image135 >>> from io import BytesIO136137 >>> i = Image.open(BytesIO(r.content))138139140JSON Response Content141---------------------142143There's also a builtin JSON decoder, in case you're dealing with JSON data::144145 >>> import requests146147 >>> r = requests.get('https://api.github.com/events')148 >>> r.json()149 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...150151In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if152the response gets a 204 (No Content), or if the response contains invalid JSON,153attempting ``r.json()`` raises ``ValueError: No JSON object could be decoded``.154155It should be noted that the success of the call to ``r.json()`` does **not**156indicate the success of the response. Some servers may return a JSON object in a157failed response (e.g. error details with HTTP 500). Such JSON will be decoded158and returned. To check that a request is successful, use159``r.raise_for_status()`` or check ``r.status_code`` is what you expect.160161162Raw Response Content163--------------------164165In the rare case that you'd like to get the raw socket response from the166server, you can access ``r.raw``. If you want to do this, make sure you set167``stream=True`` in your initial request. Once you do, you can do this::168169 >>> r = requests.get('https://api.github.com/events', stream=True)170171 >>> r.raw172 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>173174 >>> r.raw.read(10)175 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'176177In general, however, you should use a pattern like this to save what is being178streamed to a file::179180 with open(filename, 'wb') as fd:181 for chunk in r.iter_content(chunk_size=128):182 fd.write(chunk)183184Using ``Response.iter_content`` will handle a lot of what you would otherwise185have to handle when using ``Response.raw`` directly. When streaming a186download, the above is the preferred and recommended way to retrieve the187content. Note that ``chunk_size`` can be freely adjusted to a number that188may better fit your use cases.189190191Custom Headers192--------------193194If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the195``headers`` parameter.196197For example, we didn't specify our user-agent in the previous example::198199 >>> url = 'https://api.github.com/some/endpoint'200 >>> headers = {'user-agent': 'my-app/0.0.1'}201202 >>> r = requests.get(url, headers=headers)203204Note: Custom headers are given less precedence than more specific sources of information. For instance:205206* Authorization headers set with `headers=` will be overridden if credentials207 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``208 parameter.209* Authorization headers will be removed if you get redirected off-host.210* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.211* Content-Length headers will be overridden when we can determine the length of the content.212213Furthermore, 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.214215Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.216217More complicated POST requests218------------------------------219220Typically, you want to send some form-encoded data — much like an HTML form.221To do this, simply pass a dictionary to the ``data`` argument. Your222dictionary of data will automatically be form-encoded when the request is made::223224 >>> payload = {'key1': 'value1', 'key2': 'value2'}225226 >>> r = requests.post("http://httpbin.org/post", data=payload)227 >>> print(r.text)228 {229 ...230 "form": {231 "key2": "value2",232 "key1": "value1"233 },234 ...235 }236mergeKenneth Reitzbefore adoption2e67c86
lines 237–253why, one step back237You can also pass a list of tuples to the ``data`` argument. This is particularly238useful when the form has multiple elements that use the same key::239240 >>> payload = (('key1', 'value1'), ('key1', 'value2'))241 >>> r = requests.post('http://httpbin.org/post', data=payload)242 >>> print(r.text)243 {244 ...245 "form": {246 "key1": [247 "value1",248 "value2"249 ]250 },251 ...252 }253improvementsKenneth Reitzbefore adoptionb9a004a
line 254why, one step back254There are times that you may want to send data that is not form-encoded. Ifwe don't support python 3.2Kenneth Reitzbefore adoption5a280a1
lines 255–504why, one step back255you pass in a ``string`` instead of a ``dict``, that data will be posted directly.256257For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::258259 >>> import json260261 >>> url = 'https://api.github.com/some/endpoint'262 >>> payload = {'some': 'data'}263264 >>> r = requests.post(url, data=json.dumps(payload))265266Instead of encoding the ``dict`` yourself, you can also pass it directly using267the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::268269 >>> url = 'https://api.github.com/some/endpoint'270 >>> payload = {'some': 'data'}271272 >>> r = requests.post(url, json=payload)273274275POST a Multipart-Encoded File276-----------------------------277278Requests makes it simple to upload Multipart-encoded files::279280 >>> url = 'http://httpbin.org/post'281 >>> files = {'file': open('report.xls', 'rb')}282283 >>> r = requests.post(url, files=files)284 >>> r.text285 {286 ...287 "files": {288 "file": "<censored...binary...data>"289 },290 ...291 }292293You can set the filename, content_type and headers explicitly::294295 >>> url = 'http://httpbin.org/post'296 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}297298 >>> r = requests.post(url, files=files)299 >>> r.text300 {301 ...302 "files": {303 "file": "<censored...binary...data>"304 },305 ...306 }307308If you want, you can send strings to be received as files::309310 >>> url = 'http://httpbin.org/post'311 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}312313 >>> r = requests.post(url, files=files)314 >>> r.text315 {316 ...317 "files": {318 "file": "some,data,to,send\\nanother,row,to,send\\n"319 },320 ...321 }322323In the event you are posting a very large file as a ``multipart/form-data``324request, you may want to stream the request. By default, ``requests`` does not325support this, but there is a separate package which does -326``requests-toolbelt``. You should read `the toolbelt's documentation327<https://toolbelt.readthedocs.io>`_ for more details about how to use it.328329For sending multiple files in one request refer to the :ref:`advanced <advanced>`330section.331332.. warning:: It is strongly recommended that you open files in `binary mode`_.333 This is because Requests may attempt to provide the334 ``Content-Length`` header for you, and if it does this value will335 be set to the number of *bytes* in the file. Errors may occur if336 you open the file in *text mode*.337338.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files339340341Response Status Codes342---------------------343344We can check the response status code::345346 >>> r = requests.get('http://httpbin.org/get')347 >>> r.status_code348 200349350Requests also comes with a built-in status code lookup object for easy351reference::352353 >>> r.status_code == requests.codes.ok354 True355356If we made a bad request (a 4XX client error or 5XX server error response), we357can raise it with358:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::359360 >>> bad_r = requests.get('http://httpbin.org/status/404')361 >>> bad_r.status_code362 404363364 >>> bad_r.raise_for_status()365 Traceback (most recent call last):366 File "requests/models.py", line 832, in raise_for_status367 raise http_error368 requests.exceptions.HTTPError: 404 Client Error369370But, since our ``status_code`` for ``r`` was ``200``, when we call371``raise_for_status()`` we get::372373 >>> r.raise_for_status()374 None375376All is well.377378379Response Headers380----------------381382We can view the server's response headers using a Python dictionary::383384 >>> r.headers385 {386 'content-encoding': 'gzip',387 'transfer-encoding': 'chunked',388 'connection': 'close',389 'server': 'nginx/1.0.4',390 'x-runtime': '148ms',391 'etag': '"e1ca502697e5c9317743dc078f67693f"',392 'content-type': 'application/json'393 }394395The dictionary is special, though: it's made just for HTTP headers. According to396`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names397are case-insensitive.398399So, we can access the headers using any capitalization we want::400401 >>> r.headers['Content-Type']402 'application/json'403404 >>> r.headers.get('content-type')405 'application/json'406407It is also special in that the server could have sent the same header multiple408times with different values, but requests combines them so they can be409represented in the dictionary within a single mapping, as per410`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:411412 A recipient MAY combine multiple header fields with the same field name413 into one "field-name: field-value" pair, without changing the semantics414 of the message, by appending each subsequent field value to the combined415 field value in order, separated by a comma.416417Cookies418-------419420If a response contains some Cookies, you can quickly access them::421422 >>> url = 'http://example.com/some/cookie/setting/url'423 >>> r = requests.get(url)424425 >>> r.cookies['example_cookie_name']426 'example_cookie_value'427428To send your own cookies to the server, you can use the ``cookies``429parameter::430431 >>> url = 'http://httpbin.org/cookies'432 >>> cookies = dict(cookies_are='working')433434 >>> r = requests.get(url, cookies=cookies)435 >>> r.text436 '{"cookies": {"cookies_are": "working"}}'437438Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,439which acts like a ``dict`` but also offers a more complete interface,440suitable for use over multiple domains or paths. Cookie jars can441also be passed in to requests::442443 >>> jar = requests.cookies.RequestsCookieJar()444 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')445 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')446 >>> url = 'http://httpbin.org/cookies'447 >>> r = requests.get(url, cookies=jar)448 >>> r.text449 '{"cookies": {"tasty_cookie": "yum"}}'450451452Redirection and History453-----------------------454455By default Requests will perform location redirection for all verbs except456HEAD.457458We can use the ``history`` property of the Response object to track redirection.459460The :attr:`Response.history <requests.Response.history>` list contains the461:class:`Response <requests.Response>` objects that were created in order to462complete the request. The list is sorted from the oldest to the most recent463response.464465For example, GitHub redirects all HTTP requests to HTTPS::466467 >>> r = requests.get('http://github.com')468469 >>> r.url470 'https://github.com/'471472 >>> r.status_code473 200474475 >>> r.history476 [<Response [301]>]477478479If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable480redirection handling with the ``allow_redirects`` parameter::481482 >>> r = requests.get('http://github.com', allow_redirects=False)483484 >>> r.status_code485 301486487 >>> r.history488 []489490If you're using HEAD, you can enable redirection as well::491492 >>> r = requests.head('http://github.com', allow_redirects=True)493494 >>> r.url495 'https://github.com/'496497 >>> r.history498 [<Response [301]>]499500501Timeouts502--------503504You can tell Requests to stop waiting for a response after a given number ofmergeKenneth Reitzbefore adoption2e67c86
line 505why, one step back505seconds with the ``timeout`` parameter. Nearly all production code should usewe don't support python 3.2Kenneth Reitzbefore adoption5a280a1
lines 506–545why, one step back506this parameter in nearly all requests. Failure to do so can cause your program507to hang indefinitely::508509 >>> requests.get('http://github.com', timeout=0.001)510 Traceback (most recent call last):511 File "<stdin>", line 1, in <module>512 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)513514515.. admonition:: Note516517 ``timeout`` is not a time limit on the entire response download;518 rather, an exception is raised if the server has not issued a519 response for ``timeout`` seconds (more precisely, if no bytes have been520 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do521 not time out.522523524Errors and Exceptions525---------------------526527In the event of a network problem (e.g. DNS failure, refused connection, etc),528Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.529530:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will531raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request532returned an unsuccessful status code.533534If a request times out, a :exc:`~requests.exceptions.Timeout` exception is535raised.536537If a request exceeds the configured number of maximum redirections, a538:exc:`~requests.exceptions.TooManyRedirects` exception is raised.539540All exceptions that Requests explicitly raises inherit from541:exc:`requests.exceptions.RequestException`.542543-----------------------544545Ready for more? Check out the :ref:`advanced <advanced>` section.