Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

399 lines · 11.1 KiB

Last changed by

r.textKenneth Reitzbefore adoption1bc377b

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.323334Response Content35----------------3637We can read the content of the server's response::3839    >>> r.text40    '[{"repository":{"open_issues":0,"url":"https://github.com/...4142Requests will automatically decode content from the server. Most unicode43charsets are seamlessly decoded.4445When you make a request, ``r.encoding`` is set, based on the HTTP headers.46Requests will use that encoding when you access ``r.text``.  If ``r.encoding``47is ``None``, Requests will make an extremely educated guess of the encoding48of the response body. You can manually set ``r.encoding`` to any encoding49you'd like, and that charset will be used.505152Binary Response Content53-----------------------5455You can also access the response body as bytes, for non-text requests::5657    >>> r.content58    b'[{"repository":{"open_issues":0,"url":"https://github.com/...5960The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.616263Raw Response Content64--------------------6566In the rare case that you'd like to get the absolute raw socket response from the server,67you can access ``r.raw``::6869    >>> r.raw70    <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>7172    >>> r.raw.read(10)73    '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'74757677Make a POST Request78-------------------7980POST requests are equally simple::8182    r = requests.post("http://httpbin.org/post")838485Typically, you want to send some form-encoded data — much like an HTML form.86To do this, simply pass a dictionary to the `data` argument. Your87dictionary of data will automatically be form-encoded when the request is made::8889    >>> payload = {'key1': 'value1', 'key2': 'value2'}90    >>> r = requests.post("http://httpbin.org/post", data=payload)91    >>> print r.text92    {93      "origin": "179.13.100.4",94      "files": {},95      "form": {96        "key2": "value2",97        "key1": "value1"98      },99      "url": "http://httpbin.org/post",100      "args": {},101      "headers": {102        "Content-Length": "23",103        "Accept-Encoding": "identity, deflate, compress, gzip",104        "Accept": "*/*",105        "User-Agent": "python-requests/0.8.0",106        "Host": "127.0.0.1:7077",107        "Content-Type": "application/x-www-form-urlencoded"108      },109      "data": ""110    }111112There 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.113114For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::115116    url = 'https://api.github.com/some/endpoint'117    payload = {'some': 'data'}118119    r = requests.post(url, data=json.dumps(payload))120121122Custom Headers123--------------124125If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the126``headers`` parameter.127128For example, we didn't specify our content-type in the previous example::129130    url = 'https://api.github.com/some/endpoint'131    payload = {'some': 'data'}132    headers = {'content-type': 'application/json'}133134    r = requests.post(url, data=json.dumps(payload), headers=headers)135136137POST a Multipart-Encoded File138-----------------------------139140Requests makes it simple to upload Multipart-encoded files::141142    >>> url = 'http://httpbin.org/post'143    >>> files = {'report.xls': open('report.xls', 'rb')}144145    >>> r = requests.post(url, files=files)146    >>> r.text147    {148      "origin": "179.13.100.4",149      "files": {150        "report.xls": "<censored...binary...data>"151      },152      "form": {},153      "url": "http://httpbin.org/post",154      "args": {},155      "headers": {156        "Content-Length": "3196",157        "Accept-Encoding": "identity, deflate, compress, gzip",158        "Accept": "*/*",159        "User-Agent": "python-requests/0.8.0",160        "Host": "httpbin.org:80",161        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"162      },163      "data": ""164    }165166Setting filename explicitly::167168    >>> url = 'http://httpbin.org/post'169    >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}170171    >>> r = requests.post(url, files=files)172    >>> r.text173    {174      "origin": "179.13.100.4",175      "files": {176        "file": "<censored...binary...data>"177      },178      "form": {},179      "url": "http://httpbin.org/post",180      "args": {},181      "headers": {182        "Content-Length": "3196",183        "Accept-Encoding": "identity, deflate, compress, gzip",184        "Accept": "*/*",185        "User-Agent": "python-requests/0.8.0",186        "Host": "httpbin.org:80",187        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"188      },189      "data": ""190    }191192193Response Status Codes194---------------------195196We can check the response status code::197198    >>> r.status_code199    200200201Requests also comes with a built-in status code lookup object for easy202reference::203204    >>> r.status_code == requests.codes.ok205    True206207If we made a bad request (non-200 response), we can raise it with208:class:`Response.raise_for_status()`::209210    >>> _r = requests.get('http://httpbin.org/status/404')211    >>> _r.status_code212    404213214    >>> _r.raise_for_status()215    Traceback (most recent call last):216      File "requests/models.py", line 394, in raise_for_status217        raise self.error218    urllib2.HTTPError: HTTP Error 404: NOT FOUND219220But, since our ``status_code`` was ``200``, when we call it::221222    >>> r.raise_for_status()223    None224225All is well.226227228Response Headers229----------------230231We can view the server's response headers with a simple Python dictionary232interface::233234    >>> r.headers235    {236        'status': '200 OK',237        'content-encoding': 'gzip',238        'transfer-encoding': 'chunked',239        'connection': 'close',240        'server': 'nginx/1.0.4',241        'x-runtime': '148ms',242        'etag': '"e1ca502697e5c9317743dc078f67693f"',243        'content-type': 'application/json; charset=utf-8'244    }245246The dictionary is special, though: it's made just for HTTP headers. According to247`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP248Headers are case-insensitive.249250So, we can access the headers using any capitalization we want::251252    >>> r.headers['Content-Type']253    'application/json; charset=utf-8'254255    >>> r.headers.get('content-type')256    'application/json; charset=utf-8'257258If a header doesn't exist in the Response, its value defaults to ``None``::259260    >>> r.headers['X-Random']261    None262263264Cookies265-------266267If a response contains some Cookies, you can get quick access to them::268269    >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'270    >>> r = requests.get(url)271272    >>> print r.cookies273    {'requests-is': 'awesome'}274275To send your own cookies to the server, you can use the ``cookies``276parameter::277278    >>> url = 'http://httpbin.org/cookies'279    >>> cookies = dict(cookies_are='working')280281    >>> r = requests.get(url, cookies=cookies)282    >>> r.text283    '{"cookies": {"cookies_are": "working"}}'284285286Basic Authentication287--------------------288289Most web services require authentication. There many different types of290authentication, but the most common is HTTP Basic Auth.291292Making requests with Basic Auth is extremely simple::293294    >>> from requests.auth import HTTPBasicAuth295    >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))296    <Response [200]>297298Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for299this authentication method::300301    >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))302    <Response [200]>303304Providing the credentials as a tuple in this fashion is functionally equivalent305to the ``HTTPBasicAuth`` example above.306307308Digest Authentication309---------------------310311Another popular form of web service protection is Digest Authentication::312313    >>> from requests.auth import HTTPDigestAuth314    >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'315    >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))316    <Response [200]>317318319OAuth Authentication320--------------------321322Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for323establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.324325326Redirection and History327-----------------------328329Requests will automatically perform location redirection while using idempotent methods.330331GitHub redirects all HTTP requests to HTTPS. Let's see what happens::332333    >>> r = requests.get('http://github.com')334    >>> r.url335    'https://github.com/'336    >>> r.status_code337    200338    >>> r.history339    [<Response [301]>]340341The :class:`Response.history` list contains a list of the342:class:`Request` objects that were created in order to complete the request.343344If you're using GET, HEAD, or OPTIONS, you can disable redirection345handling with the ``allow_redirects`` parameter::346347    >>> r = requests.get('http://github.com', allow_redirects=False)348    >>> r.status_code349    301350    >>> r.history351    []352353If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::354355    >>> r = requests.post('http://github.com', allow_redirects=True)356    >>> r.url357    'https://github.com/'358    >>> r.history359    [<Response [301]>]360361362Timeouts363--------364365You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::366367    >>> requests.get('http://github.com', timeout=0.001)368    Traceback (most recent call last):369      File "<stdin>", line 1, in <module>370    requests.exceptions.Timeout: Request timed out.371372.. admonition:: Note373374    ``timeout`` only effects the connection process itself, not the downloading of the response body.375376377Errors and Exceptions378---------------------379380In the event of a network problem (e.g. DNS failure, refused connection, etc),381Requests will raise a :class:`ConnectionError` exception.382383In the event of the rare invalid HTTP response, Requests will raise384an  :class:`HTTPError` exception.385386If a request times out, a :class:`Timeout` exception is raised.387388If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.389390All exceptions that Requests explicitly raises inherit from391:class:`requests.exceptions.RequestException`.392393You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions394via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions395with the ``safe_mode`` option.396397-----------------------398399Ready for more? Check out the :ref:`advanced <advanced>` section.