quickstart.rst
This file
Path
docs/user/quickstart.rst
373 lines · 10.5 KiB
Last changed by
Merge pull request #333 from bryanhelmig/developKenneth Reitzbefore adoption281e059
History of this fileTake it
Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 1why, one step back1.. _quickstart:Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 2why, one step back2Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 3–4why, one step back3Quickstart4==========Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 5why, one step back5Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 6why, one step back6.. module:: requests.modelsMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 7why, one step back7Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158
lines 8–10why, one step back8Eager 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.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 11why, one step back11Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 12why, one step back12First, make sure that:Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 13why, one step back13Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 14–15why, one step back14* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 16–17why, one step back1617Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 18why, one step back18Lets gets started with some simple use cases and examples.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 19–20why, one step back1920Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 21–22why, one step back21Make a GET Request22------------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 23why, one step back23Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 24why, one step back24Making a standard request with Requests is very simple.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 25why, one step back25Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 26why, one step back26Let's get GitHub's public timeline ::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 27why, one step back27Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 28why, one step back28 r = requests.get('https://github.com/timeline.json')Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 29why, one step back29Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158
lines 30–31why, one step back30Now, we have a :class:`Response` object called ``r``. We can get all the31information we need from this.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 32–33why, one step back3233Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 34–35why, one step back34Response Content35----------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 36why, one step back36Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 37why, one step back37We can read the content of the server's response::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 38why, one step back38Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 39–40why, one step back39 >>> r.content40 '[{"repository":{"open_issues":0,"url":"https://github.com/...Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 41why, one step back41Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
lines 42–43why, one step back42Requests does its best to decode content from the server. Most unicode43charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 44why, one step back44Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae
lines 45–48why, one step back45When 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.Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 49why, one step back49Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae
line 50why, one step back50Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 51–59why, one step back51Make 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.Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
lines 60–61why, one step back60To do this, simply pass a dictionary to the `data` argument. Your61dictionary of data will automatically be form-encoded when the request is made::Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 62–123why, one step back6263 >>> 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": {Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 124why, one step back124 "report.xls": "<censored...binary...data>"Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 125–139why, one step back125 },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 }139Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae
lines 140–164why, one step back140Setting 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 }Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 165–166why, one step back165166Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 167–168why, one step back167Response Status Codes168---------------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 169why, one step back169Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 170why, one step back170We can check the response status code::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 171why, one step back171Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 172–173why, one step back172 >>> r.status_code173 200Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 174why, one step back174Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 175–176why, one step back175Requests also comes with a built-in status code lookup object for easy176reference::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 177why, one step back177Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 178–179why, one step back178 >>> r.status_code == requests.codes.ok179 TrueMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 180why, one step back180Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 181why, one step back181If we made a bad request (non-200 response), we can raise it withMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 182why, one step back182:class:`Response.raise_for_status()`::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 183why, one step back183Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 184–186why, one step back184 >>> _r = requests.get('http://httpbin.org/status/404')185 >>> _r.status_code186 404Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 187why, one step back187Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 188–192why, one step back188 >>> _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 FOUNDMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 193why, one step back193Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 194why, one step back194But, since our ``status_code`` was ``200``, when we call it::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 195why, one step back195Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 196–197why, one step back196 >>> r.raise_for_status()197 NoneMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 198why, one step back198Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 199why, one step back199All is well.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 200–201why, one step back200201Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 202–203why, one step back202Response Headers203----------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 204why, one step back204Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 205–206why, one step back205We can view the server's response headers with a simple Python dictionary206interface::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 207why, one step back207Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 208–218why, one step back208 >>> 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 }Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 219why, one step back219Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158
lines 220–221why, one step back220The dictionary is special, though: it's made just for HTTP headers. According to221`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTPMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 222why, one step back222Headers are case-insensitive.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 223why, one step back223Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 224why, one step back224So, we can access the headers using any capitalization we want::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 225why, one step back225Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 226–257why, one step back226 >>> 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"}}'Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 258–263why, one step back258259260Basic Authentication261--------------------262263Most web services require authentication. There many different types ofMerge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 264why, one step back264authentication, but the most common is HTTP Basic Auth.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 265why, one step back265Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 266why, one step back266Making requests with Basic Auth is extremely simple::Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 267why, one step back267Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
lines 268–274why, one step back268 >>> 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::274Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 275–277why, one step back275 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))276 <Response [200]>277Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
lines 278–279why, one step back278Providing the credentials as a tuple in this fashion is functionally equivalent279to the ``HTTPBasicAuth`` example above.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 280why, one step back280Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 281why, one step back281Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 282–284why, one step back282Digest Authentication283---------------------284Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 285why, one step back285Another popular form of web service protection is Digest Authentication::Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 286why, one step back286Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
line 287why, one step back287 >>> from requests.auth import HTTPDigestAuthMerge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 288why, one step back288 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
line 289why, one step back289 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 290why, one step back290 <Response [200]>Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
lines 291–297why, one step back291292293OAuth 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>`_.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 298why, one step back298Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 299–302why, one step back299300Redirection and History301-----------------------302Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 303why, one step back303Requests will automatically perform location redirection while using idempotent methods.Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 304–306why, one step back304305GitHub redirects all HTTP requests to HTTPS. Let's see what happens::306Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 307why, one step back307 >>> r = requests.get('http://github.com')Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 308–318why, one step back308 >>> 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 redirectionMerge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 319why, one step back319handling with the ``allow_redirects`` parameter::Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 320why, one step back320Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 321why, one step back321 >>> r = requests.get('http://github.com', allow_redirects=False)Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 322–328why, one step back322 >>> r.status_code323 301324 >>> r.history325 []326327If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::328Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 329why, one step back329 >>> r = requests.post('http://github.com', allow_redirects=True)Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 330–347why, one step back330 >>> 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:: Note347Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 348why, one step back348 ``timeout`` only effects the connection process itself, not the downloading of the response body.Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 349–365why, one step back349350351Errors 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`.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 366why, one step back366Merge pull request #333 from bryanhelmig/developKenneth Reitzbefore adoption281e059
lines 367–370why, one step back367You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions368via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions369with the ``safe_mode`` option.370Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 371–372why, one step back371-----------------------372Merge branch 'develop'Kenneth Reitzbefore adoptiond0b96f8
line 373why, one step back373Ready for more? Check out the :ref:`advanced <advanced>` section.