Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

351 lines · 9.5 KiB

Last changed by

Merge pull request #280 from darkrho/58e018af136190a2c757b13bf9371cecc2d51273Kenneth Reitzbefore adoption2a72235

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.content40    '[{"repository":{"open_issues":0,"url":"https://github.com/...4142Requests does its best to decode content from the server. Most unicode43charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.444546Make a POST Request47-------------------4849POST requests are equally simple::5051    r = requests.post("http://httpbin.org/post")525354Typically, you want to send some form-encoded data — much like an HTML form.55To do this, simply pass a dictionary to the `data` argument. Your56dictionary of data will automatically be form-encoded when the request is made::5758    >>> payload = {'key1': 'value1', 'key2': 'value2'}59    >>> r = requests.post("http://httpbin.org/post", data=payload)60    >>> print r.content61    {62      "origin": "179.13.100.4",63      "files": {},64      "form": {65        "key2": "value2",66        "key1": "value1"67      },68      "url": "http://httpbin.org/post",69      "args": {},70      "headers": {71        "Content-Length": "23",72        "Accept-Encoding": "identity, deflate, compress, gzip",73        "Accept": "*/*",74        "User-Agent": "python-requests/0.8.0",75        "Host": "127.0.0.1:7077",76        "Content-Type": "application/x-www-form-urlencoded"77      },78      "data": ""79    }8081There 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.8283For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8485    url = 'https://api.github.com/some/endpoint'86    payload = {'some': 'data'}8788    r = requests.post(url, data=json.dumps(payload))899091Custom Headers92--------------9394If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the95``headers`` parameter.9697For example, we didn't specify our content-type in the previous example::9899    url = 'https://api.github.com/some/endpoint'100    payload = {'some': 'data'}101    headers = {'content-type': 'application/json'}102103    r = requests.post(url, data=json.dumps(payload), headers=headers)104105106POST a Multipart-Encoded File107-----------------------------108109Requests makes it simple to upload Multipart-encoded files::110111    >>> url = 'http://httpbin.org/post'112    >>> files = {'report.xls': open('report.xls', 'rb')}113114    >>> r = requests.post(url, files=files)115    >>> r.content116    {117      "origin": "179.13.100.4",118      "files": {119        "report.xls": "<censored...binary...data>"120      },121      "form": {},122      "url": "http://httpbin.org/post",123      "args": {},124      "headers": {125        "Content-Length": "3196",126        "Accept-Encoding": "identity, deflate, compress, gzip",127        "Accept": "*/*",128        "User-Agent": "python-requests/0.8.0",129        "Host": "httpbin.org:80",130        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"131      },132      "data": ""133    }134135Setting filename explicitly::136137    >>> url = 'http://httpbin.org/post'138    >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}139140    >>> r = requests.post(url, files=files)141    >>> r.content142    {143      "origin": "179.13.100.4",144      "files": {145        "file": "<censored...binary...data>"146      },147      "form": {},148      "url": "http://httpbin.org/post",149      "args": {},150      "headers": {151        "Content-Length": "3196",152        "Accept-Encoding": "identity, deflate, compress, gzip",153        "Accept": "*/*",154        "User-Agent": "python-requests/0.8.0",155        "Host": "httpbin.org:80",156        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"157      },158      "data": ""159    }160161162Response Status Codes163---------------------164165We can check the response status code::166167    >>> r.status_code168    200169170Requests also comes with a built-in status code lookup object for easy171reference::172173    >>> r.status_code == requests.codes.ok174    True175176If we made a bad request (non-200 response), we can raise it with177:class:`Response.raise_for_status()`::178179    >>> _r = requests.get('http://httpbin.org/status/404')180    >>> _r.status_code181    404182183    >>> _r.raise_for_status()184    Traceback (most recent call last):185      File "requests/models.py", line 394, in raise_for_status186        raise self.error187    urllib2.HTTPError: HTTP Error 404: NOT FOUND188189But, since our ``status_code`` was ``200``, when we call it::190191    >>> r.raise_for_status()192    None193194All is well.195196197Response Headers198----------------199200We can view the server's response headers with a simple Python dictionary201interface::202203    >>> r.headers204    {205        'status': '200 OK',206        'content-encoding': 'gzip',207        'transfer-encoding': 'chunked',208        'connection': 'close',209        'server': 'nginx/1.0.4',210        'x-runtime': '148ms',211        'etag': '"e1ca502697e5c9317743dc078f67693f"',212        'content-type': 'application/json; charset=utf-8'213    }214215The dictionary is special, though: it's made just for HTTP headers. According to216`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP217Headers are case-insensitive.218219So, we can access the headers using any capitalization we want::220221    >>> r.headers['Content-Type']222    'application/json; charset=utf-8'223224    >>> r.headers.get('content-type')225    'application/json; charset=utf-8'226227If a header doesn't exist in the Response, its value defaults to ``None``::228229    >>> r.headers['X-Random']230    None231232233Cookies234-------235236If a response contains some Cookies, you can get quick access to them::237238    >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'239    >>> r = requests.get(url)240241    >>> print r.cookies242    {'requests-is': 'awesome'}243244To send your own cookies to the server, you can use the ``cookies``245parameter::246247    >>> url = 'http://httpbin.org/cookies'248    >>> cookies = dict(cookies_are='working')249250    >>> r = requests.get(url, cookies=cookies)251    >>> r.content252    '{"cookies": {"cookies_are": "working"}}'253254255Basic Authentication256--------------------257258Most web services require authentication. There many different types of259authentication, but the most common is HTTP Basic Auth.260261Making requests with Basic Auth is extremely simple::262263    >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))264    <Response [200]>265266OAuth Authentication267--------------------268269Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for270establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.271272Digest Authentication273---------------------274275Another popular form of web service protection is Digest Authentication::276277    >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'278    >>> requests.get(url, auth=('digest', 'user', 'pass'))279    <Response [200]>280281282Redirection and History283-----------------------284285Requests will automatically perform location redirection while using impodotent methods.286287GitHub redirects all HTTP requests to HTTPS. Let's see what happens::288289    >>> r = requests.get('http://github.com')290    >>> r.url291    'https://github.com/'292    >>> r.status_code293    200294    >>> r.history295    [<Response [301]>]296297The :class:`Response.history` list contains a list of the298:class:`Request` objects that were created in order to complete the request.299300If you're using GET, HEAD, or OPTIONS, you can disable redirection301handling with the ``disable_redirects`` parameter::302303    >>> r = requests.get('http://github.com')304    >>> r.status_code305    301306    >>> r.history307    []308309If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::310311    >>> r = requests.post('http://github.com', allow_redirects=True)312    >>> r.url313    'https://github.com/'314    >>> r.history315    [<Response [301]>]316317318Timeouts319--------320321You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::322323    >>> requests.get('http://github.com', timeout=0.001)324    Traceback (most recent call last):325      File "<stdin>", line 1, in <module>326    requests.exceptions.Timeout: Request timed out.327328.. admonition:: Note329330    ``timeout`` only effects the connection process itself, not the downloading of the respone body.331332333Errors and Exceptions334---------------------335336In the event of a network problem (e.g. DNS failure, refused connection, etc),337Requests will raise a :class:`ConnectionError` exception.338339In the event of the rare invalid HTTP response, Requests will raise340an  :class:`HTTPError` exception.341342If a request times out, a :class:`Timeout` exception is raised.343344If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.345346All exceptions that Requests explicitly raises inherit from347:class:`requests.exceptions.RequestException`.348349-----------------------350351Ready for more? Check out the :ref:`advanced <advanced>` section.