Skip to content

API Documentation

Service

__init__(name, url, *, description=None, resources=None, exception_handlers=None, config=None)

A python class to define a service. Contains a base url for the main HTTP service. Resources can be added to a service.

Parameters:

Name Type Description Default
name str

Name of the service

required
url str

Base url of the service

required
resources Optional[list[Resource]]

A list of resources provided by the service

None
exception_handlers ExceptionHandlers | None

A dictionary of exception handlers for the service

None
config Optional[ArrestConfig]

A dictionary of configuration options for the service

None

add_resource(resource)

Add a new resource to the service. Config fields passed here override the Service-level defaults for this resource only.

Resource

A python class used to define a RESTful resource.

Usage
>>> from arrest import Resource

>>> user_resource = Resource(name="user", route="/users", handlers=[("GET", "/")])

Handlers can be provided as a list of tuple, dictionary or instances of ResourceHandler

If provided as a dict or ResourceHandler, the keys / fields have to be set according to the ResourceHandler definiion.

If provided as a tuple, at minimum 2 entries (method, route) or a maximum of 5 entries (method, route, request, response, callback) can be defined.

__init__(name=None, *, route, response_model=None, handlers=None, config=None)

Parameters:

Name Type Description Default
name Optional[str]

Unique name of the resource

None
route Optional[str]

Unique route to the resource

required
response_model Optional[Any]

Pydantic datamodel to wrap the json response

None
handlers list[ResourceHandlerType] | None

List of handlers

None
config Optional[ArrestConfig]

An ArrestConfig instance

None

request(method, path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes an HTTP request against a handler route

Usage
>>> user_resource.user.request(method="GET")

Parameters:

Name Type Description Default
method Methods

The HTTP method for the request

required
path str

Path to a handler specified in the resource

required
request Union[BaseModel, Mapping[str, Any], None]

A pydantic object containing the necessary fields to make an http request to the handler url

Must match the corresponding handler.request pydantic model

None
headers Optional[Mapping[str, str]]

A multi-dict or httpx.Headers containing additional header key-value pairs

None
query Optional[Mapping[str, str]]

A multi-dict or httpx.QueryParams containing additional query-param key-value pairs

None
cookies Optional[dict[str, str]]

Additional cookie key-value pairs for this call.

None
timeout Optional[float]

Override the default timeout for this call.

None
follow_redirects Optional[bool]

Override redirect-following for this call.

None
raise_for_status Optional[bool]

If True, non-2xx responses raise ArrestHTTPException instead of returning a Response (legacy behaviour).

None
**kwargs

Keyword-arguments matching the path params, if any

{}

Returns:

Name Type Description
Response Response[Any]

A Response[Any] wrapping the parsed data, status code, headers, and raw httpx.Response. Callbacks receive and may return Response[Any].

get(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP GET request

see request

post(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP POST request

see request

put(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP PUT request

see request

patch(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP PATCH request

see request

delete(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP DELETE request

see request

head(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP HEAD request

see request

options(path, request=None, headers=None, query=None, cookies=None, timeout=None, follow_redirects=None, raise_for_status=None, **kwargs) async

Makes a HTTP OPTIONS request

see request

handler(path)

Decorator to bind a custom handler to the resource

Parameters:

Name Type Description Default
path str

path relative to the current resource

required

Returns:

Type Description
Any

Any

ArrestConfig

Per-request defaults that merge through the hierarchy chain.

Priority (highest to lowest): per-call kwargs > handler config > resource config > service config

Dict fields (headers, cookies, params) merge additively. All other fields, including httpx client inputs and client, are overridden by the highest-priority non-None value.

httpx_args()

Return only fields valid as httpx.AsyncClient / request kwargs.

Excludes arrest-internal fields (max_retries) and user-facing flags that are not httpx constructor args (client, raise_for_status).

merge(overrides)

Return a new config with overrides layered on top of self.

All httpx client arguments and Arrest-specific settings live here. Pass an instance to Service(...), Resource(...), or merge per-call via request(...).

Key fields:

Field Type Description
headers dict[str, str] Default request headers (merged additively)
cookies dict[str, Any] Default request cookies (merged additively)
params dict[str, Any] Default query params (merged additively)
timeout float \| None Request timeout in seconds
auth Any \| None Authentication credentials
follow_redirects bool \| None Whether to follow redirects
raise_for_status bool \| None If True, non-2xx raises ArrestHTTPException
client AsyncClient \| None A shared httpx.AsyncClient instance
max_retries int \| None Arrest-level retry count (tenacity)
verify SSLContext \| bool \| str \| None SSL verification
cert CertTypes \| None SSL client certificate
http2 bool \| None Enable HTTP/2
proxy ProxyTypes \| None Proxy configuration
mounts Mapping[str, AsyncBaseTransport] \| None Transport mounts
limits Limits \| None Connection pool limits
transport AsyncBaseTransport \| None Custom transport
trust_env bool \| None Trust environment variables
event_hooks Mapping[str, list[Callable]] \| None Request/response event hooks
default_encoding str \| Callable \| None Default response encoding

ResourceHandler

Bases: BaseModel

A pydantic class defining a resource handler

Parameters:

Name Type Description Default
method Methods

HTTP Method for the handler

required
route str

Unique path to the handler from its parent resource

required
request T

Python type to validate the request with

required
response T

Python type to deserialize the HTTP response

required
callback Callable

A callable (sync or async) to execute with the HTTP response

required
headers dict

default Headers for the handlers, can be overridden by runtime headers

required
tool_meta

(ToolMeta, optional): optional metadata for tool definitions, used during tool registration

required

__extract_path_params(path)

Positionally match path's segments as a literal prefix of this handler's own template. A template placeholder at a position where path supplies a value fills that param; a template placeholder beyond path's length is left for kwargs to fill instead (this is what lets a short hint path like "/posts" discover a longer nested route via kwargs). Returns (path_format, params, extension), where extension is how many template segments past path's own length remain.

build_path(**path_params)

Build the concrete path for this handler by substituting path_params into its route template, e.g. for a handler bound to /{user_id}/tasks, build_path(user_id="abc") returns /abc/tasks.

Returns:

Name Type Description
str str

The concrete path with all placeholders substituted with

Raises:

Type Description
RuntimeError

If the handler has not been bound to a resource yet, and thus has no compiled path format available.

ValueError

If any placeholders in the route template are not provided in path_params.

match(method, path, **kwargs)

Resolve path (plus kwargs) against this handler's route. Resource.get_matching_handler uses the returned extension to pick the closest match when routes overlap as prefixes of each other, e.g. /{id} vs /{id}/tasks.

Parameters:

Name Type Description Default
method Methods

HTTP method the request was made with

required
path str

Path to match, e.g. /{id}/tasks or a concrete path

required
**kwargs

Values for any route placeholders path doesn't cover

{}

Returns:

Type Description
tuple[str, int] | None

tuple[str, int] | None: (path, extension) if path and kwargs together resolve this handler's route, else None. extension counts template segments past path that had to come from kwargs (0 for an exact match).

Exceptions

ArrestError

Bases: BaseException

used in error situations

base class for all Exception. Used in situations that are not one of the following

RequestError

Bases: ArrestError

raised for transport-level failures (timeout, DNS errors, connection refused).

  • .message — str description of the error

ArrestHTTPException

Bases: ArrestError

raised for non-2xx HTTP responses when raise_for_status=True is set.

  • .status_code — int HTTP status code
  • .data — Any response body (JSON dict, XML model, string, etc.)

NotFoundException

Bases: ArrestError

base class for all NotFound-type exceptions

HandlerNotFound

raised when no matching handler is found for the requested path

  • .message - str

  • .message - str

ConversionError

Bases: ArrestError

raised when Arrest cannot convert path-parameter type using any of the existing converters

OpenAPIGenerator

__init__(*, url, output_path, dir_name=None)

class for generating Arrest services, resources and schema components from OpenAPI specification (>= v3.0) Generates three files:

  1. models.py (contains OpenAPI Schema component definitions)
  2. resources.py (Arrest Resources based on the path items)
  3. services.py (Arrest Services using the resources)

Parameters:

Name Type Description Default
url str

an HTTP url or full path to the OpenAPI specification (json or yaml)

required
output_path str

path where the generated files will be saved

required
dir_name Optional[str]

(optional) specify the folder name containing the files

None

generate_schema(fmt=None, silent=False)

Generates the boilerplate files against an OpenAPI Spec

Parameters:

Name Type Description Default
fmt Optional[Format]

specification format [json, yaml, yml]

None

Raises:

Type Description
ArrestError

if the output path does not exist

ArrestToolset

See the pydantic-ai toolset guide for a full walkthrough.

Bases: AbstractToolset[AgentDepsT]

__init__(service, *, id=None, include=None, exclude=None, tool_max_retries=None, config=None, retry_on_errors=None)

get_tools(ctx) async

call_tool(name, tool_args, ctx, tool) async

ToolMeta

Tool metadata for per-handler config overrides.

Parameters:

Name Type Description Default
name str

overrides the auto-generated tool name. Defaults to None, in which case a name is derived from the resource, method, and route.

None
description str

overrides the auto-generated tool description. Defaults to None, in which case a description is derived from the handler's method and route.

None
include bool

whether this handler is registered as a tool at all. Defaults to True.

True
strict bool

whether the tool should be invoked in strict mode. Defaults to None, which defers to the model/framework default.

None
metadata dict

free-form metadata attached to the tool, for future use. Defaults to None.

None
max_items int

maximum number of items returned before truncation kicks in. Only applies to list responses. Defaults to None (no truncation).

None
on_truncate note | 'raise'

what happens when a response exceeds max_items: "note" returns a truncated payload annotated with truncation metadata; "raise" fails the tool call instead, prompting the model to narrow its query. Defaults to "note".

'note'