Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

416 lines · 11.6 KiB

Last changed by

Merge pull request #1076 from sigmavirus24/masterKenneth Reitzbefore adoptionc03e893

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. This assumes you already have Requests installed. If you do not,10head over to the :ref:`Installation <install>` section.1112First, make sure that:1314* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`161718Let's get started with some simple examples.192021Make a Request22--------------2324Making a request with Requests is very simple.2526Begin by importing the Requests module::2728    >>> import requests2930Now, let's try to get a webpage. For this example, let's get GitHub's public31timeline ::3233    >>> r = requests.get('https://github.com/timeline.json')3435Now, we have a :class:`Response` object called ``r``. We can get all the36information we need from this object.3738Requests' simple API means that all forms of HTTP request are as obvious. For39example, this is how you make an HTTP POST request::4041    >>> r = requests.post("http://httpbin.org/post")4243Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44OPTIONS? These are all just as simple::4546    >>> r = requests.put("http://httpbin.org/put")47    >>> r = requests.delete("http://httpbin.org/delete")48    >>> r = requests.head("http://httpbin.org/get")49    >>> r = requests.options("http://httpbin.org/get")5051That's all well and good, but it's also only the start of what Requests can52do.535455Passing Parameters In URLs56--------------------------5758You often want to send some sort of data in the URL's query string. If59you were constructing the URL by hand, this data would be given as key/value60pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.61Requests allows you to provide these arguments as a dictionary, using the62``params`` keyword argument. As an example, if you wanted to pass63``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the64following code::6566    >>> payload = {'key1': 'value1', 'key2': 'value2'}67    >>> r = requests.get("http://httpbin.org/get", params=payload)6869You can see that the URL has been correctly encoded by printing the URL::7071    >>> print r.url72    u'http://httpbin.org/get?key2=value2&key1=value1'737475Response Content76----------------7778We can read the content of the server's response. Consider the GitHub timeline79again::8081    >>> import requests82    >>> r = requests.get('https://github.com/timeline.json')83    >>> r.text84    '[{"repository":{"open_issues":0,"url":"https://github.com/...8586Requests will automatically decode content from the server. Most unicode87charsets are seamlessly decoded.8889When you make a request, Requests makes educated guesses about the encoding of90the response based on the HTTP headers. The text encoding guessed by Requests91is used when you access ``r.text``. You can find out what encoding Requests is92using, and change it, using the ``r.encoding`` property::9394    >>> r.encoding95    'utf-8'96    >>> r.encoding = 'ISO-8859-1'9798If you change the encoding, Requests will use the new value of ``r.encoding``99whenever you call ``r.text``.100101Requests will also use custom encodings in the event that you need them. If102you have created your own encoding and registered it with the ``codecs``103module, you can simply use the codec name as the value of ``r.encoding`` and104Requests will handle the decoding for you.105106Binary Response Content107-----------------------108109You can also access the response body as bytes, for non-text requests::110111    >>> r.content112    b'[{"repository":{"open_issues":0,"url":"https://github.com/...113114The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.115116For example, to create an image from binary data returned by a request, you can117use the following code:118119    >>> from PIL import Image120    >>> from StringIO import StringIO121    >>> i = Image.open(StringIO(r.content))122123124JSON Response Content125---------------------126127There's also a builtin JSON decoder, in case you're dealing with JSON data::128129    >>> import requests130    >>> r = requests.get('https://github.com/timeline.json')131    >>> r.json()132    [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...133134In case the JSON decoding fails, ``r.json`` raises an exception.135136137Raw Response Content138--------------------139140In the rare case that you'd like to get the raw socket response from the141server, you can access ``r.raw``. If you want to do this, make sure you set142``stream=True`` in your initial request. Once you do, you can do this::143144    >>> r = requests.get('https:/github.com/timeline.json', stream=True)145    >>> r.raw146    <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>147    >>> r.raw.read(10)148    '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'149150151Custom Headers152--------------153154If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the155``headers`` parameter.156157For example, we didn't specify our content-type in the previous example::158159    >>> import json160    >>> url = 'https://api.github.com/some/endpoint'161    >>> payload = {'some': 'data'}162    >>> headers = {'content-type': 'application/json'}163164    >>> r = requests.post(url, data=json.dumps(payload), headers=headers)165166167More complicated POST requests168------------------------------169170Typically, you want to send some form-encoded data — much like an HTML form.171To do this, simply pass a dictionary to the `data` argument. Your172dictionary of data will automatically be form-encoded when the request is made::173174    >>> payload = {'key1': 'value1', 'key2': 'value2'}175    >>> r = requests.post("http://httpbin.org/post", data=payload)176    >>> print r.text177    {178      ...179      "form": {180        "key2": "value2",181        "key1": "value1"182      },183      ...184    }185186There are many times that you want to send data that is not form-encoded. If you pass in a ``string`` instead of a ``dict``, that data will be posted directly.187188For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::189190    >>> import json191    >>> url = 'https://api.github.com/some/endpoint'192    >>> payload = {'some': 'data'}193194    >>> r = requests.post(url, data=json.dumps(payload))195196197POST a Multipart-Encoded File198-----------------------------199200Requests makes it simple to upload Multipart-encoded files::201202    >>> url = 'http://httpbin.org/post'203    >>> files = {'file': open('report.xls', 'rb')}204205    >>> r = requests.post(url, files=files)206    >>> r.text207    {208      ...209      "files": {210        "file": "<censored...binary...data>"211      },212      ...213    }214215You can set the filename explicitly::216217    >>> url = 'http://httpbin.org/post'218    >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}219220    >>> r = requests.post(url, files=files)221    >>> r.text222    {223      ...224      "files": {225        "file": "<censored...binary...data>"226      },227      ...228    }229230If you want, you can send strings to be received as files::231232    >>> url = 'http://httpbin.org/post'233    >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}234235    >>> r = requests.post(url, files=files)236    >>> r.text237    {238      ...239      "files": {240        "file": "some,data,to,send\\nanother,row,to,send\\n"241      },242      ...243    }244245246Response Status Codes247---------------------248249We can check the response status code::250251    >>> r = requests.get('http://httpbin.org/get')252    >>> r.status_code253    200254255Requests also comes with a built-in status code lookup object for easy256reference::257258    >>> r.status_code == requests.codes.ok259    True260261If we made a bad request (non-200 response), we can raise it with262:class:`Response.raise_for_status()`::263264    >>> bad_r = requests.get('http://httpbin.org/status/404')265    >>> bad_r.status_code266    404267268    >>> bad_r.raise_for_status()269    Traceback (most recent call last):270      File "requests/models.py", line 832, in raise_for_status271        raise http_error272    requests.exceptions.HTTPError: 404 Client Error273274But, since our ``status_code`` for ``r`` was ``200``, when we call275``raise_for_status()`` we get::276277    >>> r.raise_for_status()278    None279280All is well.281282283Response Headers284----------------285286We can view the server's response headers using a Python dictionary::287288    >>> r.headers289    {290        'status': '200 OK',291        'content-encoding': 'gzip',292        'transfer-encoding': 'chunked',293        'connection': 'close',294        'server': 'nginx/1.0.4',295        'x-runtime': '148ms',296        'etag': '"e1ca502697e5c9317743dc078f67693f"',297        'content-type': 'application/json; charset=utf-8'298    }299300The dictionary is special, though: it's made just for HTTP headers. According to301`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP302Headers are case-insensitive.303304So, we can access the headers using any capitalization we want::305306    >>> r.headers['Content-Type']307    'application/json; charset=utf-8'308309    >>> r.headers.get('content-type')310    'application/json; charset=utf-8'311312If a header doesn't exist in the Response, its value defaults to ``None``::313314    >>> r.headers['X-Random']315    None316317318Cookies319-------320321If a response contains some Cookies, you can get quick access to them::322323    >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'324    >>> r = requests.get(url)325326    >>> r.cookies['requests-is']327    'awesome'328329To send your own cookies to the server, you can use the ``cookies``330parameter::331332    >>> url = 'http://httpbin.org/cookies'333    >>> cookies = dict(cookies_are='working')334335    >>> r = requests.get(url, cookies=cookies)336    >>> r.text337    '{"cookies": {"cookies_are": "working"}}'338339340Redirection and History341-----------------------342343Requests will automatically perform location redirection while using the GET344and OPTIONS verbs.345346GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method347of the Response object to track redirection. Let's see what Github does::348349    >>> r = requests.get('http://github.com')350    >>> r.url351    'https://github.com/'352    >>> r.status_code353    200354    >>> r.history355    [<Response [301]>]356357The :class:`Response.history` list contains a list of the358:class:`Request` objects that were created in order to complete the request. The list is sorted from the oldest to the most recent request.359360If you're using GET or OPTIONS, you can disable redirection handling with the361``allow_redirects`` parameter::362363    >>> r = requests.get('http://github.com', allow_redirects=False)364    >>> r.status_code365    301366    >>> r.history367    []368369If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable370redirection as well::371372    >>> r = requests.post('http://github.com', allow_redirects=True)373    >>> r.url374    'https://github.com/'375    >>> r.history376    [<Response [301]>]377378379Timeouts380--------381382You can tell requests to stop waiting for a response after a given number of383seconds with the ``timeout`` parameter::384385    >>> requests.get('http://github.com', timeout=0.001)386    Traceback (most recent call last):387      File "<stdin>", line 1, in <module>388    requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)389390391.. admonition:: Note:392393    ``timeout`` only effects the connection process itself, not the394    downloading of the response body.395396397Errors and Exceptions398---------------------399400In the event of a network problem (e.g. DNS failure, refused connection, etc),401Requests will raise a :class:`ConnectionError` exception.402403In the event of the rare invalid HTTP response, Requests will raise404an  :class:`HTTPError` exception.405406If a request times out, a :class:`Timeout` exception is raised.407408If a request exceeds the configured number of maximum redirections, a409:class:`TooManyRedirects` exception is raised.410411All exceptions that Requests explicitly raises inherit from412:class:`requests.exceptions.RequestException`.413414-----------------------415416Ready for more? Check out the :ref:`advanced <advanced>` section.