quickstart.rst
This file
Path
docs/user/quickstart.rst
462 lines · 13.1 KiB
Last changed by
Merge pull request #784 from Locker537/docs_fixKenneth Reitzbefore adoptioncb0fdd8
History of this fileTake 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.json132 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...133134In case the JSON decoding fails, ``r.json`` simply returns ``None``.135136137Raw Response Content138--------------------139140In the rare case that you'd like to get the absolute raw socket response from the server,141you can access ``r.raw``::142143 >>> r.raw144 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>145146 >>> r.raw.read(10)147 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'148149150Custom Headers151--------------152153If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the154``headers`` parameter.155156For example, we didn't specify our content-type in the previous example::157158 >>> import json159 >>> url = 'https://api.github.com/some/endpoint'160 >>> payload = {'some': 'data'}161 >>> headers = {'content-type': 'application/json'}162163 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)164165166More complicated POST requests167------------------------------168169Typically, you want to send some form-encoded data — much like an HTML form.170To do this, simply pass a dictionary to the `data` argument. Your171dictionary of data will automatically be form-encoded when the request is made::172173 >>> payload = {'key1': 'value1', 'key2': 'value2'}174 >>> r = requests.post("http://httpbin.org/post", data=payload)175 >>> print r.text176 {177 // ...snip... //178 "form": {179 "key2": "value2",180 "key1": "value1"181 },182 // ...snip... //183 }184185There 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.186187For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::188189 >>> import json190 >>> url = 'https://api.github.com/some/endpoint'191 >>> payload = {'some': 'data'}192193 >>> r = requests.post(url, data=json.dumps(payload))194195196POST a Multipart-Encoded File197-----------------------------198199Requests makes it simple to upload Multipart-encoded files::200201 >>> url = 'http://httpbin.org/post'202 >>> files = {'file': open('report.xls', 'rb')}203204 >>> r = requests.post(url, files=files)205 >>> r.text206 {207 // ...snip... //208 "files": {209 "file": "<censored...binary...data>"210 },211 // ...snip... //212 }213214You can set the filename explicitly::215216 >>> url = 'http://httpbin.org/post'217 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}218219 >>> r = requests.post(url, files=files)220 >>> r.text221 {222 // ...snip... //223 "files": {224 "file": "<censored...binary...data>"225 },226 // ...snip... //227 }228229If you want, you can send strings to be received as files::230231 >>> url = 'http://httpbin.org/post'232 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}233234 >>> r = requests.post(url, files=files)235 >>> r.text236 {237 // ...snip... //238 "files": {239 "file": "some,data,to,send\\nanother,row,to,send\\n"240 },241 // ...snip... //242 }243244245Response Status Codes246---------------------247248We can check the response status code::249250 >>> r = requests.get('http://httpbin.org/get')251 >>> r.status_code252 200253254Requests also comes with a built-in status code lookup object for easy255reference::256257 >>> r.status_code == requests.codes.ok258 True259260If we made a bad request (non-200 response), we can raise it with261:class:`Response.raise_for_status()`::262263 >>> bad_r = requests.get('http://httpbin.org/status/404')264 >>> bad_r.status_code265 404266267 >>> bad_r.raise_for_status()268 Traceback (most recent call last):269 File "requests/models.py", line 832, in raise_for_status270 raise http_error271 requests.exceptions.HTTPError: 404 Client Error272273But, since our ``status_code`` for ``r`` was ``200``, when we call274``raise_for_status()`` we get::275276 >>> r.raise_for_status()277 None278279All is well.280281282Response Headers283----------------284285We can view the server's response headers using a Python dictionary::286287 >>> r.headers288 {289 'status': '200 OK',290 'content-encoding': 'gzip',291 'transfer-encoding': 'chunked',292 'connection': 'close',293 'server': 'nginx/1.0.4',294 'x-runtime': '148ms',295 'etag': '"e1ca502697e5c9317743dc078f67693f"',296 'content-type': 'application/json; charset=utf-8'297 }298299The dictionary is special, though: it's made just for HTTP headers. According to300`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP301Headers are case-insensitive.302303So, we can access the headers using any capitalization we want::304305 >>> r.headers['Content-Type']306 'application/json; charset=utf-8'307308 >>> r.headers.get('content-type')309 'application/json; charset=utf-8'310311If a header doesn't exist in the Response, its value defaults to ``None``::312313 >>> r.headers['X-Random']314 None315316317Cookies318-------319320If a response contains some Cookies, you can get quick access to them::321322 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'323 >>> r = requests.get(url)324325 >>> r.cookies['requests-is']326 'awesome'327328To send your own cookies to the server, you can use the ``cookies``329parameter::330331 >>> url = 'http://httpbin.org/cookies'332 >>> cookies = dict(cookies_are='working')333334 >>> r = requests.get(url, cookies=cookies)335 >>> r.text336 '{"cookies": {"cookies_are": "working"}}'337338339Basic Authentication340--------------------341342Many web services require authentication. There are many different types of343authentication, but the most common is HTTP Basic Auth.344345Making requests with Basic Auth is extremely simple::346347 >>> from requests.auth import HTTPBasicAuth348 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))349 <Response [200]>350351Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for352this authentication method::353354 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))355 <Response [200]>356357Providing the credentials as a tuple in this fashion is functionally equivalent358to the ``HTTPBasicAuth`` example above.359360361Digest Authentication362---------------------363364Another popular form of web service protection is Digest Authentication::365366 >>> from requests.auth import HTTPDigestAuth367 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'368 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))369 <Response [200]>370371372OAuth Authentication373--------------------374375Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_376project provides a simple interface for establishing OAuth connections.377Documentation and examples can be found on the requests-oauth378`git repository <https://github.com/maraujop/requests-oauth>`_.379380381Redirection and History382-----------------------383384Requests will automatically perform location redirection while using the GET385and OPTIONS verbs.386387GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method388of the Response object to track redirection. Let's see what Github does::389390 >>> r = requests.get('http://github.com')391 >>> r.url392 'https://github.com/'393 >>> r.status_code394 200395 >>> r.history396 [<Response [301]>]397398The :class:`Response.history` list contains a list of the399:class:`Request` objects that were created in order to complete the request. The list is sorted from the oldest to the most recent request.400401If you're using GET or OPTIONS, you can disable redirection handling with the402``allow_redirects`` parameter::403404 >>> r = requests.get('http://github.com', allow_redirects=False)405 >>> r.status_code406 301407 >>> r.history408 []409410If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable411redirection as well::412413 >>> r = requests.post('http://github.com', allow_redirects=True)414 >>> r.url415 'https://github.com/'416 >>> r.history417 [<Response [301]>]418419420Timeouts421--------422423You can tell requests to stop waiting for a response after a given number of424seconds with the ``timeout`` parameter::425426 >>> requests.get('http://github.com', timeout=0.001)427 Traceback (most recent call last):428 File "<stdin>", line 1, in <module>429 requests.exceptions.Timeout: Request timed out.430431.. admonition:: Note:432433 ``timeout`` only effects the connection process itself, not the434 downloading of the response body.435436437Errors and Exceptions438---------------------439440In the event of a network problem (e.g. DNS failure, refused connection, etc),441Requests will raise a :class:`ConnectionError` exception.442443In the event of the rare invalid HTTP response, Requests will raise444an :class:`HTTPError` exception.445446If a request times out, a :class:`Timeout` exception is raised.447448If a request exceeds the configured number of maximum redirections, a449:class:`TooManyRedirects` exception is raised.450451All exceptions that Requests explicitly raises inherit from452:class:`requests.exceptions.RequestException`.453454You can refer to :ref:`Configuration API Docs <configurations>` for immediate455raising of :class:`HTTPError` exceptions via the ``danger_mode`` option or456have Requests catch the majority of457:class:`requests.exceptions.RequestException` exceptions with the ``safe_mode``458option.459460-----------------------461462Ready for more? Check out the :ref:`advanced <advanced>` section.