quickstart.rst
This file
Path
docs/user/quickstart.rst
369 lines · 10.2 KiB
Last changed by
sp Kenneth Reitzbefore adoptionf7e4832
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>`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.4445When you make a request, ``r.encoding`` is set, based on the HTTP headers.46Requests will attempt to use that encoding when you access ``r.content``. You47can manually set ``r.encoding`` to any encoding you'd like (including ``None``),48and that charset will be used.495051Make a POST Request52-------------------5354POST requests are equally simple::5556 r = requests.post("http://httpbin.org/post")575859Typically, you want to send some form-encoded data — much like an HTML form.60To do this, simply pass a dictionary to the `data` argument. Your61dictionary of data will automatically be form-encoded when the request is made::6263 >>> payload = {'key1': 'value1', 'key2': 'value2'}64 >>> r = requests.post("http://httpbin.org/post", data=payload)65 >>> print r.content66 {67 "origin": "179.13.100.4",68 "files": {},69 "form": {70 "key2": "value2",71 "key1": "value1"72 },73 "url": "http://httpbin.org/post",74 "args": {},75 "headers": {76 "Content-Length": "23",77 "Accept-Encoding": "identity, deflate, compress, gzip",78 "Accept": "*/*",79 "User-Agent": "python-requests/0.8.0",80 "Host": "127.0.0.1:7077",81 "Content-Type": "application/x-www-form-urlencoded"82 },83 "data": ""84 }8586There 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.8788For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8990 url = 'https://api.github.com/some/endpoint'91 payload = {'some': 'data'}9293 r = requests.post(url, data=json.dumps(payload))949596Custom Headers97--------------9899If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the100``headers`` parameter.101102For example, we didn't specify our content-type in the previous example::103104 url = 'https://api.github.com/some/endpoint'105 payload = {'some': 'data'}106 headers = {'content-type': 'application/json'}107108 r = requests.post(url, data=json.dumps(payload), headers=headers)109110111POST a Multipart-Encoded File112-----------------------------113114Requests makes it simple to upload Multipart-encoded files::115116 >>> url = 'http://httpbin.org/post'117 >>> files = {'report.xls': open('report.xls', 'rb')}118119 >>> r = requests.post(url, files=files)120 >>> r.content121 {122 "origin": "179.13.100.4",123 "files": {124 "report.xls": "<censored...binary...data>"125 },126 "form": {},127 "url": "http://httpbin.org/post",128 "args": {},129 "headers": {130 "Content-Length": "3196",131 "Accept-Encoding": "identity, deflate, compress, gzip",132 "Accept": "*/*",133 "User-Agent": "python-requests/0.8.0",134 "Host": "httpbin.org:80",135 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"136 },137 "data": ""138 }139140Setting filename explicitly::141142 >>> url = 'http://httpbin.org/post'143 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}144145 >>> r = requests.post(url, files=files)146 >>> r.content147 {148 "origin": "179.13.100.4",149 "files": {150 "file": "<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 }165166167Response Status Codes168---------------------169170We can check the response status code::171172 >>> r.status_code173 200174175Requests also comes with a built-in status code lookup object for easy176reference::177178 >>> r.status_code == requests.codes.ok179 True180181If we made a bad request (non-200 response), we can raise it with182:class:`Response.raise_for_status()`::183184 >>> _r = requests.get('http://httpbin.org/status/404')185 >>> _r.status_code186 404187188 >>> _r.raise_for_status()189 Traceback (most recent call last):190 File "requests/models.py", line 394, in raise_for_status191 raise self.error192 urllib2.HTTPError: HTTP Error 404: NOT FOUND193194But, since our ``status_code`` was ``200``, when we call it::195196 >>> r.raise_for_status()197 None198199All is well.200201202Response Headers203----------------204205We can view the server's response headers with a simple Python dictionary206interface::207208 >>> r.headers209 {210 'status': '200 OK',211 'content-encoding': 'gzip',212 'transfer-encoding': 'chunked',213 'connection': 'close',214 'server': 'nginx/1.0.4',215 'x-runtime': '148ms',216 'etag': '"e1ca502697e5c9317743dc078f67693f"',217 'content-type': 'application/json; charset=utf-8'218 }219220The dictionary is special, though: it's made just for HTTP headers. According to221`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP222Headers are case-insensitive.223224So, we can access the headers using any capitalization we want::225226 >>> r.headers['Content-Type']227 'application/json; charset=utf-8'228229 >>> r.headers.get('content-type')230 'application/json; charset=utf-8'231232If a header doesn't exist in the Response, its value defaults to ``None``::233234 >>> r.headers['X-Random']235 None236237238Cookies239-------240241If a response contains some Cookies, you can get quick access to them::242243 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'244 >>> r = requests.get(url)245246 >>> print r.cookies247 {'requests-is': 'awesome'}248249To send your own cookies to the server, you can use the ``cookies``250parameter::251252 >>> url = 'http://httpbin.org/cookies'253 >>> cookies = dict(cookies_are='working')254255 >>> r = requests.get(url, cookies=cookies)256 >>> r.content257 '{"cookies": {"cookies_are": "working"}}'258259260Basic Authentication261--------------------262263Most web services require authentication. There many different types of264authentication, but the most common is HTTP Basic Auth.265266Making requests with Basic Auth is extremely simple::267268 >>> from requests.auth import HTTPBasicAuth269 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))270 <Response [200]>271272Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for273this authentication method::274275 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))276 <Response [200]>277278Providing the credentials as a tuple in this fashion is functionally equivalent279to the ``HTTPBasicAuth`` example above.280281282Digest Authentication283---------------------284285Another popular form of web service protection is Digest Authentication::286287 >>> from requests.auth import HTTPDigestAuth288 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'289 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))290 <Response [200]>291292293OAuth Authentication294--------------------295296Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for297establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.298299300Redirection and History301-----------------------302303Requests will automatically perform location redirection while using impodotent methods.304305GitHub redirects all HTTP requests to HTTPS. Let's see what happens::306307 >>> r = requests.get('http://github.com')308 >>> r.url309 'https://github.com/'310 >>> r.status_code311 200312 >>> r.history313 [<Response [301]>]314315The :class:`Response.history` list contains a list of the316:class:`Request` objects that were created in order to complete the request.317318If you're using GET, HEAD, or OPTIONS, you can disable redirection319handling with the ``disable_redirects`` parameter::320321 >>> r = requests.get('http://github.com')322 >>> r.status_code323 301324 >>> r.history325 []326327If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::328329 >>> r = requests.post('http://github.com', allow_redirects=True)330 >>> r.url331 'https://github.com/'332 >>> r.history333 [<Response [301]>]334335336Timeouts337--------338339You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::340341 >>> requests.get('http://github.com', timeout=0.001)342 Traceback (most recent call last):343 File "<stdin>", line 1, in <module>344 requests.exceptions.Timeout: Request timed out.345346.. admonition:: Note347348 ``timeout`` only effects the connection process itself, not the downloading of the response body.349350351Errors and Exceptions352---------------------353354In the event of a network problem (e.g. DNS failure, refused connection, etc),355Requests will raise a :class:`ConnectionError` exception.356357In the event of the rare invalid HTTP response, Requests will raise358an :class:`HTTPError` exception.359360If a request times out, a :class:`Timeout` exception is raised.361362If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.363364All exceptions that Requests explicitly raises inherit from365:class:`requests.exceptions.RequestException`.366367-----------------------368369Ready for more? Check out the :ref:`advanced <advanced>` section.