quickstart.rst
This file
Path
docs/user/quickstart.rst
472 lines · 14.7 KiB
Last changed by
Merge pull request #2531 from benjaminran/issue2062Cory Benfieldbefore adoption18e678c
History of this fileTake it
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::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.7576In order to pass a list of items as a value you must mark the key as77referring to a list like string by appending ``[]`` to the key::7879 >>> payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}80 >>> r = requests.get("http://httpbin.org/get", params=payload)81 >>> print(r.url)82 http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value38384Response Content85----------------8687We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requests91 >>> r = requests.get('https://api.github.com/events')92 >>> r.text93 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9495Requests will automatically decode content from the server. Most unicode96charsets are seamlessly decoded.9798When you make a request, Requests makes educated guesses about the encoding of99the response based on the HTTP headers. The text encoding guessed by Requests100is used when you access ``r.text``. You can find out what encoding Requests is101using, and change it, using the ``r.encoding`` property::102103 >>> r.encoding104 'utf-8'105 >>> r.encoding = 'ISO-8859-1'106107If you change the encoding, Requests will use the new value of ``r.encoding``108whenever you call ``r.text``. You might want to do this in any situation where109you can apply special logic to work out what the encoding of the content will110be. For example, HTTP and XML have the ability to specify their encoding in111their body. In situations like this, you should use ``r.content`` to find the112encoding, and then set ``r.encoding``. This will let you use ``r.text`` with113the correct encoding.114115Requests will also use custom encodings in the event that you need them. If116you have created your own encoding and registered it with the ``codecs``117module, you can simply use the codec name as the value of ``r.encoding`` and118Requests will handle the decoding for you.119120Binary Response Content121-----------------------122123You can also access the response body as bytes, for non-text requests::124125 >>> r.content126 b'[{"repository":{"open_issues":0,"url":"https://github.com/...127128The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.129130For example, to create an image from binary data returned by a request, you can131use the following code::132133 >>> from PIL import Image134 >>> from StringIO import StringIO135 >>> i = Image.open(StringIO(r.content))136137138JSON Response Content139---------------------140141There's also a builtin JSON decoder, in case you're dealing with JSON data::142143 >>> import requests144 >>> r = requests.get('https://api.github.com/events')145 >>> r.json()146 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...147148In case the JSON decoding fails, ``r.json`` raises an exception. For example, if149the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:150No JSON object could be decoded``151152153Raw Response Content154--------------------155156In the rare case that you'd like to get the raw socket response from the157server, you can access ``r.raw``. If you want to do this, make sure you set158``stream=True`` in your initial request. Once you do, you can do this::159160 >>> r = requests.get('https://api.github.com/events', stream=True)161 >>> r.raw162 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>163 >>> r.raw.read(10)164 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'165166In general, however, you should use a pattern like this to save what is being167streamed to a file::168169 with open(filename, 'wb') as fd:170 for chunk in r.iter_content(chunk_size):171 fd.write(chunk)172173Using ``Response.iter_content`` will handle a lot of what you would otherwise174have to handle when using ``Response.raw`` directly. When streaming a175download, the above is the preferred and recommended way to retrieve the176content.177178179Custom Headers180--------------181182If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the183``headers`` parameter.184185For example, we didn't specify our content-type in the previous example::186187 >>> import json188 >>> url = 'https://api.github.com/some/endpoint'189 >>> headers = {'user-agent': 'my-app/0.0.1'}190191 >>> r = requests.get(url, headers=headers)192193Note: Custom headers are given less precedence than more specific sources of information. For instance:194195* Authorization headers will be overridden if credentials are passed via the ``auth`` parameter or are specified in a ``.netrc`` accessible in the environment.196* Authorization headers will be removed if you get redirected off-host.197* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.198* Content-Length headers will be overridden when we can determine the length of the content.199200Furthermore, 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.201202203More complicated POST requests204------------------------------205206Typically, you want to send some form-encoded data — much like an HTML form.207To do this, simply pass a dictionary to the ``data`` argument. Your208dictionary of data will automatically be form-encoded when the request is made::209210 >>> payload = {'key1': 'value1', 'key2': 'value2'}211 >>> r = requests.post("http://httpbin.org/post", data=payload)212 >>> print(r.text)213 {214 ...215 "form": {216 "key2": "value2",217 "key1": "value1"218 },219 ...220 }221222There are many times that you want to send data that is not form-encoded. If223you pass in a ``string`` instead of a ``dict``, that data will be posted directly.224225For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::226227 >>> import json228 >>> url = 'https://api.github.com/some/endpoint'229 >>> payload = {'some': 'data'}230231 >>> r = requests.post(url, data=json.dumps(payload))232233234POST a Multipart-Encoded File235-----------------------------236237Requests makes it simple to upload Multipart-encoded files::238239 >>> url = 'http://httpbin.org/post'240 >>> files = {'file': open('report.xls', 'rb')}241242 >>> r = requests.post(url, files=files)243 >>> r.text244 {245 ...246 "files": {247 "file": "<censored...binary...data>"248 },249 ...250 }251252You can set the filename, content_type and headers explicitly:253254 >>> url = 'http://httpbin.org/post'255 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}256257 >>> r = requests.post(url, files=files)258 >>> r.text259 {260 ...261 "files": {262 "file": "<censored...binary...data>"263 },264 ...265 }266267If you want, you can send strings to be received as files::268269 >>> url = 'http://httpbin.org/post'270 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}271272 >>> r = requests.post(url, files=files)273 >>> r.text274 {275 ...276 "files": {277 "file": "some,data,to,send\\nanother,row,to,send\\n"278 },279 ...280 }281282In the event you are posting a very large file as a ``multipart/form-data``283request, you may want to stream the request. By default, ``requests`` does not284support this, but there is a separate package which does -285``requests-toolbelt``. You should read `the toolbelt's documentation286<https://toolbelt.readthedocs.org>`_ for more details about how to use it.287288For sending multiple files in one request refer to the :ref:`advanced <advanced>`289section.290291292Response Status Codes293---------------------294295We can check the response status code::296297 >>> r = requests.get('http://httpbin.org/get')298 >>> r.status_code299 200300301Requests also comes with a built-in status code lookup object for easy302reference::303304 >>> r.status_code == requests.codes.ok305 True306307If we made a bad request (a 4XX client error or 5XX server error response), we308can raise it with309:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::310311 >>> bad_r = requests.get('http://httpbin.org/status/404')312 >>> bad_r.status_code313 404314315 >>> bad_r.raise_for_status()316 Traceback (most recent call last):317 File "requests/models.py", line 832, in raise_for_status318 raise http_error319 requests.exceptions.HTTPError: 404 Client Error320321But, since our ``status_code`` for ``r`` was ``200``, when we call322``raise_for_status()`` we get::323324 >>> r.raise_for_status()325 None326327All is well.328329330Response Headers331----------------332333We can view the server's response headers using a Python dictionary::334335 >>> r.headers336 {337 'content-encoding': 'gzip',338 'transfer-encoding': 'chunked',339 'connection': 'close',340 'server': 'nginx/1.0.4',341 'x-runtime': '148ms',342 'etag': '"e1ca502697e5c9317743dc078f67693f"',343 'content-type': 'application/json'344 }345346The dictionary is special, though: it's made just for HTTP headers. According to347`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names348are case-insensitive.349350So, we can access the headers using any capitalization we want::351352 >>> r.headers['Content-Type']353 'application/json'354355 >>> r.headers.get('content-type')356 'application/json'357358It is also special in that the server could have sent the same header multiple359times with different values, but requests combines them so they can be360represented in the dictionary within a single mapping, as per361`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:362363 > A recipient MAY combine multiple header fields with the same field name364 > into one "field-name: field-value" pair, without changing the semantics365 > of the message, by appending each subsequent field value to the combined366 > field value in order, separated by a comma.367368Cookies369-------370371If a response contains some Cookies, you can quickly access them::372373 >>> url = 'http://example.com/some/cookie/setting/url'374 >>> r = requests.get(url)375376 >>> r.cookies['example_cookie_name']377 'example_cookie_value'378379To send your own cookies to the server, you can use the ``cookies``380parameter::381382 >>> url = 'http://httpbin.org/cookies'383 >>> cookies = dict(cookies_are='working')384385 >>> r = requests.get(url, cookies=cookies)386 >>> r.text387 '{"cookies": {"cookies_are": "working"}}'388389390Redirection and History391-----------------------392393By default Requests will perform location redirection for all verbs except394HEAD.395396We can use the ``history`` property of the Response object to track redirection.397398The :meth:`Response.history <requests.Response.history>` list contains the399:class:`Response <requests.Response>` objects that were created in order to400complete the request. The list is sorted from the oldest to the most recent401response.402403For example, GitHub redirects all HTTP requests to HTTPS::404405 >>> r = requests.get('http://github.com')406 >>> r.url407 'https://github.com/'408 >>> r.status_code409 200410 >>> r.history411 [<Response [301]>]412413414If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable415redirection handling with the ``allow_redirects`` parameter::416417 >>> r = requests.get('http://github.com', allow_redirects=False)418 >>> r.status_code419 301420 >>> r.history421 []422423If you're using HEAD, you can enable redirection as well::424425 >>> r = requests.head('http://github.com', allow_redirects=True)426 >>> r.url427 'https://github.com/'428 >>> r.history429 [<Response [301]>]430431432Timeouts433--------434435You can tell Requests to stop waiting for a response after a given number of436seconds with the ``timeout`` parameter::437438 >>> requests.get('http://github.com', timeout=0.001)439 Traceback (most recent call last):440 File "<stdin>", line 1, in <module>441 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)442443444.. admonition:: Note445446 ``timeout`` is not a time limit on the entire response download;447 rather, an exception is raised if the server has not issued a448 response for ``timeout`` seconds (more precisely, if no bytes have been449 received on the underlying socket for ``timeout`` seconds).450451452Errors and Exceptions453---------------------454455In the event of a network problem (e.g. DNS failure, refused connection, etc),456Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.457458In the rare event of an invalid HTTP response, Requests will raise an459:class:`~requests.exceptions.HTTPError` exception.460461If a request times out, a :class:`~requests.exceptions.Timeout` exception is462raised.463464If a request exceeds the configured number of maximum redirections, a465:class:`~requests.exceptions.TooManyRedirects` exception is raised.466467All exceptions that Requests explicitly raises inherit from468:class:`requests.exceptions.RequestException`.469470-----------------------471472Ready for more? Check out the :ref:`advanced <advanced>` section.