Reference
Meatie is a metaprogramming library for building HTTP REST API clients based on methods annotated with type hints.
AsyncContext
Bases: Generic[ResponseBodyType]
Stores context for processing an asynchronous HTTP request.
Source code in src/meatie/aio/descriptor.py
__init__(client, operators, request)
Initializes the context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
BaseAsyncClient
|
HTTP client instance used for sending the HTTP request. |
required |
operators
|
list[AsyncOperator[ResponseBodyType]]
|
list of operators that should be applied on the HTTP request and its response. |
required |
request
|
Request
|
the HTTP request to be sent. |
required |
Source code in src/meatie/aio/descriptor.py
proceed()
async
One method call will apply one operator on the HTTP request.
Operators are applied on HTTP requests according to order defined in the context object. HTTP responses are processed in the opposite order.
Source code in src/meatie/aio/descriptor.py
AsyncEndpointDescriptor
Bases: Generic[PT, ResponseBodyType]
Class descriptor for calling HTTP endpoints asynchronously.
Source code in src/meatie/aio/descriptor.py
__init__(template, response_decoder)
Creates an asynchronous endpoint descriptor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
RequestTemplate[Any]
|
the template for building HTTP requests to send to the given endpoint. |
required |
response_decoder
|
TypeAdapter[ResponseBodyType]
|
the adapter for decoding the HTTP responses returned from the endpoint. |
required |
Source code in src/meatie/aio/descriptor.py
register_operator(priority, operator)
Registers an operator to apply on an HTTP request or response.
Meatie uses the following priorities for the built-in operators
- 20 - caching
- 40 - retry
- 60 - rate limiting
- 80 - authentication
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
priority
|
int
|
the priority of the operator, operators are applied in ascending order of priority. |
required |
operator
|
AsyncOperator[ResponseBodyType]
|
the operator to apply. |
required |
Source code in src/meatie/aio/descriptor.py
AsyncResponse
Bases: Protocol
Interface for an asynchronous HTTP response.
Source code in src/meatie/types.py
status
property
Get HTTP status code.
Returns:
| Type | Description |
|---|---|
int
|
HTTP status code. |
json()
async
Reads the response body and decodes it to JSON.
Returns:
| Type | Description |
|---|---|
Any
|
Response body as JSON. |
Raises:
| Type | Description |
|---|---|
ResponseError
|
If an error occurs while reading the response body. |
ParseResponseError
|
If an error occurs while parsing the response body. |
Source code in src/meatie/types.py
read()
async
Reads the response body and returns it as bytes without decoding.
Returns:
| Type | Description |
|---|---|
bytes
|
Response body as bytes. |
Raises:
| Type | Description |
|---|---|
ResponseError
|
If an error occurs while reading the response body. |
text()
async
Reads the response body and decodes it to a string using encoding declared in the Content-Type response header.
Returns:
| Type | Description |
|---|---|
str
|
Response body as string. |
Raises:
| Type | Description |
|---|---|
ResponseError
|
If an error occurs while reading the response body. |
Source code in src/meatie/types.py
BaseAsyncClient
Base class for the integration with asynchronous HTTP client libraries.
Source code in src/meatie/aio/client.py
__init__(local_cache=None, limiter=None)
Creates a BaseAsyncClient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_cache
|
Optional[Cache]
|
Cache implementation for storing the HTTP responses. |
None
|
limiter
|
Optional[Limiter]
|
Rate limiter used for throttling the rate of sending the HTTP requests. |
None
|
Source code in src/meatie/aio/client.py
authenticate(request)
async
Method called by the Meatie before sending an HTTP request for an endpoint marked as private.
The method could be used to set the Authorization header or sign the HTTP request and using API keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
HTTP request object. |
required |
Source code in src/meatie/aio/client.py
send(request)
abstractmethod
async
Sends an HTTP request using the underlying HTTP client library.
Returns:
| Type | Description |
|---|---|
Any
|
HTTP response object from the underlying HTTP client library. |
BaseClient
Base class for the integration with HTTP client libraries.
Source code in src/meatie/client.py
__init__(local_cache=None, limiter=None)
Creates a BaseClient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_cache
|
Optional[Cache]
|
Cache implementation for storing the HTTP responses. |
None
|
limiter
|
Optional[Limiter]
|
Rate limiter used for throttling the rate of sending the HTTP requests. |
None
|
Source code in src/meatie/client.py
authenticate(request)
Method called by the Meatie before sending an HTTP request for an endpoint marked as private.
The method could be used to set the Authorization header or sign the HTTP request and using API keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
HTTP request object. |
required |
Source code in src/meatie/client.py
send(request)
abstractmethod
Sends an HTTP request using the underlying HTTP client library.
Returns:
| Type | Description |
|---|---|
Any
|
HTTP response object from the underlying HTTP client library. |
Context
Bases: Generic[ResponseBodyType]
Stores context for processing an HTTP request.
Source code in src/meatie/descriptor.py
__init__(client, operators, request)
Initializes the context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
BaseClient
|
HTTP client instance used for sending the HTTP request. |
required |
operators
|
list[Operator[ResponseBodyType]]
|
list of operators that should be applied on the HTTP request and its response. |
required |
request
|
Request
|
the HTTP request to be sent. |
required |
Source code in src/meatie/descriptor.py
proceed()
One method call will apply one operator on the HTTP request.
Operators are applied on HTTP requests according to order defined in the context object. HTTP responses are processed in the opposite order.
Source code in src/meatie/descriptor.py
EndpointDescriptor
Bases: Generic[PT, ResponseBodyType]
Class descriptor for calling HTTP endpoints.
Source code in src/meatie/descriptor.py
__init__(template, response_decoder)
Creates an endpoint descriptor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
RequestTemplate[Any]
|
the template for building HTTP requests to send to the given endpoint. |
required |
response_decoder
|
TypeAdapter[ResponseBodyType]
|
the adapter for decoding the HTTP responses returned from the endpoint. |
required |
Source code in src/meatie/descriptor.py
register_operator(priority, operator)
Registers an operator to apply on an HTTP request or response.
Meatie uses the following priorities for the built-in operators
- 20 - caching
- 40 - retry
- 60 - rate limiting
- 80 - authentication
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
priority
|
int
|
the priority of the operator, operators are applied in ascending order of priority. |
required |
operator
|
Operator[ResponseBodyType]
|
the operator to apply. |
required |
Source code in src/meatie/descriptor.py
HttpStatusError
Bases: ResponseError
Dedicated for handling HTTP status errors. Currently, it is not raised by the Meatie library.
Source code in src/meatie/error.py
MeatieError
Bases: Exception
Base class for all Meatie exceptions.
Check __cause__ for the original exception raised by the underlying HTTP client library.
ParseResponseError
Bases: ResponseError
Raised when the response body cannot be parsed to a JSON object.
Source code in src/meatie/error.py
__init__(text, response)
Creates a ParseResponseError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
response body in the text format. |
required |
response
|
Union[Response, AsyncResponse]
|
HTTP response object. |
required |
Source code in src/meatie/error.py
ProxyError
Bases: TransportError
Raised when a proxy error occurs.
Request failed due to a proxy error, i.e., the proxy server is refusing connections, the proxy server does not accept CONNECT requests.
RateLimitExceeded
Request
dataclass
Specification of an HTTP request.
Value types used for headers and query parameters must be supported by the underlying HTTP client library.
Source code in src/meatie/types.py
RequestError
Bases: MeatieError
Raised when the request cannot be sent by the underlying HTTP client library, i.e., invalid URL, unsupported protocol.
There is no point in retrying the operation.
Response
Bases: Protocol
Interface for an HTTP response.
Source code in src/meatie/types.py
status
property
Get HTTP status code.
Returns:
| Type | Description |
|---|---|
int
|
HTTP status code. |
json()
Reads the response body and decodes it to JSON.
Returns:
| Type | Description |
|---|---|
Any
|
Response body as JSON. |
Raises:
| Type | Description |
|---|---|
ResponseError
|
If an error occurs while reading the response body. |
ParseResponseError
|
If an error occurs while parsing the response body. |
Source code in src/meatie/types.py
read()
Reads the response body and returns it as bytes without decoding.
Returns:
| Type | Description |
|---|---|
bytes
|
Response body as bytes. |
Raises:
| Type | Description |
|---|---|
ResponseError
|
If an error occurs while reading the response body. |
text()
Reads the response body and decodes it to a string using encoding declared in the Content-Type response header.
Returns:
| Type | Description |
|---|---|
str
|
Response body as string. |
Raises:
| Type | Description |
|---|---|
ResponseError
|
If an error occurs while reading the response body. |
Source code in src/meatie/types.py
ResponseError
Bases: MeatieError
Raised when the response body cannot be read or decoded to a string.
Source code in src/meatie/error.py
__init__(response)
Creates a ResponseError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
Union[Response, AsyncResponse]
|
HTTP response object. |
required |
RetryError
Bases: MeatieError
Raised when all retry attempts have been exhausted.
ServerError
Bases: TransportError
Raised when a server or a network error occurs.
HTTP request failed because of the server-side error i.e., server violated HTTP protocol by returning a corrupted response, server disconnected the connection prematurely, server certificate is invalid, cannot establish a connection with the server.
Source code in src/meatie/error.py
Timeout
Bases: ServerError
Raised when a request times out, i.e., connection timeout, read timeout, write timeout.
TransportError
Bases: MeatieError
Raised in response to a transport error, i.e., too many redirects, a protocol error, a network error.
endpoint(path, *args, method=None)
Class descriptor for decorating methods that represent API endpoints.
Inspects the method signature to create an endpoint descriptor that can be used to make HTTP requests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
URL path template. It should start with |
required |
args
|
Any
|
options to customize the endpoint behaviour, such as caching, rate limiting, retries, and authentication. |
()
|
method
|
Optional[Method]
|
HTTP method for making the request. Inferred from the method name by default. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[PT, T]], Callable[PT, T]]
|
A decorator that preserves the callable signature of the decorated method. |
Callable[[Callable[PT, T]], Callable[PT, T]]
|
For async methods, returns a callable with Awaitable return type. |
Callable[[Callable[PT, T]], Callable[PT, T]]
|
For sync methods, returns a callable with direct return type. |
Examples:
from typing import Annotated
from aiohttp import ClientSession
from meatie import api_ref, endpoint
from meatie_aiohttp import Client
class JsonPlaceholderClient(Client):
def __init__(self) -> None:
super().__init__(ClientSession(base_url="https://jsonplaceholder.typicode.com"))
@endpoint("/todos")
async def get_todos(self, user_id: Annotated[int, api_ref("userId")] = None) -> list[dict]: ...
@endpoint("/users/{user_id}/todos")
async def get_todos_by_user(self, user_id: int) -> list[dict]: ...
Source code in src/meatie/endpoint.py
ApiReference
ApiReference stores additional settings that customize handling of a parameter in the HTTP request.
Source code in src/meatie/api_reference.py
__init__(name=None, fmt=None, unwrap=None)
Create an ApiReference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Optional[str]
|
the name of the query parameter in the HTTP request, the name of the Python parameter is used as default. |
None
|
fmt
|
Optional[Callable[[Any], Any]]
|
conversion function to apply on the parameter value before sending the HTTP request |
None
|
unwrap
|
Optional[Callable[[Any], dict[str, Any]]]
|
conversion function to apply on the parameter value before sending the HTTP request. In contrast to the fmt function, which produces a single value, the unwrap function returns a dictionary of key value pairs. |
None
|
Source code in src/meatie/api_reference.py
from_signature(parameter, resolved_annotation=None)
classmethod
Create an ApiReference from the Python method parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter
|
Parameter
|
The parameter from the function signature. |
required |
resolved_annotation
|
Optional[Any]
|
The resolved type hint (from get_type_hints with include_extras=True). If provided, this is tried first, then falls back to parameter.annotation. |
None
|
Source code in src/meatie/api_reference.py
BodyOption
Customize handling of HTTP response body, such as text decoding, parsing JSON and detecting errors.
Source code in src/meatie/option/body_option.py
__call__(descriptor)
Apply the body option to the endpoint descriptor.
Source code in src/meatie/option/body_option.py
__init__(json=None, text=None, error=None)
Creates a new body option.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json
|
Optional[Union[Callable[[Any], Any], Callable[[Any], Awaitable[Any]]]]
|
function to parse JSON from the HTTP response body. The default is to rely on the behaviour of the HTTP client library. |
None
|
text
|
Optional[Union[Callable[[Any], str], Callable[[Any], Awaitable[str]]]]
|
function to decode text from the HTTP response body. The default is to rely on the behaviour of the HTTP client library. |
None
|
error
|
Optional[Union[Callable[[Response], Optional[Exception]], Callable[[AsyncResponse], Awaitable[Optional[Exception]]]]]
|
function to detect an error in the HTTP response. The default is to do nothing. |
None
|
Source code in src/meatie/option/body_option.py
BaseAsyncOperator
Bases: Generic[T]
Base class for asynchronous cache operators. Saves the value returned from the endpoint in cache.
Source code in src/meatie/option/cache_option.py
BaseOperator
Bases: Generic[T]
Base class for cache operators. Saves the value returned from the endpoint in cache.
Source code in src/meatie/option/cache_option.py
CacheOption
Configure caching of endpoint call results.
Source code in src/meatie/option/cache_option.py
priority
property
Returns: the priority of the cache operator.
__call__(descriptor)
Apply the cache option to the endpoint descriptor.
Source code in src/meatie/option/cache_option.py
__init__(ttl, shared=False)
Creates a new cache option.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl
|
Duration
|
the time-to-live of the cache entry in seconds |
required |
shared
|
bool
|
if set to False (default) the cache entry will be stored in the local cache owned by the client instance. Records cached by another client instance will not be visible. Otherwise, if set to True, all client that are instances of the same Python class will share the same cache. |
False
|
Source code in src/meatie/option/cache_option.py
LocalAsyncOperator
Bases: BaseAsyncOperator[T]
Asynchronous cache operator that stores the value returned from the endpoint in the local cache owned by the client instance.
Source code in src/meatie/option/cache_option.py
LocalOperator
Bases: BaseOperator[T]
Cache operator that stores the value returned from the endpoint in the local cache owned by the client instance.
Source code in src/meatie/option/cache_option.py
SharedAsyncOperator
Bases: BaseAsyncOperator[T]
Asynchronous cache operator that stores the value returned from the endpoint in the cache shared by all client instances of the same Python class.
Source code in src/meatie/option/cache_option.py
SharedOperator
Bases: BaseOperator[T]
Cache operator that stores the value returned from the endpoint in the cache shared by all client instances of the same Python class.
Source code in src/meatie/option/cache_option.py
AsyncLimitOperator
Bases: Generic[T]
Delays the endpoint calls that exceed the rate limit.
Source code in src/meatie/option/limit_option.py
__init__(tokens, sleep_func)
Creates a new limit operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tokens
|
number of tokens consumed by the endpoint call |
required |
sleep_func
|
Callable[[Duration], Awaitable[None]]
|
the sleep function to use (default: asyncio.sleep). |
required |
Source code in src/meatie/option/limit_option.py
LimitOperator
Bases: Generic[T]
Delays the endpoint calls that exceed the rate limit.
Source code in src/meatie/option/limit_option.py
__init__(tokens, sleep_func)
Creates a new limit operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tokens
|
number of tokens consumed by the endpoint call |
required |
sleep_func
|
Callable[[Duration], None]
|
the sleep function to use (default: time.sleep). |
required |
Source code in src/meatie/option/limit_option.py
LimitOption
Configure the rate limit for the endpoint calls.
Source code in src/meatie/option/limit_option.py
priority
property
Returns: the priority of the limit operator.
__call__(descriptor)
Apply the rate limit option to the endpoint descriptor.
Source code in src/meatie/option/limit_option.py
__init__(tokens, sleep_func=None)
Creates a new rate limit option.
The number of available tokens at a given time are controlled by the rate limiter instance used by the client. Meatie provides leaky bucket rate limiter implementation with constant replenishment rate and burst size. See meatie.Limiter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tokens
|
number of tokens consumed by the endpoint call |
required |
sleep_func
|
Union[Callable[[float], Union[None, Awaitable[None]]], None]
|
the sleep function to use. Default behaviour is to rely on the Python standard library functions: time.sleep and asyncio.sleep for async functions. |
None
|
Source code in src/meatie/option/limit_option.py
PrivateOption
Include additional information in the HTTP request before calling the API endpoint.
Instructs Meatie library to call the authenticate method of the client instance with the HTTP request as the argument.
Popular use cases are to set the Authorization header or sign the HTTP request using API keys before calling the API endpoint.
Source code in src/meatie/option/private_option.py
priority
property
Returns: the priority of the private operator.
__call__(descriptor)
Apply the private option to the endpoint descriptor.
Source code in src/meatie/option/private_option.py
AsyncRetryOperator
Bases: Generic[T]
Executes the retry strategy for asynchronous endpoint calls.
Source code in src/meatie/option/retry_option.py
__init__(on, wait, stop, sleep_func)
Creates a new retry operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
Condition
|
function that returns True if the operation should be retried. |
required |
wait
|
WaitFunc
|
function that returns the duration to wait before the next retry attempt. |
required |
stop
|
Condition
|
function that returns True if the operation should be aborted. |
required |
sleep_func
|
Callable[[Duration], Awaitable[None]]
|
the sleep function to use. |
required |
Source code in src/meatie/option/retry_option.py
RetryOperator
Bases: Generic[T]
Executes the retry strategy for synchronous endpoint calls.
Source code in src/meatie/option/retry_option.py
__init__(on, wait, stop, sleep_func)
Creates a new retry operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
Condition
|
function that returns True if the operation should be retried. |
required |
wait
|
WaitFunc
|
function that returns the duration to wait before the next retry attempt. |
required |
stop
|
Condition
|
function that returns True if the operation should be aborted. |
required |
sleep_func
|
Callable[[Duration], None]
|
the sleep function to use. |
required |
Source code in src/meatie/option/retry_option.py
RetryOption
Configure the strategy for retrying the endpoint calls that failed.
Source code in src/meatie/option/retry_option.py
priority
property
Returns: the priority of the retry operator.
__call__(descriptor)
Apply the retry option to the endpoint descriptor.
Source code in src/meatie/option/retry_option.py
__init__(on=has_status(HTTPStatus.TOO_MANY_REQUESTS), wait=zero, stop=never, sleep_func=None)
Creates a new retry option.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
Condition
|
function that returns True if the operation should be retried. Default behaviour is to retry on the HTTP Too Many Requests (429) status code. |
has_status(TOO_MANY_REQUESTS)
|
wait
|
WaitFunc
|
function that returns the duration to wait before the next retry attempt. Default behaviour is no to wait. |
zero
|
stop
|
Condition
|
function that returns True if the operation should be aborted. Default behaviour is never to stop. |
never
|
sleep_func
|
Union[Callable[[Duration], None], Callable[[Duration], Awaitable[None]], None]
|
the sleep function to use. Default behaviour is to rely on the Python standard library functions: time.sleep and asyncio.sleep for async functions. |
None
|
See Also
meatie.has_status: retry on a specific HTTP status code meatie.has_exception_type: retry on a specific exception type meatie.has_exception_cause_type: retry if a specific exception type is present in the exception chain meatie.zero: do not wait meatie.fixed: wait a fixed amount of seconds meatie.uniform: wait a random amount of seconds in the given time range meatie.exponential: keep increasing the wait time exponentially meatie.jitter: add a random jitter to the wait time meatie.never: never stop meatie.after: stop after deadline in seconds meatie.after_attempt: stop after a number of attempts