Skip to main content

frappex-client

CI Integration Security CodeQL OpenSSF Scorecard License: MIT

A typed REST client for Frappe and ERPNext sites, with a blocking client and an asyncio client that share one implementation.

Documentation: https://frappex-client.zeal.ninja: guides, recipes and the full API reference.

frappex-client is an independent community project. It is not affiliated with or endorsed by Frappe Technologies.

What it is

Every Frappe and ERPNext site has a REST API: any program can read and write its documents over HTTP. frappex-client is the Python package for the other end of that connection, the code that runs outside the site and talks to it.

Instead of building URLs, encoding filters as JSON and decoding Frappe's error format by hand:

import json

import requests

response = requests.get(
    "https://erp.example.com/api/resource/Customer",
    headers={"Authorization": f"token {key}:{secret}"},
    params={
        "filters": json.dumps({"territory": "India"}),
        "fields": json.dumps(["name", "customer_name"]),
        "limit_page_length": 20,
    },
    timeout=30,
)
response.raise_for_status()
customers = response.json()["data"]

you write:

customers = client.get_list(
    "Customer", filters={"territory": "India"}, fields=["name", "customer_name"]
)

Why frappex-client

Frappe publishes no maintained Python client on PyPI. The official frappe-client repository is archived and was never published, so most projects either install an unmaintained package or write raw HTTP calls and solve the same problems again:

Problem with hand-written calls What frappex-client does
No asyncio support for FastAPI, bots and other async programs AsyncClient with the same methods as Client
The API returns 20 rows by default; reading everything needs a loop iter_list walks every page in a stable order
Errors arrive as Frappe's own JSON and must be decoded A typed exception per failure: NotFoundError, PermissionDeniedError, ValidationError and more
A retried insert can create a duplicate document Only safe requests are retried; writes never are
TLS checks get switched off and keys end up in logs HTTPS only, certificate checks always on, secrets masked everywhere
No editor help Fully typed, checked with mypy --strict

It has one dependency (httpx) and is tested on every change against real Frappe 14, 15 and 16 sites.

Use cases

Sync another system into ERPNext. A webshop, CRM or form backend that creates or updates ERPNext records:

import os

from frappex_client import Client, TokenAuth

erp = Client(os.environ["ERP_URL"], TokenAuth(os.environ["ERP_KEY"], os.environ["ERP_SECRET"]))


def upsert_customer(email: str, values: dict[str, str]) -> None:
    existing = erp.get_value("Customer", "name", {"email_id": email})
    if existing:
        erp.update("Customer", existing["name"], values)
    else:
        erp.insert("Customer", {"email_id": email, **values})

Serve ERP data from an async web app. One shared AsyncClient in a FastAPI service:

from contextlib import asynccontextmanager

from fastapi import FastAPI

from frappex_client import AsyncClient, TokenAuth


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with AsyncClient("https://erp.example.com", TokenAuth("key", "secret")) as erp:
        app.state.erp = erp
        yield


app = FastAPI(lifespan=lifespan)


@app.get("/orders/{name}")
async def order(name: str):
    return await app.state.erp.get_doc("Sales Order", name)

Export data for reports and pipelines. Every row, without writing a pagination loop:

import csv

fields = ["name", "customer_name", "territory"]
with open("customers.csv", "w", newline="") as out:
    writer = csv.DictWriter(out, fieldnames=fields)
    writer.writeheader()
    writer.writerows(erp.iter_list("Customer", fields=fields))

Call your own app's API. Methods you whitelist in a custom Frappe app, from scripts, bots or other services:

summary = erp.call("myapp.api.monthly_summary", {"year": 2026}, http_method="GET")

Attach files to documents. Invoices, scans and reports, private by default:

with open("invoice.pdf", "rb") as pdf:
    erp.upload_file("invoice.pdf", pdf.read(), doctype="Sales Invoice", docname="SINV-0001")

Monitor a site. A health check needs no credentials:

from frappex_client import Client, FrappexError

try:
    with Client("https://erp.example.com", timeout=5) as site:
        healthy = site.ping() == "pong"
except FrappexError:
    healthy = False

When not to use it

  • Code running inside a Frappe app. Use frappe.get_doc and the rest of the server-side API directly; there is no need to go over HTTP.
  • Realtime events, reports or print formats. frappex-client covers documents, whitelisted methods and files. Call a report or print method with call.
  • The /api/v2 routes. Planned for a later release.

Features

  • Sync (Client) and async (AsyncClient) with identical methods
  • API key, OAuth bearer token, username/password, or guest access
  • Automatic pagination with iter_list
  • A typed exception for each kind of failure
  • Retries only where repeating a request is safe
  • Secure defaults: HTTPS only, certificate checks always on, no redirects followed, credentials never printed
  • Fully type-annotated; one dependency (httpx)

Requires Python 3.10+. Uses the /api/resource and /api/method routes. The integration suite runs in CI against Frappe v14, v15 and v16.

Install

pip install frappex-client

Quick start

from frappex_client import Client, TokenAuth

with Client("https://erp.example.com", TokenAuth("api_key", "api_secret")) as client:
    print(client.get_logged_user())

    todo = client.insert("ToDo", {"description": "Call the supplier"})
    client.update("ToDo", todo["name"], {"status": "Closed"})

    for row in client.iter_list("ToDo", fields=["name", "status"], filters={"status": "Open"}):
        print(row["name"])

The async client is the same, awaited:

import asyncio
from frappex_client import AsyncClient, TokenAuth


async def main() -> None:
    async with AsyncClient("https://erp.example.com", TokenAuth("key", "secret")) as client:
        async for row in client.iter_list("Customer", fields=["name"]):
            print(row["name"])


asyncio.run(main())

Authentication

Class Use it for
TokenAuth(api_key, api_secret) Servers, scripts and jobs. Recommended.
BearerAuth(token) An OAuth 2 access token issued by the site.
PasswordAuth(username, password) A cookie session. Logs in on first use, logs out on close.
(omitted) Guest access. No credentials are sent.

Read credentials from the environment or a secret store, never from source code.

Without auth, the client acts as a guest. That is enough for a health check, public files and methods the site whitelists with allow_guest:

from frappex_client import Client

with Client("https://erp.example.com") as client:
    assert client.ping() == "pong"

Methods

Method What it does
ping() Check the site answers.
get_logged_user() Return the authenticated user.
get_list(doctype, fields=, filters=, or_filters=, order_by=, limit=, offset=) One page of documents.
iter_list(doctype, ..., page_size=) Every matching document, page by page.
get_doc(doctype, name) One document.
insert(doctype, values) Create a document.
update(doctype, name, values) Change fields.
delete(doctype, name) Delete a document.
submit(doctype, name) / cancel(doctype, name) Submit or cancel.
rename(doctype, old_name, new_name, merge=) Rename; returns the new name.
get_count(doctype, filters) Count matching documents.
get_value(doctype, fieldname, filters) / set_value(doctype, name, values) Read or set fields.
call(method, params, http_method=) Call a whitelisted method.
upload_file(filename, content, is_private=, doctype=, docname=) Upload a file.
download(file_url) / download_to(file_url, target) Fetch a file.

Errors

from frappex_client import NotFoundError, PermissionDeniedError, ValidationError, FrappexError

try:
    client.get_doc("Customer", "CUST-0001")
except NotFoundError:
    ...
except PermissionDeniedError:
    ...
except FrappexError as error:  # everything frappex-client raises
    ...
Exception When
AuthenticationError 401: bad or expired credentials
PermissionDeniedError 403
NotFoundError 404
ConflictError 409: duplicate or conflicting write
ValidationError 417 and other 4xx
RateLimitError 429; retry_after holds the advised wait
ServerError 5xx
TransportError, RequestTimeoutError No response was received
UnexpectedResponseError Redirect or non-JSON reply (usually a wrong base_url)
ResponseTooLargeError Body above max_response_bytes
ConfigurationError An unsafe or malformed argument

APIError subclasses carry status_code, exc_type, server_messages and traceback. Frappe 14 does not always report the exception type, so exc_type can be None there; rely on the exception class instead. The server traceback is deliberately left out of str(error).

Security behaviour

  • http:// is refused unless you pass allow_insecure_http=True (local development only).
  • TLS verification cannot be disabled. For a private CA, pass verify="/path/ca.pem" or an ssl.SSLContext.
  • Redirects are never followed, so credentials cannot be forwarded to another host.
  • DocType and document names are percent-encoded; . and .. are rejected.
  • download accepts only site-relative paths.
  • Uploads are private by default.
  • Writes are never retried after a network error or 5xx. GET requests and HTTP 429 replies are.
  • Secrets are masked in repr() and never logged.

See SECURITY.md to report a vulnerability.

Retries and timeouts

from frappex_client import Client, RetryPolicy, TokenAuth

client = Client(
    "https://erp.example.com",
    TokenAuth("key", "secret"),
    timeout=10,
    retry=RetryPolicy(max_attempts=5, backoff_base=1.0),
)

RetryPolicy(max_attempts=1) turns retries off.

Development

uv sync
uv run ruff check . && uv run ruff format --check .
uv run mypy
uv run pytest

Integration tests run against a live development site and are skipped unless these are set. They remove everything they create. See the developer guide for the full list of settings and the permissions the API user needs:

export FRAPPEX_TEST_URL=http://localhost:8000
export FRAPPEX_TEST_API_KEY=...
export FRAPPEX_TEST_API_SECRET=...
uv run pytest -m integration

Documentation

License

MIT

Metadata

Release files for frappex-client 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for frappex-client 0.1.1
File Size Uploaded Provenance Actions
frappex_client-0.1.1.tar.gz 43.6 kB With provenance Details for frappex_client-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for frappex-client 0.1.1
File Interpreter ABI Platform Actions
frappex_client-0.1.1-py3-none-any.whl Python 3 none any Details for frappex_client-0.1.1-py3-none-any.whl

Total release size: 75.2 kB

Release files / frappex_client-0.1.1.tar.gz

Download URL frappex_client-0.1.1.tar.gz
Size 43.6 kB
Tags Source
SHA-256 checksum
How to use checksums
adb0f105c921bb50449d9a311f9a34c51042fdc8efc903d14a6a8097a340be2a
BLAKE2b-256 checksum
How to use checksums
c7741c0448e8de38521b14e720c711601c0dc7cc29d40a41198bee5ed2f791a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / frappex_client-0.1.1-py3-none-any.whl

Download URL frappex_client-0.1.1-py3-none-any.whl
Size 31.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
31521e0acac2b2959229b0d98e37dfd565dbd66495ac288d24d17089109a03ac
BLAKE2b-256 checksum
How to use checksums
436915f3f68a9073f009e05bf9c8286aaf178810e1bd8d819c326005f1e2af1c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for frappex-client 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for frappex_client-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page