Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

547 lines · 17.3 KiB

Last changed by

Update quickstart.rstKenneth Reitzbefore adoption8af65a1

History of this file

Take it

1.. _quickstart:23Quickstart4==========56.. image:: https://farm5.staticflickr.com/4259/35163667010_8bfcaef274_k_d.jpg78.. 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 will113be. For example, HTTP and XML have the ability to specify their encoding in114their 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.raw174    <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>175176    >>> 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.191192193Custom Headers194--------------195196If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the197``headers`` parameter.198199For example, we didn't specify our user-agent in the previous example::200201    >>> url = 'https://api.github.com/some/endpoint'202    >>> headers = {'user-agent': 'my-app/0.0.1'}203204    >>> r = requests.get(url, headers=headers)205206Note: Custom headers are given less precedence than more specific sources of information. For instance:207208* Authorization headers set with `headers=` will be overridden if credentials209  are specified in ``.netrc``, which in turn will be overridden by the  ``auth=``210  parameter.211* Authorization headers will be removed if you get redirected off-host.212* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.213* Content-Length headers will be overridden when we can determine the length of the content.214215Furthermore, 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.216217Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.218219More complicated POST requests220------------------------------221222Typically, you want to send some form-encoded data — much like an HTML form.223To do this, simply pass a dictionary to the ``data`` argument. Your224dictionary of data will automatically be form-encoded when the request is made::225226    >>> payload = {'key1': 'value1', 'key2': 'value2'}227228    >>> r = requests.post("http://httpbin.org/post", data=payload)229    >>> print(r.text)230    {231      ...232      "form": {233        "key2": "value2",234        "key1": "value1"235      },236      ...237    }238239You can also pass a list of tuples to the ``data`` argument. This is particularly240useful when the form has multiple elements that use the same key::241242    >>> payload = (('key1', 'value1'), ('key1', 'value2'))243    >>> r = requests.post('http://httpbin.org/post', data=payload)244    >>> print(r.text)245    {246      ...247      "form": {248        "key1": [249          "value1",250          "value2"251        ]252      },253      ...254    }255256There are times that you may want to send data that is not form-encoded. If257you pass in a ``string`` instead of a ``dict``, that data will be posted directly.258259For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::260261    >>> import json262263    >>> url = 'https://api.github.com/some/endpoint'264    >>> payload = {'some': 'data'}265266    >>> r = requests.post(url, data=json.dumps(payload))267268Instead of encoding the ``dict`` yourself, you can also pass it directly using269the ``json`` parameter (added in version 2.4.2) and it will be encoded automatically::270271    >>> url = 'https://api.github.com/some/endpoint'272    >>> payload = {'some': 'data'}273274    >>> r = requests.post(url, json=payload)275276277POST a Multipart-Encoded File278-----------------------------279280Requests makes it simple to upload Multipart-encoded files::281282    >>> url = 'http://httpbin.org/post'283    >>> files = {'file': open('report.xls', 'rb')}284285    >>> r = requests.post(url, files=files)286    >>> r.text287    {288      ...289      "files": {290        "file": "<censored...binary...data>"291      },292      ...293    }294295You can set the filename, content_type and headers explicitly::296297    >>> url = 'http://httpbin.org/post'298    >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}299300    >>> r = requests.post(url, files=files)301    >>> r.text302    {303      ...304      "files": {305        "file": "<censored...binary...data>"306      },307      ...308    }309310If you want, you can send strings to be received as files::311312    >>> url = 'http://httpbin.org/post'313    >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}314315    >>> r = requests.post(url, files=files)316    >>> r.text317    {318      ...319      "files": {320        "file": "some,data,to,send\\nanother,row,to,send\\n"321      },322      ...323    }324325In the event you are posting a very large file as a ``multipart/form-data``326request, you may want to stream the request. By default, ``requests`` does not327support this, but there is a separate package which does -328``requests-toolbelt``. You should read `the toolbelt's documentation329<https://toolbelt.readthedocs.io>`_ for more details about how to use it.330331For sending multiple files in one request refer to the :ref:`advanced <advanced>`332section.333334.. warning:: It is strongly recommended that you open files in `binary mode`_.335             This is because Requests may attempt to provide the336             ``Content-Length`` header for you, and if it does this value will337             be set to the number of *bytes* in the file. Errors may occur if338             you open the file in *text mode*.339340.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files341342343Response Status Codes344---------------------345346We can check the response status code::347348    >>> r = requests.get('http://httpbin.org/get')349    >>> r.status_code350    200351352Requests also comes with a built-in status code lookup object for easy353reference::354355    >>> r.status_code == requests.codes.ok356    True357358If we made a bad request (a 4XX client error or 5XX server error response), we359can raise it with360:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::361362    >>> bad_r = requests.get('http://httpbin.org/status/404')363    >>> bad_r.status_code364    404365366    >>> bad_r.raise_for_status()367    Traceback (most recent call last):368      File "requests/models.py", line 832, in raise_for_status369        raise http_error370    requests.exceptions.HTTPError: 404 Client Error371372But, since our ``status_code`` for ``r`` was ``200``, when we call373``raise_for_status()`` we get::374375    >>> r.raise_for_status()376    None377378All is well.379380381Response Headers382----------------383384We can view the server's response headers using a Python dictionary::385386    >>> r.headers387    {388        'content-encoding': 'gzip',389        'transfer-encoding': 'chunked',390        'connection': 'close',391        'server': 'nginx/1.0.4',392        'x-runtime': '148ms',393        'etag': '"e1ca502697e5c9317743dc078f67693f"',394        'content-type': 'application/json'395    }396397The dictionary is special, though: it's made just for HTTP headers. According to398`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names399are case-insensitive.400401So, we can access the headers using any capitalization we want::402403    >>> r.headers['Content-Type']404    'application/json'405406    >>> r.headers.get('content-type')407    'application/json'408409It is also special in that the server could have sent the same header multiple410times with different values, but requests combines them so they can be411represented in the dictionary within a single mapping, as per412`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:413414    A recipient MAY combine multiple header fields with the same field name415    into one "field-name: field-value" pair, without changing the semantics416    of the message, by appending each subsequent field value to the combined417    field value in order, separated by a comma.418419Cookies420-------421422If a response contains some Cookies, you can quickly access them::423424    >>> url = 'http://example.com/some/cookie/setting/url'425    >>> r = requests.get(url)426427    >>> r.cookies['example_cookie_name']428    'example_cookie_value'429430To send your own cookies to the server, you can use the ``cookies``431parameter::432433    >>> url = 'http://httpbin.org/cookies'434    >>> cookies = dict(cookies_are='working')435436    >>> r = requests.get(url, cookies=cookies)437    >>> r.text438    '{"cookies": {"cookies_are": "working"}}'439440Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,441which acts like a ``dict`` but also offers a more complete interface,442suitable for use over multiple domains or paths.  Cookie jars can443also be passed in to requests::444445    >>> jar = requests.cookies.RequestsCookieJar()446    >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')447    >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')448    >>> url = 'http://httpbin.org/cookies'449    >>> r = requests.get(url, cookies=jar)450    >>> r.text451    '{"cookies": {"tasty_cookie": "yum"}}'452453454Redirection and History455-----------------------456457By default Requests will perform location redirection for all verbs except458HEAD.459460We can use the ``history`` property of the Response object to track redirection.461462The :attr:`Response.history <requests.Response.history>` list contains the463:class:`Response <requests.Response>` objects that were created in order to464complete the request. The list is sorted from the oldest to the most recent465response.466467For example, GitHub redirects all HTTP requests to HTTPS::468469    >>> r = requests.get('http://github.com')470471    >>> r.url472    'https://github.com/'473474    >>> r.status_code475    200476477    >>> r.history478    [<Response [301]>]479480481If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable482redirection handling with the ``allow_redirects`` parameter::483484    >>> r = requests.get('http://github.com', allow_redirects=False)485486    >>> r.status_code487    301488489    >>> r.history490    []491492If you're using HEAD, you can enable redirection as well::493494    >>> r = requests.head('http://github.com', allow_redirects=True)495496    >>> r.url497    'https://github.com/'498499    >>> r.history500    [<Response [301]>]501502503Timeouts504--------505506You can tell Requests to stop waiting for a response after a given number of507seconds with the ``timeout`` parameter. Nearly all production code should use508this parameter in nearly all requests. Failure to do so can cause your program509to hang indefinitely::510511    >>> requests.get('http://github.com', timeout=0.001)512    Traceback (most recent call last):513      File "<stdin>", line 1, in <module>514    requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)515516517.. admonition:: Note518519    ``timeout`` is not a time limit on the entire response download;520    rather, an exception is raised if the server has not issued a521    response for ``timeout`` seconds (more precisely, if no bytes have been522    received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do523    not time out.524525526Errors and Exceptions527---------------------528529In the event of a network problem (e.g. DNS failure, refused connection, etc),530Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.531532:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will533raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request534returned an unsuccessful status code.535536If a request times out, a :exc:`~requests.exceptions.Timeout` exception is537raised.538539If a request exceeds the configured number of maximum redirections, a540:exc:`~requests.exceptions.TooManyRedirects` exception is raised.541542All exceptions that Requests explicitly raises inherit from543:exc:`requests.exceptions.RequestException`.544545-----------------------546547Ready for more? Check out the :ref:`advanced <advanced>` section.