Quickstart - Requests 2.28.1 Documentation
Quickstart - Requests 2.28.1 Documentation
Eager to get started? This page gives a good introduction in how to get started with Requests.
Requests is installed
Requests is up-to-date
Make a Request
Making a request with Requests is very simple.
Now, let’s try to get a webpage. For this example, let’s get GitHub’s public timeline:
>>> r = requests.get('https://api.github.com/events')
Now, we have a Response object called r. We can get all the information we need from this object.
Requests’ simple API means that all forms of HTTP request are as obvious. For example, this is
how you make an HTTP POST request:
Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and OPTIONS? These
are all just as simple:
That’s all well and good, but it’s also only the start of what Requests can do.
You can see that the URL has been correctly encoded by printing the URL:
>>> print(r.url)
https://httpbin.org/get?key2=value2&key1=value1
Note that any dictionary key whose value is None will not be added to the URL’s query string.
Response Content
We can read the content of the server’s response. Consider the GitHub timeline again:
>>> r = requests.get('https://api.github.com/events')
>>> r.text
'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests will automatically decode content from the server. Most unicode charsets are seamlessly
decoded.
When you make a request, Requests makes educated guesses about the encoding of the response
based on the HTTP headers. The text encoding guessed by Requests is used when you access
r.text. You can find out what encoding Requests is using, and change it, using the r.encoding
property:
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
If you change the encoding, Requests will use the new value of r.encoding whenever you call
r.text. You might want to do this in any situation where you can apply special logic to work out
what the encoding of the content will be. For example, HTML and XML have the ability to specify
their encoding in their body. In situations like this, you should use r.content to find the encoding,
and then set r.encoding. This will let you use r.text with the correct encoding.
Requests will also use custom encodings in the event that you need them. If you have created your
own encoding and registered it with the codecs module, you can simply use the codec name as the
value of r.encoding and Requests will handle the decoding for you.
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
The gzip and deflate transfer-encodings are automatically decoded for you.
The br transfer-encoding is automatically decoded for you if a Brotli library like brotli or brotlicffi
is installed.
For example, to create an image from binary data returned by a request, you can use the following
code:
>>> i = Image.open(BytesIO(r.content))
>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{'repository': {'open_issues': 0, 'url': 'https://github.com/...
In case the JSON decoding fails, r.json() raises an exception. For example, if the response gets a
204 (No Content), or if the response contains invalid JSON, attempting r.json() raises
requests.exceptions.JSONDecodeError. This wrapper exception provides interoperability for
multiple exceptions that may be thrown by different python versions and json serialization
libraries.
It should be noted that the success of the call to r.json() does not indicate the success of the re-
sponse. Some servers may return a JSON object in a failed response (e.g. error details with HTTP
500). Such JSON will be decoded and returned. To check that a request is successful, use
r.raise_for_status() or check r.status_code is what you expect.
>>> r.raw
<urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
In general, however, you should use a pattern like this to save what is being streamed to a file:
Using Response.iter_content will handle a lot of what you would otherwise have to handle when
using Response.raw directly. When streaming a download, the above is the preferred and recom-
mended way to retrieve the content. Note that chunk_size can be freely adjusted to a number that
may better fit your use cases.
Note:
An important note about using Response.iter_content versus Response.raw.
Response.iter_content will automatically decode the gzip and deflate transfer-encod-
ings. Response.raw is a raw stream of bytes – it does not transform the response content. If
you really need access to the bytes as they were returned, use Response.raw.
Custom Headers
If you’d like to add HTTP headers to a request, simply pass in a dict to the headers parameter.
Furthermore, 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.
Note: All header values must be a string, bytestring, or unicode. While permitted, it’s advised to
avoid passing unicode header values.
The data argument can also have multiple values for each key. This can be done by making data
either a list of tuples or a dictionary with lists as values. This is particularly useful when the form
has multiple elements that use the same key:
There are times that you may 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.
If you need that header set and you don’t want to encode the dict yourself, you can also pass it di-
rectly using the json parameter (added in version 2.4.2) and it will be encoded automatically:
In the event you are posting a very large file as a multipart/form-data request, you may want to
stream the request. By default, requests does not support this, but there is a separate package
which does - requests-toolbelt. You should read the toolbelt’s documentation for more details
about how to use it. v: latest
For sending multiple files in one request refer to the advanced section.
Warning:
It is strongly recommended that you open files in binary mode. This is because Requests
may attempt to provide the Content-Length header for you, and if it does this value will be
set to the number of bytes in the file. Errors may occur if you open the file in text mode.
>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200
Requests also comes with a built-in status code lookup object for easy reference:
If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with
Response.raise_for_status():
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
But, since our status_code for r was 200, when we call raise_for_status() we get:
>>> r.raise_for_status()
None
All is well.
Response Headers
We can view the server’s response headers using a Python dictionary:
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
The dictionary is special, though: it’s made just for HTTP headers. According to RFC 7230, HTTP
Header names are case-insensitive.
>>> r.headers['Content-Type']
'application/json' v: latest
>>> r.headers.get('content-type')
'application/json'
It is also special in that the server could have sent the same header multiple times with different
values, but requests combines them so they can be represented in the dictionary within a single
mapping, as per RFC 7230:
A recipient MAY combine multiple header fields with the same field name into one “field-
name: field-value” pair, without changing the semantics of the message, by appending each
subsequent field value to the combined field value in order, separated by a comma.
Cookies
If a response contains some Cookies, you can quickly access them:
>>> r.cookies['example_cookie_name']
'example_cookie_value'
To send your own cookies to the server, you can use the cookies parameter:
Cookies are returned in a RequestsCookieJar, which acts like a dict but also offers a more com-
plete interface, suitable for use over multiple domains or paths. Cookie jars can also be passed in
to requests:
We can use the history property of the Response object to track redirection.
The Response.history list contains the Response objects that were created in order to complete the
request. The list is sorted from the oldest to the most recent response.
>>> r = requests.get('http://github.com/')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>] v: latest
If you’re using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable redirection handling
with the allow_redirects parameter:
>>> r.status_code
301
>>> r.history
[]
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]
Timeouts
You can tell Requests to stop waiting for a response after a given number of seconds with the
timeout parameter. Nearly all production code should use this parameter in nearly all requests.
Failure to do so can cause your program to hang indefinitely:
Note:
timeout is not a time limit on the entire response download; rather, an exception is raised
if the server has not issued a response for timeout seconds (more precisely, if no bytes
have been received on the underlying socket for timeout seconds). If no timeout is speci-
fied explicitly, requests do not time out.
If you’re on the job market, consider taking this programming quiz. A substantial donation will be
made to this project, if you find a job through this platform.
v: latest