quickstart.rst
This file
Path
docs/user/quickstart.rst
573 lines · 18.8 KiB
Last changed by
docs: clarify Quickstart POST example (#6960)Ethan Pricebefore adoptiond568f47
History of this fileTake it
The walk stopped after 200 commits: lines older than 8812812 point at it.
Merge pull request #6519 from psf/dependabot/github_actions/actions/checkout-4.0.0Ian Stapleton Cordascobefore adoption8812812
lines 1–203why, one step back1.. _quickstart:23Quickstart4==========56.. module:: requests.models78Eager to get started? This page gives a good introduction in how to get started9with Requests.1011First, make sure that:1213* Requests is :ref:`installed <install>`14* Requests is :ref:`up-to-date <updates>`151617Let's get started with some simple examples.181920Make a Request21--------------2223Making a request with Requests is very simple.2425Begin by importing the Requests module::2627 >>> import requests2829Now, let's try to get a webpage. For this example, let's get GitHub's public30timeline::3132 >>> r = requests.get('https://api.github.com/events')3334Now, we have a :class:`Response <requests.Response>` object called ``r``. We can35get all the information we need from this object.3637Requests' simple API means that all forms of HTTP request are as obvious. For38example, this is how you make an HTTP POST request::3940 >>> r = requests.post('https://httpbin.org/post', data={'key': 'value'})4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::4445 >>> r = requests.put('https://httpbin.org/put', data={'key': 'value'})46 >>> r = requests.delete('https://httpbin.org/delete')47 >>> r = requests.head('https://httpbin.org/get')48 >>> r = requests.options('https://httpbin.org/get')4950That's all well and good, but it's also only the start of what Requests can51do.525354Passing Parameters In URLs55--------------------------5657You often want to send some sort of data in the URL's query string. If58you were constructing the URL by hand, this data would be given as key/value59pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.60Requests allows you to provide these arguments as a dictionary of strings,61using the ``params`` keyword argument. As an example, if you wanted to pass62``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the63following code::6465 >>> payload = {'key1': 'value1', 'key2': 'value2'}66 >>> r = requests.get('https://httpbin.org/get', params=payload)6768You can see that the URL has been correctly encoded by printing the URL::6970 >>> print(r.url)71 https://httpbin.org/get?key2=value2&key1=value17273Note that any dictionary key whose value is ``None`` will not be added to the74URL's query string.7576You can also pass a list of items as a value::7778 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}7980 >>> r = requests.get('https://httpbin.org/get', params=payload)81 >>> print(r.url)82 https://httpbin.org/get?key1=value1&key2=value2&key2=value38384Response Content85----------------8687We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requests9192 >>> r = requests.get('https://api.github.com/events')93 >>> r.text94 '[{"repository":{"open_issues":0,"url":"https://github.com/...9596Requests will automatically decode content from the server. Most unicode97charsets are seamlessly decoded.9899When you make a request, Requests makes educated guesses about the encoding of100the response based on the HTTP headers. The text encoding guessed by Requests101is used when you access ``r.text``. You can find out what encoding Requests is102using, and change it, using the ``r.encoding`` property::103104 >>> r.encoding105 'utf-8'106 >>> r.encoding = 'ISO-8859-1'107108If you change the encoding, Requests will use the new value of ``r.encoding``109whenever you call ``r.text``. You might want to do this in any situation where110you can apply special logic to work out what the encoding of the content will111be. For example, HTML and XML have the ability to specify their encoding in112their body. In situations like this, you should use ``r.content`` to find the113encoding, and then set ``r.encoding``. This will let you use ``r.text`` with114the correct encoding.115116Requests will also use custom encodings in the event that you need them. If117you have created your own encoding and registered it with the ``codecs``118module, you can simply use the codec name as the value of ``r.encoding`` and119Requests will handle the decoding for you.120121Binary Response Content122-----------------------123124You can also access the response body as bytes, for non-text requests::125126 >>> r.content127 b'[{"repository":{"open_issues":0,"url":"https://github.com/...128129The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.130131The ``br`` transfer-encoding is automatically decoded for you if a Brotli library132like `brotli <https://pypi.org/project/brotli>`_ or `brotlicffi <https://pypi.org/project/brotlicffi>`_ is installed.133134For example, to create an image from binary data returned by a request, you can135use the following code::136137 >>> from PIL import Image138 >>> from io import BytesIO139140 >>> i = Image.open(BytesIO(r.content))141142143JSON Response Content144---------------------145146There's also a builtin JSON decoder, in case you're dealing with JSON data::147148 >>> import requests149150 >>> r = requests.get('https://api.github.com/events')151 >>> r.json()152 [{'repository': {'open_issues': 0, 'url': 'https://github.com/...153154In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if155the response gets a 204 (No Content), or if the response contains invalid JSON,156attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception157provides interoperability for multiple exceptions that may be thrown by different158python versions and json serialization libraries.159160It should be noted that the success of the call to ``r.json()`` does **not**161indicate the success of the response. Some servers may return a JSON object in a162failed response (e.g. error details with HTTP 500). Such JSON will be decoded163and returned. To check that a request is successful, use164``r.raise_for_status()`` or check ``r.status_code`` is what you expect.165166167Raw Response Content168--------------------169170In the rare case that you'd like to get the raw socket response from the171server, you can access ``r.raw``. If you want to do this, make sure you set172``stream=True`` in your initial request. Once you do, you can do this::173174 >>> r = requests.get('https://api.github.com/events', stream=True)175176 >>> r.raw177 <urllib3.response.HTTPResponse object at 0x101194810>178179 >>> r.raw.read(10)180 b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'181182In general, however, you should use a pattern like this to save what is being183streamed to a file::184185 with open(filename, 'wb') as fd:186 for chunk in r.iter_content(chunk_size=128):187 fd.write(chunk)188189Using ``Response.iter_content`` will handle a lot of what you would otherwise190have to handle when using ``Response.raw`` directly. When streaming a191download, the above is the preferred and recommended way to retrieve the192content. Note that ``chunk_size`` can be freely adjusted to a number that193may better fit your use cases.194195.. note::196197 An important note about using ``Response.iter_content`` versus ``Response.raw``.198 ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``199 transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not200 transform the response content. If you really need access to the bytes as they201 were returned, use ``Response.raw``.202203Merge pull request #6612 from miketheman/fix-docs-urlsIan Stapleton Cordascobefore adoption72eccc8
lines 204–205why, one step back204.. _custom-headers:205Merge pull request #6519 from psf/dependabot/github_actions/actions/checkout-4.0.0Ian Stapleton Cordascobefore adoption8812812
lines 206–224why, one step back206Custom Headers207--------------208209If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the210``headers`` parameter.211212For example, we didn't specify our user-agent in the previous example::213214 >>> url = 'https://api.github.com/some/endpoint'215 >>> headers = {'user-agent': 'my-app/0.0.1'}216217 >>> r = requests.get(url, headers=headers)218219Note: Custom headers are given less precedence than more specific sources of information. For instance:220221* Authorization headers set with `headers=` will be overridden if credentials222 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``223 parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,224 or at the path specified by the `NETRC` environment variable.Add netrc file search information to authentication documentation (#6876)Piotr Szlazakbefore adoption59f8aa2
line 225why, one step back225 Check details in :ref:`netrc authentication <authentication>`.Merge pull request #6519 from psf/dependabot/github_actions/actions/checkout-4.0.0Ian Stapleton Cordascobefore adoption8812812
lines 226–273why, one step back226* Authorization headers will be removed if you get redirected off-host.227* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.228* Content-Length headers will be overridden when we can determine the length of the content.229230Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.231232Note: All header values must be a ``string``, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.233234More complicated POST requests235------------------------------236237Typically, you want to send some form-encoded data — much like an HTML form.238To do this, simply pass a dictionary to the ``data`` argument. Your239dictionary of data will automatically be form-encoded when the request is made::240241 >>> payload = {'key1': 'value1', 'key2': 'value2'}242243 >>> r = requests.post('https://httpbin.org/post', data=payload)244 >>> print(r.text)245 {246 ...247 "form": {248 "key2": "value2",249 "key1": "value1"250 },251 ...252 }253254The ``data`` argument can also have multiple values for each key. This can be255done by making ``data`` either a list of tuples or a dictionary with lists256as values. This is particularly useful when the form has multiple elements that257use the same key::258259 >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]260 >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)261 >>> payload_dict = {'key1': ['value1', 'value2']}262 >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)263 >>> print(r1.text)264 {265 ...266 "form": {267 "key1": [268 "value1",269 "value2"270 ]271 },272 ...273 }docs: clarify Quickstart POST example (#6960)Ethan Pricebefore adoptiond568f47
lines 274–276why, one step back274 >>> # httpbin may embed non-deterministic metadata,275 >>> # so we only compare our submitted data here.276 >>> r1.json()['form'] == r2.json()['form']Merge pull request #6519 from psf/dependabot/github_actions/actions/checkout-4.0.0Ian Stapleton Cordascobefore adoption8812812
lines 277–573why, one step back277 True278279There are times that you may want to send data that is not form-encoded. If280you pass in a ``string`` instead of a ``dict``, that data will be posted directly.281282For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::283284 >>> import json285286 >>> url = 'https://api.github.com/some/endpoint'287 >>> payload = {'some': 'data'}288289 >>> r = requests.post(url, data=json.dumps(payload))290291Please note that the above code will NOT add the ``Content-Type`` header292(so in particular it will NOT set it to ``application/json``).293294If you need that header set and you don't want to encode the ``dict`` yourself,295you can also pass it directly using the ``json`` parameter (added in version 2.4.2)296and it will be encoded automatically:297298 >>> url = 'https://api.github.com/some/endpoint'299 >>> payload = {'some': 'data'}300301 >>> r = requests.post(url, json=payload)302303Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.304305POST a Multipart-Encoded File306-----------------------------307308Requests makes it simple to upload Multipart-encoded files::309310 >>> url = 'https://httpbin.org/post'311 >>> files = {'file': open('report.xls', 'rb')}312313 >>> r = requests.post(url, files=files)314 >>> r.text315 {316 ...317 "files": {318 "file": "<censored...binary...data>"319 },320 ...321 }322323You can set the filename, content_type and headers explicitly::324325 >>> url = 'https://httpbin.org/post'326 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}327328 >>> r = requests.post(url, files=files)329 >>> r.text330 {331 ...332 "files": {333 "file": "<censored...binary...data>"334 },335 ...336 }337338If you want, you can send strings to be received as files::339340 >>> url = 'https://httpbin.org/post'341 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}342343 >>> r = requests.post(url, files=files)344 >>> r.text345 {346 ...347 "files": {348 "file": "some,data,to,send\\nanother,row,to,send\\n"349 },350 ...351 }352353In the event you are posting a very large file as a ``multipart/form-data``354request, you may want to stream the request. By default, ``requests`` does not355support this, but there is a separate package which does -356``requests-toolbelt``. You should read `the toolbelt's documentation357<https://toolbelt.readthedocs.io>`_ for more details about how to use it.358359For sending multiple files in one request refer to the :ref:`advanced <advanced>`360section.361362.. warning:: It is strongly recommended that you open files in :ref:`binary363 mode <tut-files>`. This is because Requests may attempt to provide364 the ``Content-Length`` header for you, and if it does this value365 will be set to the number of *bytes* in the file. Errors may occur366 if you open the file in *text mode*.367368369Response Status Codes370---------------------371372We can check the response status code::373374 >>> r = requests.get('https://httpbin.org/get')375 >>> r.status_code376 200377378Requests also comes with a built-in status code lookup object for easy379reference::380381 >>> r.status_code == requests.codes.ok382 True383384If we made a bad request (a 4XX client error or 5XX server error response), we385can raise it with386:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::387388 >>> bad_r = requests.get('https://httpbin.org/status/404')389 >>> bad_r.status_code390 404391392 >>> bad_r.raise_for_status()393 Traceback (most recent call last):394 File "requests/models.py", line 832, in raise_for_status395 raise http_error396 requests.exceptions.HTTPError: 404 Client Error397398But, since our ``status_code`` for ``r`` was ``200``, when we call399``raise_for_status()`` we get::400401 >>> r.raise_for_status()402 None403404All is well.405406407Response Headers408----------------409410We can view the server's response headers using a Python dictionary::411412 >>> r.headers413 {414 'content-encoding': 'gzip',415 'transfer-encoding': 'chunked',416 'connection': 'close',417 'server': 'nginx/1.0.4',418 'x-runtime': '148ms',419 'etag': '"e1ca502697e5c9317743dc078f67693f"',420 'content-type': 'application/json'421 }422423The dictionary is special, though: it's made just for HTTP headers. According to424`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names425are case-insensitive.426427So, we can access the headers using any capitalization we want::428429 >>> r.headers['Content-Type']430 'application/json'431432 >>> r.headers.get('content-type')433 'application/json'434435It is also special in that the server could have sent the same header multiple436times with different values, but requests combines them so they can be437represented in the dictionary within a single mapping, as per438`RFC 7230 <https://tools.ietf.org/html/rfc7230#section-3.2>`_:439440 A recipient MAY combine multiple header fields with the same field name441 into one "field-name: field-value" pair, without changing the semantics442 of the message, by appending each subsequent field value to the combined443 field value in order, separated by a comma.444445Cookies446-------447448If a response contains some Cookies, you can quickly access them::449450 >>> url = 'http://example.com/some/cookie/setting/url'451 >>> r = requests.get(url)452453 >>> r.cookies['example_cookie_name']454 'example_cookie_value'455456To send your own cookies to the server, you can use the ``cookies``457parameter::458459 >>> url = 'https://httpbin.org/cookies'460 >>> cookies = dict(cookies_are='working')461462 >>> r = requests.get(url, cookies=cookies)463 >>> r.text464 '{"cookies": {"cookies_are": "working"}}'465466Cookies are returned in a :class:`~requests.cookies.RequestsCookieJar`,467which acts like a ``dict`` but also offers a more complete interface,468suitable for use over multiple domains or paths. Cookie jars can469also be passed in to requests::470471 >>> jar = requests.cookies.RequestsCookieJar()472 >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')473 >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')474 >>> url = 'https://httpbin.org/cookies'475 >>> r = requests.get(url, cookies=jar)476 >>> r.text477 '{"cookies": {"tasty_cookie": "yum"}}'478479480Redirection and History481-----------------------482483By default Requests will perform location redirection for all verbs except484HEAD.485486We can use the ``history`` property of the Response object to track redirection.487488The :attr:`Response.history <requests.Response.history>` list contains the489:class:`Response <requests.Response>` objects that were created in order to490complete the request. The list is sorted from the oldest to the most recent491response.492493For example, GitHub redirects all HTTP requests to HTTPS::494495 >>> r = requests.get('http://github.com/')496497 >>> r.url498 'https://github.com/'499500 >>> r.status_code501 200502503 >>> r.history504 [<Response [301]>]505506507If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable508redirection handling with the ``allow_redirects`` parameter::509510 >>> r = requests.get('http://github.com/', allow_redirects=False)511512 >>> r.status_code513 301514515 >>> r.history516 []517518If you're using HEAD, you can enable redirection as well::519520 >>> r = requests.head('http://github.com/', allow_redirects=True)521522 >>> r.url523 'https://github.com/'524525 >>> r.history526 [<Response [301]>]527528529Timeouts530--------531532You can tell Requests to stop waiting for a response after a given number of533seconds with the ``timeout`` parameter. Nearly all production code should use534this parameter in nearly all requests. Failure to do so can cause your program535to hang indefinitely::536537 >>> requests.get('https://github.com/', timeout=0.001)538 Traceback (most recent call last):539 File "<stdin>", line 1, in <module>540 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)541542543.. admonition:: Note544545 ``timeout`` is not a time limit on the entire response download;546 rather, an exception is raised if the server has not issued a547 response for ``timeout`` seconds (more precisely, if no bytes have been548 received on the underlying socket for ``timeout`` seconds). If no timeout is specified explicitly, requests do549 not time out.550551552Errors and Exceptions553---------------------554555In the event of a network problem (e.g. DNS failure, refused connection, etc),556Requests will raise a :exc:`~requests.exceptions.ConnectionError` exception.557558:meth:`Response.raise_for_status() <requests.Response.raise_for_status>` will559raise an :exc:`~requests.exceptions.HTTPError` if the HTTP request560returned an unsuccessful status code.561562If a request times out, a :exc:`~requests.exceptions.Timeout` exception is563raised.564565If a request exceeds the configured number of maximum redirections, a566:exc:`~requests.exceptions.TooManyRedirects` exception is raised.567568All exceptions that Requests explicitly raises inherit from569:exc:`requests.exceptions.RequestException`.570571-----------------------572573Ready for more? Check out the :ref:`advanced <advanced>` section.