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, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True, prefetch=False, session=None, config=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 ‘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.
  • return_response – (optional) If False, an un-sent Request object will returned.
  • session – (optional) A Session object to be used for the request.
  • config – (optional) A configuration dictionary.

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 or unicode (if available).

cookies = None

A dictionary of Cookies the server sent back.

encoding = None

Encoding to decode with when accessing r.content.

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.

iter_content(chunk_size=10240, decode_unicode=None)

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.

raise_for_status()

Raises stored HTTPError or URLError, if one occurred.

raw = None

File-like object representation of response (for advanced usage).

request = None

The Request that created the Response.

status_code = None

Integer Code of responded HTTP Status.

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.
timeout:Seconds until request timeout.
max_redirects:Maximum number of redirects allowed within a request.
decode_unicode:Decode unicode responses automatically?
keep_alive:Reuse HTTP Connections?
max_retries:The number of times a request should be retried in the event of a connection failure.
safe_mode:If true, Requests will catch all errors.
pool_maxsize:The maximium size of an HTTP connection pool.
pool_connections:
 The number of active HTTP connection pools to use.

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)

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.
requests.utils.get_encoding_from_headers(headers)

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:

  1. charset from content-type
  2. every encodings from <meta ... charset=XXX>
  3. fall back and replace all unicode characters
requests.utils.decode_gzip(content)

Return gzip-decoded string.

Parameters:content – bytestring to gzip-decode.

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 or unicode (if available).

cookies = None

A dictionary of Cookies the server sent back.

encoding = None

Encoding to decode with when accessing r.content.

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.

iter_content(chunk_size=10240, decode_unicode=None)

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.

raise_for_status()

Raises stored HTTPError or URLError, if one occurred.

raw = None

File-like object representation of response (for advanced usage).

request = None

The Request that created the Response.

status_code = None

Integer Code of responded HTTP Status.

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, _poolmanager=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.

config = None

Dictionary of configurations for this request.

cookies = None

CookieJar to attach to Request.

data = None

Dictionary or byte of request body data to attach to the Request.

files = None

Dictionary of files to multipart upload ({filename: content}).

full_url

Build the actual URL to use.

headers = None

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.

path_url

Build the path URL to use.

redirect = None

True if Request is part of a redirect chain (disables history and HTTPError storage).

response = None

Response instance, containing content and metadata of HTTP Response, once sent.

send(anyway=False, prefetch=False)

Sends the request. Returns True of 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.

sent = None

True if Request has been sent.

session = None

Session.

timeout = None

Float describes the timeout of the request.

url = None

Request URL.

class requests.Session(headers=None, cookies=None, auth=None, timeout=None, proxies=None, hooks=None, params=None, config=None)

A Requests 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.

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=False, proxies=None, hooks=None, return_response=True, config=None, prefetch=False)

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 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.
  • return_response – (optional) If False, an un-sent Request object will returned.
  • config – (optional) A configuration dictionary.
  • prefetch – (optional) if True, the response content will be immediately downloaded.

Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release.

Support Requests

If you love Requests, consider making a small donation on Flattr:

Table Of Contents

Related Topics

Fork me on GitHub