frappex-client v0.1.1

Reference

API reference#

Generated from frappex_client 0.1.1. Everything listed here is importable from the top-level frappex-client package; modules whose names start with an underscore are private and may change in any release.

from frappex_client import Client, AsyncClient, TokenAuth, NotFoundError

Client#

class Client(
    base_url: str,
    auth: Auth | None = None,
    *,
    timeout: float | httpx.Timeout = 30.0,
    retry: RetryPolicy | None = None,
    verify: ssl.SSLContext | str | os.PathLike[str] | None = None,
    allow_insecure_http: bool = False,
    max_response_bytes: int = 67108864,
    headers: Mapping[str, str] | None = None,
    transport: httpx.BaseTransport | None = None,
)

Blocking client for one Frappe site.

Use it as a context manager so connections (and a password session) are closed when you are done:

with Client("https://erp.example.com", TokenAuth(key, secret)) as client:
    for todo in client.iter_list("ToDo", filters={"status": "Open"}):
        print(todo["name"])

Args

  • base_url: Root address of the site. Must be https:// unless allow_insecure_http is set.
  • auth: A frappex_client.TokenAuth, frappex_client.BearerAuth or frappex_client.PasswordAuth. Omit it for guest access: no credentials are sent, so only what the site opens to guests works, such as ping, public files and methods whitelisted with allow_guest.
  • timeout: Seconds allowed per request, or an httpx.Timeout.
  • retry: Retry rules; defaults to frappex_client.RetryPolicy.
  • verify: Path of a CA bundle or an ssl.SSLContext for sites with a private certificate. Certificate checks cannot be disabled.
  • allow_insecure_http: Permit http:// for a local development site.
  • max_response_bytes: Largest response body accepted, after decompression.
  • headers: Extra headers for every request, such as Host for a multi-site bench. Authorization and Cookie are refused.
  • transport: An httpx transport to use instead of the default, for tests or custom networking. It then owns TLS, so verify no longer applies.

Raises

  • ConfigurationError: A setting is malformed or unsafe.

ping#

def ping() -> str

Check that the site answers. Returns "pong".

get_logged_user#

def get_logged_user() -> str

Return the user the credentials belong to.

A cheap way to confirm that the credentials work.

get_list#

def get_list(
    doctype: str,
    *,
    fields: Sequence[str] | None = None,
    filters: Filters | None = None,
    or_filters: Filters | None = None,
    order_by: str | None = None,
    limit: int = 20,
    offset: int = 0,
    parent: str | None = None,
) -> list[Document]

Return one page of documents.

Args

  • doctype: DocType to list.
  • fields: Fields to return; the site returns only name if omitted.
  • filters: Conditions every row must meet.
  • or_filters: Conditions of which a row must meet at least one.
  • order_by: Sort clause, such as "modified desc".
  • limit: Maximum rows to return.
  • offset: Rows to skip.
  • parent: Parent DocType, required when listing a child table.
  • See: meth:iter_list to read every matching row.

iter_list#

def iter_list(
    doctype: str,
    *,
    fields: Sequence[str] | None = None,
    filters: Filters | None = None,
    or_filters: Filters | None = None,
    order_by: str | None = None,
    page_size: int = 100,
    parent: str | None = None,
) -> Iterator[Document]

Yield every matching document, fetching page_size rows at a time.

Rows are ordered by creation time unless order_by is given, so that documents edited during the iteration are not skipped or repeated. Rows created or deleted meanwhile can still shift pages.

get_doc#

def get_doc(doctype: str, name: str) -> Document

Return one document.

Raises

  • NotFoundError: No such document.

insert#

def insert(doctype: str, values: Mapping[str, Any]) -> Document

Create a document and return it as saved.

This request is never retried automatically, because a repeat could create a duplicate.

update#

def update(doctype: str, name: str, values: Mapping[str, Any]) -> Document

Change the given fields of a document and return it as saved.

delete#

def delete(doctype: str, name: str) -> None

Delete a document.

submit#

def submit(doctype: str, name: str) -> None

Submit a draft document.

cancel#

def cancel(doctype: str, name: str) -> None

Cancel a submitted document.

rename#

def rename(doctype: str, old_name: str, new_name: str, *, merge: bool = False) -> str

Rename a document and return its new name.

Args

  • doctype: DocType of the document.
  • old_name: Current name.
  • new_name: Name to give it.
  • merge: Merge into an existing document called new_name.

get_count#

def get_count(doctype: str, filters: Filters | None = None) -> int

Return how many documents match filters.

get_value#

def get_value(
    doctype: str,
    fieldname: str | Sequence[str],
    filters: Filters | str | None = None,
) -> Document | None

Return the requested fields of the first matching document.

Args

  • doctype: DocType to read.
  • fieldname: One field name or a list of them.
  • filters: Conditions, or a document name.

Returns

A mapping of field name to value, or None if nothing matches.

set_value#

def set_value(doctype: str, name: str, values: Mapping[str, Any]) -> Document

Set fields on a document and return it as saved.

call#

def call(
    method: str,
    params: Mapping[str, Any] | None = None,
    *,
    http_method: Literal['GET', 'POST'] = 'POST',
) -> Any

Call a whitelisted server method and return its result.

Args

  • method: Dotted path, such as "myapp.api.get_summary".
  • params: Arguments for the method.
  • http_method: "POST" (default) sends the arguments as JSON and is never retried. Use "GET" for a read-only method that is safe to repeat.

upload_file#

def upload_file(
    filename: str,
    content: bytes,
    *,
    is_private: bool = True,
    doctype: str | None = None,
    docname: str | None = None,
    fieldname: str | None = None,
    folder: str | None = None,
) -> Document

Upload a file and return its File document.

Files are private unless is_private=False is passed: a public file can be fetched by anyone who has its URL.

Args

  • filename: Name to store the file under.
  • content: File contents.
  • is_private: Keep the file behind the site's permissions.
  • doctype: DocType of the document to attach the file to.
  • docname: Name of the document to attach the file to.
  • fieldname: Attach field on that document to fill in.
  • folder: Folder in the file manager; the site defaults to Home.

download_to#

def download_to(file_url: str, target: BinaryIO, *, max_bytes: int | None = None) -> int

Stream a file from the site into target.

Args

  • file_url: Site-relative location, such as /private/files/a.pdf (the file_url field of a File document).
  • target: Writable binary file object.
  • max_bytes: Stop with frappex_client.ResponseTooLargeError after this many bytes; unlimited when omitted.

Returns

Number of bytes written. A download is not retried, since part of it may already be written.

download#

def download(file_url: str) -> bytes

Return a file's contents, up to max_response_bytes.

Use download_to for large files.

AsyncClient#

class AsyncClient(
    base_url: str,
    auth: Auth | None = None,
    *,
    timeout: float | httpx.Timeout = 30.0,
    retry: RetryPolicy | None = None,
    verify: ssl.SSLContext | str | os.PathLike[str] | None = None,
    allow_insecure_http: bool = False,
    max_response_bytes: int = 67108864,
    headers: Mapping[str, str] | None = None,
    transport: httpx.AsyncBaseTransport | None = None,
)

Asyncio client for one Frappe site.

It has the same methods as frappex_client.Client, awaited. Use it as an async context manager so connections (and a password session) are closed when you are done:

async with AsyncClient("https://erp.example.com", TokenAuth(key, secret)) as client:
    async for todo in client.iter_list("ToDo", filters={"status": "Open"}):
        print(todo["name"])

Args

  • base_url: Root address of the site. Must be https:// unless allow_insecure_http is set.
  • auth: A frappex_client.TokenAuth, frappex_client.BearerAuth or frappex_client.PasswordAuth. Omit it for guest access: no credentials are sent, so only what the site opens to guests works, such as ping, public files and methods whitelisted with allow_guest.
  • timeout: Seconds allowed per request, or an httpx.Timeout.
  • retry: Retry rules; defaults to frappex_client.RetryPolicy.
  • verify: Path of a CA bundle or an ssl.SSLContext for sites with a private certificate. Certificate checks cannot be disabled.
  • allow_insecure_http: Permit http:// for a local development site.
  • max_response_bytes: Largest response body accepted, after decompression.
  • headers: Extra headers for every request, such as Host for a multi-site bench. Authorization and Cookie are refused.
  • transport: An async httpx transport to use instead of the default, for tests or custom networking. It then owns TLS, so verify no longer applies.

Raises

  • ConfigurationError: A setting is malformed or unsafe.

Every method below has the same arguments and behaviour as on Client; call it with await (and async for for iter_list).

Authentication#

TokenAuth#

class TokenAuth(api_key: str, api_secret: str | Secret)

Authenticate with a user's API key and API secret.

This is the recommended method for server-to-server use: generate the pair under User > Settings > API Access on the Frappe site.

BearerAuth#

class BearerAuth(token: str | Secret)

Authenticate with an OAuth 2 access token issued by the Frappe site.

PasswordAuth#

class PasswordAuth(username: str, password: str | Secret)

Authenticate with a username and password (cookie session).

The client logs in on its first request and logs out when closed. Prefer TokenAuth for unattended programs: it needs no login round trip and the key can be revoked without changing the user's password.

Secret#

class Secret(value: str | Secret)

A string that never shows its value unless asked to.

repr and str return a mask. Call reveal at the single point where the value has to go on the wire.

RetryPolicy#

class RetryPolicy(
    max_attempts: int = 3,
    backoff_base: float = 0.5,
    backoff_max: float = 8.0,
    max_retry_after: float = 30.0,
    retry_statuses: frozenset[int] = <factory>,
)

When and how long to wait before repeating a failed request.

Only requests that are safe to repeat are retried:

  • GET requests after a connection failure, timeout or 502/503/504.
  • Any request after HTTP 429, because Frappe rejects a rate-limited request before running it.

A write (POST/PUT/DELETE) is never repeated after a network failure or 5xx, since the first attempt may have been applied.

Attributes

  • max_attempts: Total tries including the first. 1 disables retries.
  • backoff_base: First delay in seconds; it doubles on each attempt.
  • backoff_max: Upper bound for a computed delay, in seconds.
  • max_retry_after: Longest server-requested wait that will be honoured. A longer Retry-After raises instead of blocking the caller.

Exceptions#

FrappexError
    APIError
        AuthenticationError
        ConflictError
        NotFoundError
        PermissionDeniedError
        RateLimitError
        ServerError
        ValidationError
    ConfigurationError
    ResponseTooLargeError
    TransportError
        RequestTimeoutError
    UnexpectedResponseError

FrappexError#

Subclass of Exception.

Base class for every error raised by frappex-client.

APIError#

Subclass of FrappexError.

The Frappe site rejected the request.

Attributes

  • status_code: HTTP status of the response.
  • exc_type: Name of the server-side exception class, when reported. Frappe 14 does not always report it, so it can be None.
  • server_messages: Human-readable messages the server attached.
  • traceback: Server traceback, when the site exposes one. It is kept off str(error) on purpose so it does not leak into logs.

AuthenticationError#

Subclass of APIError.

Credentials are missing, wrong or expired (HTTP 401).

ConfigurationError#

Subclass of FrappexError, ValueError.

The client or a call was given an unusable or unsafe argument.

ConflictError#

Subclass of APIError.

The write clashes with existing data, such as a duplicate (HTTP 409).

NotFoundError#

Subclass of APIError.

The document, DocType or method does not exist (HTTP 404).

PermissionDeniedError#

Subclass of APIError.

The authenticated user may not perform the action (HTTP 403).

RateLimitError#

Subclass of APIError.

The site is rate limiting the caller (HTTP 429).

Attributes

  • retry_after: Seconds the server asked the caller to wait, if stated.

RequestTimeoutError#

Subclass of TransportError.

The request exceeded its timeout.

ResponseTooLargeError#

Subclass of FrappexError.

The response body exceeded the configured size limit.

ServerError#

Subclass of APIError.

The site failed while handling the request (HTTP 5xx).

TransportError#

Subclass of FrappexError.

The request never produced an HTTP response (DNS, TLS, connection).

UnexpectedResponseError#

Subclass of FrappexError.

The server answered with something that is not a Frappe API reply.

Typical causes are a redirect (never followed, so credentials stay on the configured host), an HTML page from a proxy, or a wrong base URL.

ValidationError#

Subclass of APIError.

The site refused the data as invalid (HTTP 417 and other 4xx).

Types#

Name Meaning
Document dict[str, Any]: a document as the API returns it.
Filters {"status": "Open"} or [["status", "=", "Open"]].
Auth TokenAuth | BearerAuth | PasswordAuth.

Found a mistake? Open an issue.