quickstart.rst
This file
Path
docs/user/quickstart.rst
254 lines · 6.5 KiB
Last changed by
file uploadsKenneth Reitzbefore adoption40c5480
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 unicode charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.434445Make a POST Request46-------------------4748POST requests are equally simple::4950 r = requests.post("http://httpbin.org/post")515253Typically, you want to send some form-encoded data — much like an HTML form.54To do this, simply pass a dictionary to the `data` argument. Your dictionary of data will automatically be form-encoded when the request is made::5556 >>> payload = {'key1': 'value1', 'key2': 'value2'}57 >>> r = requests.post("http://httpbin.org/post", data=payload)58 >>> print r.content59 {60 "origin": "179.13.100.4",61 "files": {},62 "form": {63 "key2": "value2",64 "key1": "value1"65 },66 "url": "http://httpbin.org/post",67 "args": {},68 "headers": {69 "Content-Length": "23",70 "Accept-Encoding": "identity, deflate, compress, gzip",71 "Accept": "*/*",72 "User-Agent": "python-requests/0.8.0",73 "Host": "127.0.0.1:7077",74 "Content-Type": "application/x-www-form-urlencoded"75 },76 "data": ""77 }7879There 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.8081For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8283 url = 'https://api.github.com/some/endpoint'84 payload = {'some': 'data'}8586 r = requests.post(url, data=json.dumps(payload))878889Custom Headers90--------------9192If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the93``headers`` parameter.9495For example, we didn't specify our content-type in the previous example::9697 url = 'https://api.github.com/some/endpoint'98 payload = {'some': 'data'}99 headers = {'content-type': 'application/json'}100101 r = requests.post(url, data=json.dumps(payload), headers=headers)102103104POST a Multipart-Encoded File105-----------------------------106107Requests makes it simple to upload Multipart-encoded files::108109 >>> url = 'http://httpbin.org/post'110 >>> files = {'report.xls': open('report.xls', 'rb')}111112 >>> r = requests.post(url, files=files)113 >>> r.content114 {115 "origin": "179.13.100.4",116 "files": {117 "hmm": "<censored...binary...data>"118 },119 "form": {},120 "url": "http://httpbin.org/post",121 "args": {},122 "headers": {123 "Content-Length": "3196",124 "Accept-Encoding": "identity, deflate, compress, gzip",125 "Accept": "*/*",126 "User-Agent": "python-requests/0.8.0",127 "Host": "httpbin.org:80",128 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"129 },130 "data": ""131 }132133134135136137Response Status Codes138---------------------139140We can check the response status code::141142 >>> r.status_code143 200144145Requests also comes with a built-in status code lookup object for easy146reference::147148 >>> r.status_code == requests.codes.ok149 True150151If we made a bad request (non-200 response), we can raise it with152:class:`Response.raise_for_status()`::153154 >>> _r = requests.get('http://httpbin.org/status/404')155 >>> _r.status_code156 404157158 >>> _r.raise_for_status()159 Traceback (most recent call last):160 File "requests/models.py", line 394, in raise_for_status161 raise self.error162 urllib2.HTTPError: HTTP Error 404: NOT FOUND163164But, since our ``status_code`` was ``200``, when we call it::165166 >>> r.raise_for_status()167 None168169All is well.170171172Response Headers173----------------174175We can view the server's response headers with a simple Python dictionary176interface::177178 >>> r.headers179 {180 'status': '200 OK',181 'content-encoding': 'gzip',182 'transfer-encoding': 'chunked',183 'connection': 'close',184 'server': 'nginx/1.0.4',185 'x-runtime': '148ms',186 'etag': '"e1ca502697e5c9317743dc078f67693f"',187 'content-type': 'application/json; charset=utf-8'188 }189190The dictionary is special, though: it's made just for HTTP headers. According to191`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP192Headers are case-insensitive.193194So, we can access the headers using any capitalization we want::195196 >>> r.headers['Content-Type']197 'application/json; charset=utf-8'198199 >>> r.headers.get('content-type')200 'application/json; charset=utf-8'201202If a header doesn't exist in the Response, its value defaults to ``None``::203204 >>> r.headers['X-Random']205 None206207208Cookies209-------210211If a response contains some Cookies, you can get quick access to them::212213 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'214 >>> r = requests.get(url)215216 >>> print r.cookies217 {'requests-is': 'awesome'}218219To send your own cookies to the server, you can use the ``cookies``220parameter::221222 >>> url = 'http://httpbin.org/cookies'223 >>> cookies = dict(cookies_are='working')224225 >>> r = requests.get(url, cookies=cookies)226 >>> r.content227 '{"cookies": {"cookies_are": "working"}}'228229230Basic Authentication231--------------------232233Most web services require authentication. There many different types of234authentication, but the most common is called HTTP Basic Auth.235236Making requests with Basic Auth is extremely simple::237238 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))239 <Response [200]>240241242Digest Authentication243---------------------244245Another popular form of protecting web service is Digest Authentication::246247 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'248 >>> requests.get(url, auth=('digest', 'user', 'pass'))249 <Response [200]>250251252-----------------------253254Ready for more? Check out the :ref:`advanced <advanced>` section.