API
This part of the documentation covers all the interfaces of Requests. For
parts where Requests depends on external libraries, we document the most
important right here and provide links to the canonical documentation.
Main Interface
All of Request’s functionality can be accessed by these 7 methods.
They all return an instance of the Response object.
-
requests.request(method, url, **kwargs)
-
class requests.Response
The core Response object. All
Request objects contain a
response attribute, which is an instance
of this class.
-
config = None
Dictionary of configurations for this request.
-
content
Content of the response, in bytes.
-
cookies = None
A CookieJar of Cookies the server sent back.
-
encoding = None
Encoding to decode with when accessing r.text.
-
error = None
Resulting HTTPError of request, if one occurred.
Case-insensitive Dictionary of Response Headers.
For example, headers['content-encoding'] will return the
value of a 'Content-Encoding' response header.
-
history = None
A list of Response objects from
the history of the Request. Any redirect responses will end
up here. The list is sorted from the oldest to the most recent request.
-
iter_content(chunk_size=1, decode_unicode=False)
Iterates over the response data. This avoids reading the content
at once into memory for large responses. The chunk size is the number
of bytes it should read into memory. This is not necessarily the
length of each item returned as decoding can take place.
-
iter_lines(chunk_size=10240, decode_unicode=None)
Iterates over the response data, one line at a time. This
avoids reading the content at once into memory for large
responses.
-
json
Returns the json-encoded content of a response, if any.
-
links
Returns the parsed header links of the response, if any.
-
raise_for_status(allow_redirects=True)
Raises stored HTTPError or URLError, if one occurred.
-
raw = None
File-like object representation of response (for advanced usage).
-
reason
The HTTP Reason for the response.
-
request = None
The Request that created the Response.
-
status_code = None
Integer Code of responded HTTP Status.
-
text
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding
will be guessed.
-
url = None
Final URL location of Response.
-
requests.head(url, **kwargs)
Sends a HEAD request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
requests.get(url, **kwargs)
Sends a GET request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
requests.post(url, data=None, **kwargs)
Sends a POST request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- **kwargs – Optional arguments that request takes.
|
-
requests.put(url, data=None, **kwargs)
Sends a PUT request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- **kwargs – Optional arguments that request takes.
|
-
requests.patch(url, data=None, **kwargs)
Sends a PATCH request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- **kwargs – Optional arguments that request takes.
|
-
requests.delete(url, **kwargs)
Sends a DELETE request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
requests.session(**kwargs)
Returns a Session for context-management.
Exceptions
-
exception requests.RequestException
There was an ambiguous exception that occurred while handling your
request.
-
exception requests.ConnectionError
A Connection error occurred.
-
exception requests.HTTPError
An HTTP error occurred.
-
exception requests.URLRequired
A valid URL is required to make a request.
-
exception requests.TooManyRedirects
Too many redirects.
Configurations
requests.defaults
This module provides the Requests configuration defaults.
Configurations:
base_headers: | Default HTTP headers. |
verbose: | Stream to write request logging to. |
max_redirects: | Maximum number of redirects allowed within a request.s |
keep_alive: | Reuse HTTP Connections? |
max_retries: | The number of times a request should be retried in the event of a connection failure. |
danger_mode: | If true, Requests will raise errors immediately. |
safe_mode: | If true, Requests will catch all errors. |
strict_mode: | If true, Requests will do its best to follow RFCs (e.g. POST redirects). |
pool_maxsize: | The maximium size of an HTTP connection pool. |
pool_connections: |
| The number of active HTTP connection pools to use. |
encode_uri: | If true, URIs will automatically be percent-encoded. |
trust_env: | If true, the surrouding environment will be trusted (environ, netrc). |
param store_cookies: |
| If false, the received cookies as part of the HTTP response would be ignored. |
Async
Utilities
These functions are used internally, but may be useful outside of
Requests.
Status Code Lookup
-
requests.codes(name=None)
Dictionary lookup object.
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200
Cookies
-
requests.utils.dict_from_cookiejar(cj)
Returns a key/value dictionary from a CookieJar.
Parameters: | cj – CookieJar object to extract cookies from. |
-
requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None)
Returns a CookieJar from a key/value dictionary.
Parameters: | cookie_dict – Dict of key/values to insert into CookieJar. |
-
requests.utils.add_dict_to_cookiejar(cj, cookie_dict)
Returns a CookieJar from a key/value dictionary.
Parameters: |
- cj – CookieJar to insert cookies into.
- cookie_dict – Dict of key/values to insert into CookieJar.
|
Encodings
-
requests.utils.get_encodings_from_content(content)
Returns encodings from given content string.
Parameters: | content – bytestring to extract encodings from. |
Returns encodings from given HTTP Header Dict.
Parameters: | headers – dictionary to extract encoding from. |
-
requests.utils.get_unicode_from_response(r)
Returns the requested content back in unicode.
Parameters: | r – Response object to get unicode content from. |
Tried:
- charset from content-type
- every encodings from <meta ... charset=XXX>
- fall back and replace all unicode characters
Internals
These items are an internal component to Requests, and should never be
seen by the end user (developer). This part of the API documentation
exists for those who are extending the functionality of Requests.
Classes
-
class requests.Response
The core Response object. All
Request objects contain a
response attribute, which is an instance
of this class.
-
config = None
Dictionary of configurations for this request.
-
content
Content of the response, in bytes.
-
cookies = None
A CookieJar of Cookies the server sent back.
-
encoding = None
Encoding to decode with when accessing r.text.
-
error = None
Resulting HTTPError of request, if one occurred.
-
headers = None
Case-insensitive Dictionary of Response Headers.
For example, headers['content-encoding'] will return the
value of a 'Content-Encoding' response header.
-
history = None
A list of Response objects from
the history of the Request. Any redirect responses will end
up here. The list is sorted from the oldest to the most recent request.
-
iter_content(chunk_size=1, decode_unicode=False)
Iterates over the response data. This avoids reading the content
at once into memory for large responses. The chunk size is the number
of bytes it should read into memory. This is not necessarily the
length of each item returned as decoding can take place.
-
iter_lines(chunk_size=10240, decode_unicode=None)
Iterates over the response data, one line at a time. This
avoids reading the content at once into memory for large
responses.
-
json
Returns the json-encoded content of a response, if any.
-
links
Returns the parsed header links of the response, if any.
-
raise_for_status(allow_redirects=True)
Raises stored HTTPError or URLError, if one occurred.
-
raw = None
File-like object representation of response (for advanced usage).
-
reason
The HTTP Reason for the response.
-
request = None
The Request that created the Response.
-
status_code = None
Integer Code of responded HTTP Status.
-
text
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding
will be guessed.
-
url = None
Final URL location of Response.
-
class requests.Request(url=None, headers={}, files=None, method=None, data={}, params={}, auth=None, cookies=None, timeout=None, redirect=False, allow_redirects=False, proxies=None, hooks=None, config=None, prefetch=True, _poolmanager=None, verify=None, session=None, cert=None)
The Request object. It carries out all functionality
of Requests. Recommended interface is with the Requests functions.
-
allow_redirects = None
Set to True if full redirects are allowed (e.g. re-POST-ing of data at new Location)
-
auth = None
Authentication tuple or object to attach to Request.
-
cert = None
SSL Certificate
-
config = None
Dictionary of configurations for this request.
-
data = None
Dictionary, bytes or file stream of request body data to attach to the
Request.
-
deregister_hook(event, hook)
Deregister a previously registered hook.
Returns True if the hook existed, False if not.
-
files = None
Dictionary of files to multipart upload ({filename: content}).
-
full_url
Build the actual URL to use.
Dictionary of HTTP Headers to attach to the Request.
-
hooks = None
Event-handling hooks.
-
method = None
HTTP Method to use.
-
params = None
Dictionary or byte of querystring data to attach to the
Request. The dictionary values can be lists for representing
multivalued query parameters.
-
path_url
Build the path URL to use.
-
prefetch = None
Prefetch response content
-
redirect = None
True if Request is part of a redirect chain (disables history
and HTTPError storage).
-
register_hook(event, hook)
Properly register a hook.
-
response = None
Response instance, containing
content and metadata of HTTP Response, once sent.
-
send(anyway=False, prefetch=None)
Sends the request. Returns True if successful, False if not.
If there was an HTTPError during transmission,
self.response.status_code will contain the HTTPError code.
Once a request is successfully sent, sent will equal True.
Parameters: | anyway – If True, request will be sent, even if it has |
already been sent.
Parameters: | prefetch – If not None, will override the request’s own setting |
for prefetch.
-
sent = None
True if Request has been sent.
-
session = None
Session.
-
timeout = None
Float describes the timeout of the request.
-
verify = None
SSL Verification.
-
class requests.Session(headers=None, cookies=None, auth=None, timeout=None, proxies=None, hooks=None, params=None, config=None, prefetch=True, verify=True, cert=None)
A Requests session.
-
close()
Dispose of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections.
-
delete(url, **kwargs)
Sends a DELETE request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
get(url, **kwargs)
Sends a GET request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
head(url, **kwargs)
Sends a HEAD request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
options(url, **kwargs)
Sends a OPTIONS request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- **kwargs – Optional arguments that request takes.
|
-
patch(url, data=None, **kwargs)
Sends a PATCH request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- **kwargs – Optional arguments that request takes.
|
-
post(url, data=None, **kwargs)
Sends a POST request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- **kwargs – Optional arguments that request takes.
|
-
put(url, data=None, **kwargs)
Sends a PUT request. Returns Response object.
Parameters: |
- url – URL for the new Request object.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- **kwargs – Optional arguments that request takes.
|
-
request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, return_response=True, config=None, prefetch=None, verify=None, cert=None)
Constructs and sends a Request.
Returns Response object.
Parameters: |
- method – method for the new Request object.
- url – URL for the new Request object.
- params – (optional) Dictionary or bytes to be sent in the query string for the Request.
- data – (optional) Dictionary or bytes to send in the body of the Request.
- headers – (optional) Dictionary of HTTP Headers to send with the Request.
- cookies – (optional) Dict or CookieJar object to send with the Request.
- files – (optional) Dictionary of ‘filename’: file-like-objects for multipart encoding upload.
- auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.
- timeout – (optional) Float describing the timeout of the request.
- allow_redirects – (optional) Boolean. Set to True by default.
- proxies – (optional) Dictionary mapping protocol to the URL of the proxy.
- return_response – (optional) If False, an un-sent Request object will returned.
- config – (optional) A configuration dictionary. See request.defaults for allowed keys and their default values.
- prefetch – (optional) whether to immediately download the response content. Defaults to True.
- verify – (optional) if True, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
- cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
|