Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

480 lines · 14.9 KiB

Last changed by

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

History of this file

Take 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.7576You can also pass a list of items as a value::7778    >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}79    >>> r = requests.get("http://httpbin.org/get", params=payload)80    >>> print(r.url)81    http://httpbin.org/get?key1=value1&key2=value2&key2=value38283Response 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, if148the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:149No JSON object could be decoded``150151152Raw Response Content153--------------------154155In the rare case that you'd like to get the raw socket response from the156server, you can access ``r.raw``. If you want to do this, make sure you set157``stream=True`` in your initial request. Once you do, you can do this::158159    >>> r = requests.get('https://api.github.com/events', stream=True)160    >>> r.raw161    <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>162    >>> r.raw.read(10)163    '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'164165In general, however, you should use a pattern like this to save what is being166streamed to a file::167168    with open(filename, 'wb') as fd:169        for chunk in r.iter_content(chunk_size):170            fd.write(chunk)171172Using ``Response.iter_content`` will handle a lot of what you would otherwise173have to handle when using ``Response.raw`` directly. When streaming a174download, the above is the preferred and recommended way to retrieve the175content.176177178Custom Headers179--------------180181If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the182``headers`` parameter.183184For example, we didn't specify our user-agent in the previous example::185186    >>> import json187    >>> url = 'https://api.github.com/some/endpoint'188    >>> headers = {'user-agent': 'my-app/0.0.1'}189190    >>> r = requests.get(url, headers=headers)191192Note: Custom headers are given less precedence than more specific sources of information. For instance:193194* Authorization headers will be overridden if credentials are passed via the ``auth`` parameter or are specified in a ``.netrc`` accessible in the environment.195* Authorization headers will be removed if you get redirected off-host.196* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.197* Content-Length headers will be overridden when we can determine the length of the content.198199Furthermore, 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.200201202More complicated POST requests203------------------------------204205Typically, you want to send some form-encoded data — much like an HTML form.206To do this, simply pass a dictionary to the ``data`` argument. Your207dictionary of data will automatically be form-encoded when the request is made::208209    >>> payload = {'key1': 'value1', 'key2': 'value2'}210    >>> r = requests.post("http://httpbin.org/post", data=payload)211    >>> print(r.text)212    {213      ...214      "form": {215        "key2": "value2",216        "key1": "value1"217      },218      ...219    }220221There are many times that you want to send data that is not form-encoded. If222you pass in a ``string`` instead of a ``dict``, that data will be posted directly.223224For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::225226    >>> import json227    >>> url = 'https://api.github.com/some/endpoint'228    >>> payload = {'some': 'data'}229230    >>> r = requests.post(url, data=json.dumps(payload))231232Instead of encoding the ``dict`` yourself, you can also pass it directly using233the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::234235    >>> import json236    >>> url = 'https://api.github.com/some/endpoint'237    >>> payload = {'some': 'data'}238239    >>> r = requests.post(url, json=payload)240241242POST a Multipart-Encoded File243-----------------------------244245Requests makes it simple to upload Multipart-encoded files::246247    >>> url = 'http://httpbin.org/post'248    >>> files = {'file': open('report.xls', 'rb')}249250    >>> r = requests.post(url, files=files)251    >>> r.text252    {253      ...254      "files": {255        "file": "<censored...binary...data>"256      },257      ...258    }259260You can set the filename, content_type and headers explicitly::261262    >>> url = 'http://httpbin.org/post'263    >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}264265    >>> r = requests.post(url, files=files)266    >>> r.text267    {268      ...269      "files": {270        "file": "<censored...binary...data>"271      },272      ...273    }274275If you want, you can send strings to be received as files::276277    >>> url = 'http://httpbin.org/post'278    >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}279280    >>> r = requests.post(url, files=files)281    >>> r.text282    {283      ...284      "files": {285        "file": "some,data,to,send\\nanother,row,to,send\\n"286      },287      ...288    }289290In the event you are posting a very large file as a ``multipart/form-data``291request, you may want to stream the request. By default, ``requests`` does not292support this, but there is a separate package which does -293``requests-toolbelt``. You should read `the toolbelt's documentation294<https://toolbelt.readthedocs.org>`_ for more details about how to use it.295296For sending multiple files in one request refer to the :ref:`advanced <advanced>`297section.298299300Response Status Codes301---------------------302303We can check the response status code::304305    >>> r = requests.get('http://httpbin.org/get')306    >>> r.status_code307    200308309Requests also comes with a built-in status code lookup object for easy310reference::311312    >>> r.status_code == requests.codes.ok313    True314315If we made a bad request (a 4XX client error or 5XX server error response), we316can raise it with317:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::318319    >>> bad_r = requests.get('http://httpbin.org/status/404')320    >>> bad_r.status_code321    404322323    >>> bad_r.raise_for_status()324    Traceback (most recent call last):325      File "requests/models.py", line 832, in raise_for_status326        raise http_error327    requests.exceptions.HTTPError: 404 Client Error328329But, since our ``status_code`` for ``r`` was ``200``, when we call330``raise_for_status()`` we get::331332    >>> r.raise_for_status()333    None334335All is well.336337338Response Headers339----------------340341We can view the server's response headers using a Python dictionary::342343    >>> r.headers344    {345        'content-encoding': 'gzip',346        'transfer-encoding': 'chunked',347        'connection': 'close',348        'server': 'nginx/1.0.4',349        'x-runtime': '148ms',350        'etag': '"e1ca502697e5c9317743dc078f67693f"',351        'content-type': 'application/json'352    }353354The dictionary is special, though: it's made just for HTTP headers. According to355`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names356are case-insensitive.357358So, we can access the headers using any capitalization we want::359360    >>> r.headers['Content-Type']361    'application/json'362363    >>> r.headers.get('content-type')364    'application/json'365366It is also special in that the server could have sent the same header multiple367times with different values, but requests combines them so they can be368represented in the dictionary within a single mapping, as per369`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:370371    > A recipient MAY combine multiple header fields with the same field name372    > into one "field-name: field-value" pair, without changing the semantics373    > of the message, by appending each subsequent field value to the combined374    > field value in order, separated by a comma.375376Cookies377-------378379If a response contains some Cookies, you can quickly access them::380381    >>> url = 'http://example.com/some/cookie/setting/url'382    >>> r = requests.get(url)383384    >>> r.cookies['example_cookie_name']385    'example_cookie_value'386387To send your own cookies to the server, you can use the ``cookies``388parameter::389390    >>> url = 'http://httpbin.org/cookies'391    >>> cookies = dict(cookies_are='working')392393    >>> r = requests.get(url, cookies=cookies)394    >>> r.text395    '{"cookies": {"cookies_are": "working"}}'396397398Redirection and History399-----------------------400401By default Requests will perform location redirection for all verbs except402HEAD.403404We can use the ``history`` property of the Response object to track redirection.405406The :meth:`Response.history <requests.Response.history>` list contains the407:class:`Response <requests.Response>` objects that were created in order to408complete the request. The list is sorted from the oldest to the most recent409response.410411For example, GitHub redirects all HTTP requests to HTTPS::412413    >>> r = requests.get('http://github.com')414    >>> r.url415    'https://github.com/'416    >>> r.status_code417    200418    >>> r.history419    [<Response [301]>]420421422If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable423redirection handling with the ``allow_redirects`` parameter::424425    >>> r = requests.get('http://github.com', allow_redirects=False)426    >>> r.status_code427    301428    >>> r.history429    []430431If you're using HEAD, you can enable redirection as well::432433    >>> r = requests.head('http://github.com', allow_redirects=True)434    >>> r.url435    'https://github.com/'436    >>> r.history437    [<Response [301]>]438439440Timeouts441--------442443You can tell Requests to stop waiting for a response after a given number of444seconds with the ``timeout`` parameter::445446    >>> requests.get('http://github.com', timeout=0.001)447    Traceback (most recent call last):448      File "<stdin>", line 1, in <module>449    requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)450451452.. admonition:: Note453454    ``timeout`` is not a time limit on the entire response download;455    rather, an exception is raised if the server has not issued a456    response for ``timeout`` seconds (more precisely, if no bytes have been457    received on the underlying socket for ``timeout`` seconds).458459460Errors and Exceptions461---------------------462463In the event of a network problem (e.g. DNS failure, refused connection, etc),464Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.465466In the rare event of an invalid HTTP response, Requests will raise an467:class:`~requests.exceptions.HTTPError` exception.468469If a request times out, a :class:`~requests.exceptions.Timeout` exception is470raised.471472If a request exceeds the configured number of maximum redirections, a473:class:`~requests.exceptions.TooManyRedirects` exception is raised.474475All exceptions that Requests explicitly raises inherit from476:class:`requests.exceptions.RequestException`.477478-----------------------479480Ready for more? Check out the :ref:`advanced <advanced>` section.