Restpite API

isort:skip_file

restpite.CERTIFICATE_TYPES

alias of restpite._models.CertificateInfo

class restpite.Connection(*, max_connections: Optional[int] = None, max_keepalive_connections: Optional[int] = None, keepalive_expiry: Optional[float] = 5.0)[source]
classmethod from_tuple(options: Union[Tuple[int, int], Tuple[int, int, float]])restpite._models.Connection[source]

Class method for converting a length 2 OR 3 tuple into the appropriate Connection instance.

class restpite.Notifyable(*args, **kwargs)[source]

Custom protocol for inspecting Restpite request and responses (and others) at runtime in order to drop in and control or manipulate the data.

exception restpite.RestpiteAssertionError(message: str)[source]
class restpite.RestpiteClient(*, auth: Optional[Union[Tuple[Union[str, bytes], Union[str, bytes]], Callable[[httpx.Request], httpx.Request], httpx.Auth]] = None, params: Optional[Mapping[str, Union[str, int, float, bytes, Sequence[Union[str, int, float, bytes]]]]] = None, headers: Optional[Dict[Union[str, bytes], Union[str, bytes]]] = None, cookies: Optional[Union[http.cookiejar.CookieJar, Mapping[str, str]]] = None, verify: Optional[Union[str, bool, ssl.SSLContext]] = True, cert: Optional[restpite._models.CertificateInfo] = None, http1: bool = True, http2: bool = False, proxies: Optional[Union[restpite._models.URL, str, httpx.Proxy, Dict[Union[restpite._models.URL, str], Optional[Union[restpite._models.URL, str, httpx.Proxy]]]]] = None, mounts: Optional[Mapping[str, httpcore.SyncHTTPTransport]] = None, timeout: Optional[restpite._models.Timeout] = Timeout(timeout=10.0), connection: Optional[Union[Tuple[int, int, float], restpite._models.Connection]] = Connection(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0), max_redirects: int = 20, event_hooks: Optional[Mapping[str, List[Callable[[Any], Any]]]] = None, base_url: Union[restpite._models.URL, str] = '', transport: Optional[httpcore.SyncHTTPTransport] = None, app: Optional[Callable[[Any], Any]] = None, trust_env: bool = True, user_agent: Optional[str] = None, event_subscribers: Optional[Sequence[restpite._protocols.Notifyable]] = None)[source]
A synchronous (IO blocking) HTTP client which supports:
  • HTTP/2

  • Connection pooling

  • Cookie persistence

  • Redirects

  • Request/Response tracking and performance

  • Much more …

  • Note: Only keyword arguments are supported by the client instance.

Usage:

`python >>> client = RestpiteClient() >>> response = client.get("https://www.google.com", headers={"foo": "bar"}, ...) `

Context usage:

`python >>> with RestpiteClient() as client: >>>     client.get("https://www.google.com", params={"foo": "bar"}) `

Parameters

auth – (Optional) By default Restpite supports Basic and Digest auth. In order to use Basic auth, pass

a tuple containing either bytes or strings, this will be sent in the request Authorization header b64 encoded. In order to use digest auth you should pass a httpx.DigestAuth instance. Subsequently subclassing httpx.Auth and implementing your own authorization mechanism can be useful. Lastly any callable can be passed that takes a single httpx.Request instance and returns the same instance. If omitted, no request headers will be manipulated for authorization.

Parameters

params – (Optional) Mapping of data to be sent in the request query string parameters. To provide multiple

values for the same parameter provide a sequence of primitive types as the mapping key:

```python >>> params = {“foo”: [“bar”, “baz”], “one”: 25} >>> response = RestpiteClient().get(“https://www.google.com”, params=params) >>> response.url >>> URL(‘https://www.google.com?foo=bar&foo=baz&one=25’)

If omitted, no query string parameters will be appended to the url for issued requests.

Parameters

headers – (Optional) Mapping of data to be send in the request headers. Headers should be a mapping

of either strings or bytes. By default all restpite issued requests will add their own user agent header in order to easily distinguish requests generated via the library.

If omitted, no user defined request headers will be sent with issued requests.

Parameters

cookies – (Optional) Mapping of Cookie items to send when issuing requests. Cookies can be either

http.cookiejar.CookieJar or a Mapping[str, str]. When using a client instance, cookies set by a remote server will be persisted across subsequent requests. It is advised to pass cookies= during client instantiation, rather than on an individual request basis.

If omitted, no user defined cookies will be sent with the issued requests.

Parameters

verify – (Optional) string, boolean or ssl.SSLContext. By default Restpite will use the

CA bundle provided by the Certifi package. In the event you would like to specify a different bundle CA, verify should be passed the string path (or using an instance of SSLContext instead). In order to completely disable SSL verification (not advised - tho sometimes necessary and useful in a development or testing environment). verify=False can be passed on the client.

If omitted, Certifi CA bundle will be assumed.

Parameters

cert – (Optional) A restpite.CertificateInfo instance containing data for the SSL

Certificate used by the requested host. CertificateInfo instances can contain either:
  • The path to the SSL certificate file (certfile=)

  • The path to the SSL certificate file (certfile=) and the path to a key file (keyfile=)

  • The path to both SSL certificate & key file, along with a password (password=)

if omitted, The Certifi CA bundle will be assumed.

Parameters
  • http1 – If specified as True, the client will communicate over the HTTP/1 protocol.

  • http2 – If specified as True, data will be transfered using the new HTTP/2 binary

format rather than the traditional HTTP/1 text format. HTTP/2 requires a single TCP connection to handle multiple concurrent requests. To better understand the changes and performance improvements of HTTP/2: https://http2-explained.haxx.se/content/en/

If http1=True & http2=True is provided to the client, http2 will be used. By default RestpiteClient will communicate using the more common HTTP/1 protocol however the option is there if you wish to explore it.

Parameters

proxies – (Optional) Dict mapping proxy keys to proxy URLs. SOCKS proxies

are not yet supported. Also permits a single string such as “http://localhost:8030”. An example for multiple proxies would be:

`python >>> proxies = {"http": "http://localhost:8030", "https": "http://localhost:8031"} >>> RestpiteClient(proxies=proxies) `

Note: The example above is not a typo; https traffic should likely route through http as far as the proxy is concerned, while some may support HTTPS most proxies will only support HTTP.

For more fine grained proxy control, passing an instance of httpx.Proxy can allow you to control things like Tunnelling vs Forwarding. By default forwarding will be used for HTTP requests and tunneling for https requests.

Parameters

mounts – Transports can be mounted against given domains or schemas, in order to control which

transport dispatched requests should be routed through, a mounts mapping can be provided which follows the same style used for proxy routing.

Parameters

timeoutrestpite.Timeout: Unlike when using requests, by default all requests sent will assume

sensible default timeouts (10.00), these are configurable on an individual basis.

  • connect -> How long we will attempt to wait for a success socket connection to be established to the server.

  • read -> How long we will wait for a chunk of data to be received from the remote server to the client.

  • write -> How long we will wait for a chunk of data to be sent from the client to the server.

  • pool -> How long we are willing to wait for a connection from the connection pool to be acquired.

By default, Restpite will assume a 10.0 second timeout across the board, this is configurable on:

  • A per request basis: client.get(timeout=…)

  • On a client directly and applied to all subsequent requests: RestpiteClient(timeout…)

It is possible to completely remove timeouts across the board by setting the timeout= parameter explicitly to None. This will prevent exceptions for all timeouts specified above during request dispatch workflow.

Through a number of environment variables, these can be globally configured, for each of the 4 potential timeouts, an equivalent env var can be set:

  • RESTPITE_CONNECT_TIMEOUT

  • RESTPITE_READ_TIMEOUT

  • RESTPITE_WRITE_TIMEOUT

  • RESTPITE_POOL_TIMEOUT

Parameters

connection – A restpite.Connection instance to dictate connection pooling limitations. Connection

controls both the max_keepalive connections (default: 20) and the maximum_connections for the client (default: 100). A Tuple of length two is also permitted where index 0 will control the max_keepalive and index 1 the maximum_connections

  • connection is only available on the client.

Parameters
  • max_redirects – The maximum number of response redirects that should be followed, defaults to 20.

  • event_hooks – (Optional) mutable mapping of callable objects, callbacks when particular events

occur. Note: If using an asynchronous client the callables should be coroutines.

Parameters
  • transport – (Optional) transport class to use for sending eequests over the network.

  • app – (Optional) WSGI Server to dispatch requests too, rather than sending actual

network requests.

Parameters

trust_env – A bool to control if the the .netrc can be used to read for

basic auth credentials. This is True by default, in the event that trust_env=True and there are no Authorization HTTP Headers then Basic Auth will be used after reading credentials from the file.

Parameters

user_agent – (Optional) a str to set the user agent HTTP header on all requests

dispatched by the client. By default if omitted, restpite will create it’s own user agent header which includes the restpite version:

  • python-restpite/{restpite_version}

Parameters

event_subscribers – (Optional) user defined classes that implement the restpite.Notifyable

protocol. A hooking mechanism used by restpite to notify observers at various stage(s) of the HTTP communication process, allowing things like pre and post processing of requests and responses.

Parameters

base_url – (Optional) A str or restpite.URL instance used when

instantiating a client to prefix all issued requests with that url. For example for api testing you may have a base_url=”dev.product.com”, then subsequent requests can specify only “/{api_version}/users” resulting in all issued requests from the client talking to dev.product.com/v1/users.

get(url: Union[restpite._models.URL, str], *args, **kwargs)restpite._response.RestpiteResponse[source]

Issue a HTTP GET request

request(method: str, url: Union[restpite._models.URL, str], *, content: Optional[Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]] = None, data: Optional[Dict[Any, Any]] = None, files: Optional[Union[IO[str], IO[bytes], str, bytes, Tuple[Optional[str], Union[IO[str], IO[bytes], str, bytes]], Tuple[Optional[str], Union[IO[str], IO[bytes], str, bytes], Optional[str]]]] = None, json: Optional[Any] = None, params: Optional[Mapping[str, Union[str, int, float, bytes, Sequence[Union[str, int, float, bytes]]]]] = None, headers: Optional[Dict[Union[str, bytes], Union[str, bytes]]] = None, cookies: Optional[Union[http.cookiejar.CookieJar, Mapping[str, str]]] = None, auth: Optional[Union[Tuple[Union[str, bytes], Union[str, bytes]], Callable[[httpx.Request], httpx.Request], httpx.Auth]] = None, allow_redirects: bool = True, timeout: restpite._models.Timeout = Timeout(timeout=10.0))restpite._response.RestpiteResponse[source]

Responsible for managing the actual HTTP Request from request -> Response # TODO: Understand these types (args) # TODO: Understand the proper flow of the traffic through the underlying httpx library # TODO: Dispatching hooks mechanism around some of this # TODO: Hooks for raw request sending, raw response received, post RestpiteResponse, post RequestRequest # TODO: handlers = dispatching hook / calls to client code, adapter = transport adapters of requests # TODO: hooks need dispatched here multiple times, Hooks need invoked as well to permit control! # TODO: Built in capturing of all traffic, thinking simple restpite.json (configurable on|off) ? # TODO: !!! - Investigate auth UNSET != NoneType

class restpite.RestpiteResponse(httpx_response: httpx.Response)[source]
curlify()str[source]

Converts the object into a curl string, used for recreating the request

elapsed_time_was_less_than(seconds: int)restpite._response.RestpiteResponse[source]

Checks that the total time between sending the request and closing the response connection was less than seconds.

Parameters

seconds – Expected number of seconds to ensure the request -> response cycle was less than

encoding_was(expected_encoding: str)restpite._response.RestpiteResponse[source]

Checks that the response encoding was a particular type

had_client_error_status_code()restpite._response.RestpiteResponse[source]

Enforces that the response status code was a 4xx (Client Error) based code. Note we do a wide assertion of 400-499 but often these are limited to a very small subset of that range, should this change in future restpite will just work.

had_header(header: str)restpite._response.RestpiteResponse[source]

Checks the response HTTP headers for a match based on the HTTP header name. As per RFC 7231 HTTP header fields should be case-insensitive, by default the header instance here is a case insensitive dictionary to cater to that.

Parameters

header – The header name to lookup in the response HTTP headers

had_history_length(expected_length: int)restpite._response.RestpiteResponse[source]

Checks the the response chain was of expected_length length.

had_informative_status_code()restpite._response.RestpiteResponse[source]

Enforces that the response status code was a 1xx (Informational) based code. Note we do a wide assertion of 100-199 but often these are limited to a very small subset of that range, should this change in future restpite will just work.

had_json_payload()restpite._response.RestpiteResponse[source]

Checks that the response contained a json payload

had_redirect_status_code()restpite._response.RestpiteResponse[source]

Enforces that the response status code was a 3xx (Redirection) based code. Note we do a wide assertion of 300-399 but often these are limited to a very small subset of that range, should this change in future restpite will just work.

had_server_error_status_code()restpite._response.RestpiteResponse[source]

Enforces that the response status code was a 3xx (Server Error) based code. Note we do a wide assertion of 500-599 but often these are limited to a very small subset of that range, should this change in future restpite will just work.

had_status(expected_code: int)restpite._response.RestpiteResponse[source]

Given a status code, matches the response against it. :param expected_code: The expected status code, it is the callers responsibility here to provide a 3 digit status code.

had_success_status_code()restpite._response.RestpiteResponse[source]

Enforces that the response status code was a 2xx (Successful) based code. Note we do a wide assertion of 200-299 but often these are limited to a very small subset of that range, should this change in future restpite will just work.

had_total_number_of_bytes(num_bytes: int)restpite._response.RestpiteResponse[source]

Checks that the total number of bytes returned by the server was equal to num_bytes.

Parameters

num_bytes – Expected number of bytes in the response

validate(schema: Type[restpite._schema.RestpiteSchema], schema_kwargs: Dict[Any, Any])None[source]

Validate(s) response json against a pre-defined schema. This does not dump the response json through the schema, but checks for validation issues and raises a ValidationError upon failure.

was_http1()restpite._response.RestpiteResponse[source]

Checks that the servers response was HTTP1/1

was_http2()restpite._response.RestpiteResponse[source]

Checks that he servers response was truly HTTP/2

restpite.TIMEOUT_TYPES

alias of restpite._models.Timeout

restpite.codes

alias of restpite._status_codes.StatusCodes