Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

432 lines · 12.1 KiB

Last changed by

update documentation to correspond to new cookie APIShivaram Lingamnenibefore adoptionfdd0821

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>`161718Lets gets started with some simple use cases and examples.192021Make a GET Request22------------------2324Making a standard request with Requests is very simple.2526Let's get GitHub's public timeline ::2728    r = requests.get('https://github.com/timeline.json')2930Now, we have a :class:`Response` object called ``r``. We can get all the31information we need from this.3233Typically, you want to send some sort of data in the urls query string.34To do this, simply pass a dictionary to the `params` argument. Your35dictionary of data will automatically be encoded when the request is made::3637    >>> payload = {'key1': 'value1', 'key2': 'value2'}38    >>> r = requests.get("http://httpbin.org/get", params=payload)39    >>> print r.text40    {41      "origin": "179.13.100.4",42      "args": {43        "key2": "value2",44        "key1": "value1"45      },46      "url": "http://httpbin.org/get",47      "headers": {48        "Connections": "keep-alive",49        "Content-Length": "",50        "Accept-Encoding": "identity, deflate, compress, gzip",51        "Accept": "*/*",52        "User-Agent": "python-requests/0.11.0",53        "Host": httpbin.org",54        "Content-Type": ""55      },56    }57585960Response Content61----------------6263We can read the content of the server's response::6465    >>> r.text66    '[{"repository":{"open_issues":0,"url":"https://github.com/...6768Requests will automatically decode content from the server. Most unicode69charsets are seamlessly decoded.7071When you make a request, ``r.encoding`` is set, based on the HTTP headers.72Requests will use that encoding when you access ``r.text``.  If ``r.encoding``73is ``None``, Requests will make an extremely educated guess of the encoding74of the response body. You can manually set ``r.encoding`` to any encoding75you'd like, and that charset will be used.767778Binary Response Content79-----------------------8081You can also access the response body as bytes, for non-text requests::8283    >>> r.content84    b'[{"repository":{"open_issues":0,"url":"https://github.com/...8586The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.8788For example to create an image from binary data returned by a request, you can89use the following code:9091    >>> from PIL import Image92    >>> from StringIO import StringIO93    >>> i = Image.open(StringIO(r.content))949596Raw Response Content97--------------------9899In the rare case that you'd like to get the absolute raw socket response from the server,100you can access ``r.raw``::101102    >>> r.raw103    <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>104105    >>> r.raw.read(10)106    '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'107108109110Make a POST Request111-------------------112113POST requests are equally simple::114115    r = requests.post("http://httpbin.org/post")116117118Typically, you want to send some form-encoded data — much like an HTML form.119To do this, simply pass a dictionary to the `data` argument. Your120dictionary of data will automatically be form-encoded when the request is made::121122    >>> payload = {'key1': 'value1', 'key2': 'value2'}123    >>> r = requests.post("http://httpbin.org/post", data=payload)124    >>> print r.text125    {126      "origin": "179.13.100.4",127      "files": {},128      "form": {129        "key2": "value2",130        "key1": "value1"131      },132      "url": "http://httpbin.org/post",133      "args": {},134      "headers": {135        "Content-Length": "23",136        "Accept-Encoding": "identity, deflate, compress, gzip",137        "Accept": "*/*",138        "User-Agent": "python-requests/0.8.0",139        "Host": "127.0.0.1:7077",140        "Content-Type": "application/x-www-form-urlencoded"141      },142      "data": ""143    }144145There 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.146147For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::148149    url = 'https://api.github.com/some/endpoint'150    payload = {'some': 'data'}151152    r = requests.post(url, data=json.dumps(payload))153154155Custom Headers156--------------157158If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the159``headers`` parameter.160161For example, we didn't specify our content-type in the previous example::162163    url = 'https://api.github.com/some/endpoint'164    payload = {'some': 'data'}165    headers = {'content-type': 'application/json'}166167    r = requests.post(url, data=json.dumps(payload), headers=headers)168169170POST a Multipart-Encoded File171-----------------------------172173Requests makes it simple to upload Multipart-encoded files::174175    >>> url = 'http://httpbin.org/post'176    >>> files = {'report.xls': open('report.xls', 'rb')}177178    >>> r = requests.post(url, files=files)179    >>> r.text180    {181      "origin": "179.13.100.4",182      "files": {183        "report.xls": "<censored...binary...data>"184      },185      "form": {},186      "url": "http://httpbin.org/post",187      "args": {},188      "headers": {189        "Content-Length": "3196",190        "Accept-Encoding": "identity, deflate, compress, gzip",191        "Accept": "*/*",192        "User-Agent": "python-requests/0.8.0",193        "Host": "httpbin.org:80",194        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"195      },196      "data": ""197    }198199Setting filename explicitly::200201    >>> url = 'http://httpbin.org/post'202    >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}203204    >>> r = requests.post(url, files=files)205    >>> r.text206    {207      "origin": "179.13.100.4",208      "files": {209        "file": "<censored...binary...data>"210      },211      "form": {},212      "url": "http://httpbin.org/post",213      "args": {},214      "headers": {215        "Content-Length": "3196",216        "Accept-Encoding": "identity, deflate, compress, gzip",217        "Accept": "*/*",218        "User-Agent": "python-requests/0.8.0",219        "Host": "httpbin.org:80",220        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"221      },222      "data": ""223    }224225226Response Status Codes227---------------------228229We can check the response status code::230231    >>> r.status_code232    200233234Requests also comes with a built-in status code lookup object for easy235reference::236237    >>> r.status_code == requests.codes.ok238    True239240If we made a bad request (non-200 response), we can raise it with241:class:`Response.raise_for_status()`::242243    >>> _r = requests.get('http://httpbin.org/status/404')244    >>> _r.status_code245    404246247    >>> _r.raise_for_status()248    Traceback (most recent call last):249      File "requests/models.py", line 394, in raise_for_status250        raise self.error251    urllib2.HTTPError: HTTP Error 404: NOT FOUND252253But, since our ``status_code`` was ``200``, when we call it::254255    >>> r.raise_for_status()256    None257258All is well.259260261Response Headers262----------------263264We can view the server's response headers with a simple Python dictionary265interface::266267    >>> r.headers268    {269        'status': '200 OK',270        'content-encoding': 'gzip',271        'transfer-encoding': 'chunked',272        'connection': 'close',273        'server': 'nginx/1.0.4',274        'x-runtime': '148ms',275        'etag': '"e1ca502697e5c9317743dc078f67693f"',276        'content-type': 'application/json; charset=utf-8'277    }278279The dictionary is special, though: it's made just for HTTP headers. According to280`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP281Headers are case-insensitive.282283So, we can access the headers using any capitalization we want::284285    >>> r.headers['Content-Type']286    'application/json; charset=utf-8'287288    >>> r.headers.get('content-type')289    'application/json; charset=utf-8'290291If a header doesn't exist in the Response, its value defaults to ``None``::292293    >>> r.headers['X-Random']294    None295296297Cookies298-------299300If a response contains some Cookies, you can get quick access to them::301302    >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'303    >>> r = requests.get(url)304305    >>> r.cookies['requests-is']306    'awesome'307308To send your own cookies to the server, you can use the ``cookies``309parameter::310311    >>> url = 'http://httpbin.org/cookies'312    >>> cookies = dict(cookies_are='working')313314    >>> r = requests.get(url, cookies=cookies)315    >>> r.text316    '{"cookies": {"cookies_are": "working"}}'317318319Basic Authentication320--------------------321322Most web services require authentication. There many different types of323authentication, but the most common is HTTP Basic Auth.324325Making requests with Basic Auth is extremely simple::326327    >>> from requests.auth import HTTPBasicAuth328    >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))329    <Response [200]>330331Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for332this authentication method::333334    >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))335    <Response [200]>336337Providing the credentials as a tuple in this fashion is functionally equivalent338to the ``HTTPBasicAuth`` example above.339340341Digest Authentication342---------------------343344Another popular form of web service protection is Digest Authentication::345346    >>> from requests.auth import HTTPDigestAuth347    >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'348    >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))349    <Response [200]>350351352OAuth Authentication353--------------------354355Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for356establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.357358359Redirection and History360-----------------------361362Requests will automatically perform location redirection while using idempotent methods.363364GitHub redirects all HTTP requests to HTTPS. Let's see what happens::365366    >>> r = requests.get('http://github.com')367    >>> r.url368    'https://github.com/'369    >>> r.status_code370    200371    >>> r.history372    [<Response [301]>]373374The :class:`Response.history` list contains a list of the375:class:`Request` objects that were created in order to complete the request.376377If you're using GET, HEAD, or OPTIONS, you can disable redirection378handling with the ``allow_redirects`` parameter::379380    >>> r = requests.get('http://github.com', allow_redirects=False)381    >>> r.status_code382    301383    >>> r.history384    []385386If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::387388    >>> r = requests.post('http://github.com', allow_redirects=True)389    >>> r.url390    'https://github.com/'391    >>> r.history392    [<Response [301]>]393394395Timeouts396--------397398You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::399400    >>> requests.get('http://github.com', timeout=0.001)401    Traceback (most recent call last):402      File "<stdin>", line 1, in <module>403    requests.exceptions.Timeout: Request timed out.404405.. admonition:: Note406407    ``timeout`` only effects the connection process itself, not the downloading of the response body.408409410Errors and Exceptions411---------------------412413In the event of a network problem (e.g. DNS failure, refused connection, etc),414Requests will raise a :class:`ConnectionError` exception.415416In the event of the rare invalid HTTP response, Requests will raise417an  :class:`HTTPError` exception.418419If a request times out, a :class:`Timeout` exception is raised.420421If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.422423All exceptions that Requests explicitly raises inherit from424:class:`requests.exceptions.RequestException`.425426You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions427via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions428with the ``safe_mode`` option.429430-----------------------431432Ready for more? Check out the :ref:`advanced <advanced>` section.