Requests – HTTP for Humans

This part of the documentation covers all the interfaces of Requests.

Note

Editorial’s documentation only includes the core API documentation for requests. For a tutorial and more in-depth information, please visit the requests website.

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)

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, bytes, or file-like object 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 ‘name’: file-like-objects (or {‘name’: (‘filename’, fileobj)}) for multipart encoding upload.
  • auth – (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.
  • allow_redirects – (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
  • proxies – (optional) Dictionary mapping protocol to the URL of the proxy.
  • verify – (optional) if True, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
  • stream – (optional) if False, the response content will be immediately downloaded.
  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Usage:

>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>

class requests.Response

The Response object, which contains a server’s response to an HTTP request.

apparent_encoding

The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).

content

Content of the response, in bytes.

cookies

A CookieJar of Cookies the server sent back.

elapsed

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta)

encoding

Encoding to decode with when accessing r.text.

headers

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.

history

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. When stream=True is set on the request, 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=512, decode_unicode=None)

Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.

json(**kwargs)

Returns the json-encoded content of a response, if any.

Parameters:**kwargs – Optional arguments that json.loads takes.

Returns the parsed header links of the response, if any.

raise_for_status()

Raises stored HTTPError, if one occurred.

raw

File-like object representation of response (for advanced usage). Requires that ``stream=True` on the request.

status_code

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

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, bytes, or file-like object 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, bytes, or file-like object 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, bytes, or file-like object 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()

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(*args, **kwargs)

An HTTP error occurred.

exception requests.URLRequired

A valid URL is required to make a request.

exception requests.TooManyRedirects

Too many redirects.

Configurations

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 Response object, which contains a server’s response to an HTTP request.

apparent_encoding

The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).

content

Content of the response, in bytes.

cookies

A CookieJar of Cookies the server sent back.

elapsed

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta)

encoding

Encoding to decode with when accessing r.text.

headers

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding' response header.

history

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. When stream=True is set on the request, 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=512, decode_unicode=None)

Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.

json(**kwargs)

Returns the json-encoded content of a response, if any.

Parameters:**kwargs – Optional arguments that json.loads takes.
links

Returns the parsed header links of the response, if any.

raise_for_status()

Raises stored HTTPError, if one occurred.

raw

File-like object representation of response (for advanced usage). Requires that ``stream=True` on the request.

status_code

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

Final URL location of Response.

class requests.Request(method=None, url=None, headers=None, files=None, data={}, params={}, auth=None, cookies=None, hooks=None)

A user-created Request object.

Used to prepare a PreparedRequest, which is sent to the server.

Parameters:
  • method – HTTP method to use.
  • url – URL to send.
  • headers – dictionary of headers to send.
  • files – dictionary of {filename: fileobject} files to multipart upload.
  • data – the body to attach the request. If a dictionary is provided, form-encoding will take place.
  • params – dictionary of URL parameters to append to the URL.
  • auth – Auth handler or (user, pass) tuple.
  • cookies – dictionary or CookieJar of cookies to attach to this request.
  • hooks – dictionary of callback hooks, for internal usage.

Usage:

>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
deregister_hook(event, hook)

Deregister a previously registered hook. Returns True if the hook existed, False if not.

prepare()

Constructs a PreparedRequest for transmission and returns it.

register_hook(event, hook)

Properly register a hook.

class requests.Session

A Requests session.

Provides cookie persistience, connection-pooling, and configuration.

Basic Usage:

>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
200
auth

Default Authentication tuple or object to attach to Request.

cert

SSL certificate default.

close()

Closes all adapters and as such the session

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.
get_adapter(url)

Returns the appropriate connnection adapter for the given URL.

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • **kwargs – Optional arguments that request takes.
headers

A case-insensitive dictionary of headers to be sent on each Request sent from this Session.

hooks

Event-handling hooks.

max_redirects

Maximum number of redirects allowed. If the request exceeds this limit, a TooManyRedirects exception is raised.

mount(prefix, adapter)

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by key length.

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • **kwargs – Optional arguments that request takes.
params

Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • data – (optional) Dictionary, bytes, or file-like object 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, bytes, or file-like object to send in the body of the Request.
  • **kwargs – Optional arguments that request takes.
proxies

Dictionary mapping protocol to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’}) to be used on each Request.

put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • data – (optional) Dictionary, bytes, or file-like object 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, stream=None, verify=None, cert=None)

Constructs a Request, prepares it and sends it. 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.
  • stream – (optional) whether to immediately download the response content. Defaults to False.
  • 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.
resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None)

Receives a Response. Returns a generator of Responses.

send(request, **kwargs)

Send a given PreparedRequest.

stream

Stream response content default.

trust_env

Should we trust the environment?

verify

SSL Verification default.