Sessions

class restfly.session.APISession(**kwargs)[source]

The APISession class is the base model for APISessions for different products and applications. This is the model that the APIEndpoints will be grafted onto and supports some basic wrapping of standard HTTP methods on it’s own.

_box

Should responses be converted to Box objects automatically by default? If left unspecified, the default is False

Type:bool
_build

The build number/version of the integration.

Type:str
_backoff

The default backoff timer to use when retrying. The value is either a float or integer denoting the number of seconds to delay before the next retry attempt. The number will be multiplied by the number of retries attempted.

Type:float
_base_error_map

The error mapping detailing what HTTP response code should throw what kind of error. As this is the base mapping, overloading this would remove any pre-set error mappings.

Type:dict
_error_map

The error mapping detailing what HTTP response code should throw what kind of error. This error map will overload specific error mappings.

Type:dict
_error_on_unexpected_input

If unexpected keywords have been passed to the session constructor, should we raise an error? Default is False.

Type:bool
_lib_name

The name of the library.

Type:str
_lib_version

The version of the library.

Type:str
_product

The product name for the integration.

Type:str
_proxies

A dictionary detailing what proxy should be used for what transport protocol. This value will be passed to the session object after it has been either attached or created. For details on the structure of this dictionary, consult the Requests documentation.

Type:dict
_restricted_paths

A list of paths (not complete URIs) that if seen be the _req method will not pass the query params or the request body into the logging facility. This should generally be used for paths that are sensitive in nature (such as logins).

Type:list[str]
_retries

The number of retries to make before failing a request. The default is 3.

Type:int
_session

Provide a pre-built session instead of creating a requests session at instantiation.

Type:requests.Session
_ssl_verify

Should SSL verification be performed? If not, then inform requests that we don’t want to use SSL verification and suppress the SSL certificate warnings.

Type:bool
_timeout

The number of seconds to wait with no data returned before declaring the request as stalled and timing-out the request.

Type:int
_url

The base URL path to use. This should generally be a string value denoting the first half of the URI. For example, https://httpbin.org or https://example.api.site/api/2. The _req method will join this string with the incoming path to construct the complete URI. Note that the two strings will be joined with a backslash /.

Type:str
_vendor

The vendor name for the integration.

Type:str
Parameters:
  • adapter (Object, optional) – A Requests Session adaptor to bind to the session object.
  • adapter_path (str, optional) – The URL that the adapter will bind to.
  • backoff (float, optional) – If a 429 response is returned, how much do we want to backoff if the response didn’t send a Retry-After header.
  • build (str, optional) – The build number to put into the User-Agent string.
  • product (str, optional) – The product name to put into the User-Agent string.
  • proxies (dict, optional) – A dictionary detailing what proxy should be used for what transport protocol. This value will be passed to the session object after it has been either attached or created. For details on the structure of this dictionary, consult the proxies section of the Requests documentation.
  • retries (int, optional) – The number of retries to make before failing a request. The default is 3.
  • session (requests.Session, optional) – Provide a pre-built session instead of creating a requests session at instantiation.
  • ssl_verify (bool, optional) – If SSL Verification needs to be disabled (for example when using a self-signed certificate), then this parameter should be set to False to disable verification and mask the Certificate warnings.
  • url (str, optional) – The base URL that the paths will be appended onto.
  • vendor (str, optional) – The vendor name to put into the User-Agent string.
_authenticate(**kwargs)[source]

Authentication stub. Overload this method with your authentication mechanism if you with to support authentication at creation and authentication as part of context management. Note that this is run AFTER the session builder.

Example

>>> class ExampleAPISession(APISession):
...     def _authenticate(self, username, password):
...         self._session.auth = (username, password)
_build_session(**kwargs) → None[source]

The session builder. User-agent strings, cookies, headers, etc that should persist for the session should be initiated here. The session builder is called as part of the APISession constructor.

Parameters:session (requests.Session, optional) – If a session object was passed to the constructor, then this would contain a session, otherwise a new one is created.
Returns:None

Examples

Extending the session builder to use basic auth:

>>> class ExampleAPI(APISession):
...     def _build_session(self, session=None):
...         super(APISession, self)._build_session(**kwargs)
...         self._session.auth = (self._username, self._password)
_deauthenticate(**kwargs)[source]

De-authentication stub. De-authentication is automatically run as part of leaving context within the context manager.

Example

>>> class ExampleAPISession(APISession):
...     def _deauthenticate(self):
...         self.delete('session/token')
_req(method: str, path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response, Dict[KT, VT], List[T], None][source]

The requests session base request method. This is considered internal as it’s generally recommended to use the bespoke methods for each HTTP method.

Parameters:
  • method (str) – The HTTP method
  • path (str) – The URI path to append to the base path.
  • **kwargs (dict) – The keyword arguments to pass to the requests lib.
  • box (bool, optional) – A request-specific override as to if the response should attempted to be converted into a Box object.
  • box_attrs (dict, optional) – A request-specific override with a list of key-values to pass to the box constructor.
  • conv_json (bool, optional) – A request-specific override to automatically convert the response fromJSON to native datatypes.
  • redact_fields (list[str], optional) – A list of keys to redact in the response. Redaction is used for the requests to the API as all of the fields are sent to the debug logs. Note that redaction should be used with care as it basically makes a copy fo the request in order to scrub the values.
  • redact_value (str, optional) – The value to use to replace the redacted values with.
  • retry_on (list[int], optional) – A list of numeric response status codes to attempt retry on. This behavior is additive to the retry parameter in the exceptions.
  • use_base (bool, optional) – Should the base path be appended to the URL? if left unspecified the default is True.
Returns:

The default behavior is to return the requests Response object. box.Box or box.BoxList:

If the box parameter is set, then the response object will be converted to a Box object if the response contains a the content type header of “application/json”

dict or list:

If the conv_json paramerter is set, then the response object will be converted using the Response objects baked-in json() method.

None:

If either conv_json or box has been set, however the response object has an empty response body, then None will be returned instead.

Return type:

requests.Response

Examples

>>> api = APISession()
>>> resp = api._req('GET', '/')
_resp_error_check(response: requests.models.Response, **kwargs) → requests.models.Response[source]

If there is a need for additional error checking (for example within the JSON response) then overload this method with the necessary checking.

Parameters:
  • response (request.Response) – The response object.
  • **kwargs (dict) – The request keyword arguments.
Returns:

The response object.

Return type:

requests.Response

_retry_request(response: requests.models.Response, retries: int, **kwargs) → dict[source]

A method to be overloaded to return any modifications to the request upon retries. By default just passes back what was send in the same order.

Parameters:
  • response (request.Response) – The response object
  • retries (int) – The number of retries that have been performed.
  • **kwargs (dict) – The keyword arguments that were passed to the request.
Returns:

The keyword arguments

Return type:

dict

delete(path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response][source]

Initiates an HTTP DELETE request using the specified path. Refer to the requests.request for more detailed information on what keyword arguments can be passed:

Parameters:
Returns:

requests.Response or box.Box

If the request was informed to attempt to “boxify” the response and the response was JSON data, then a Box will be returned. In all other scenarios, a Response object will be returned.

Examples

>>> api = APISession()
>>> resp = api.delete('/')
get(path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response][source]

Initiates an HTTP GET request using the specified path. Refer to requests.request for more detailed information on what keyword arguments can be passed:

Parameters:
Returns:

requests.Response or box.Box

If the request was informed to attempt to “boxify” the response and the response was JSON data, then a Box will be returned. In all other scenarios, a Response object will be returned.

Examples

>>> api = APISession()
>>> resp = api.get('/')
head(path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response][source]

Initiates an HTTP HEAD request using the specified path. Refer to the requests.request for more detailed information on what keyword arguments can be passed:

Parameters:
Returns:

requests.Response or box.Box

If the request was informed to attempt to “boxify” the response and the response was JSON data, then a Box will be returned. In all other scenarios, a Response object will be returned.

Examples

>>> api = APISession()
>>> resp = api.head('/')
patch(path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response][source]

Initiates an HTTP PATCH request using the specified path. Refer to the requests.request for more detailed information on what keyword arguments can be passed:

Parameters:
Returns:

requests.Response or box.Box

If the request was informed to attempt to “boxify” the response and the response was JSON data, then a Box will be returned. In all other scenarios, a Response object will be returned.

Examples

>>> api = APISession()
>>> resp = api.patch('/')
post(path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response][source]

Initiates an HTTP POST request using the specified path. Refer to the requests.request for more detailed information on what keyword arguments can be passed:

Parameters:
Returns:

requests.Response or box.Box

If the request was informed to attempt to “boxify” the response and the response was JSON data, then a Box will be returned. In all other scenarios, a Response object will be returned.

Examples

>>> api = APISession()
>>> resp = api.post('/')
put(path: str, **kwargs) → Union[<Mock name='mock.Box' id='140109156270608'>, <Mock name='mock.BoxList' id='140109156270736'>, requests.models.Response][source]

Initiates an HTTP PUT request using the specified path. Refer to the requests.request for more detailed information on what keyword arguments can be passed:

Parameters:
Returns:

requests.Response or box.Box

If the request was informed to attempt to “boxify” the response and the response was JSON data, then a Box will be returned. In all other scenarios, a Response object will be returned.

Examples

>>> api = APISession()
>>> resp = api.put('/')