frappe-core-api

用于构建 ERPNext/Frappe(v14/v15/v16)API 集成的说明,涵盖 REST 与 RPC 端点设计、身份验证(Token/OAuth2/会话)、Webhook、速率限制以及外部 API 调用与连接问题诊断。包含如何连接、发送数据、常见错误(如 401)及调试要点。

仓库最近推送
GitHub Stars
211
Forks
61
Issues / PRs
4

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "frappe-core-api":https://skillpi.com/zh/skills/deepskill-036798b436d2aa409b8b03329d14824ebe7026791ec40e52b41a3516a8caaa0f。安装前核对上游来源和版本:https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

用于构建 ERPNext/Frappe(v14/v15/v16)API 集成的说明,涵盖 REST 与 RPC 端点设计、身份验证(Token/OAuth2/会话)、Webhook、速率限制以及外部 API 调用与连接问题诊断。包含如何连接、发送数据、常见错误(如 401)及调试要点。

0 下载

介绍来源: third_party · Impertio-Studio · 2.0 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: frappe-core-api
description: >
  Use when building ERPNext/Frappe API integrations (v14/v15/v16) including
  REST API, RPC API, authentication, webhooks, and rate limiting. Covers
  external API calls, endpoint design, token/OAuth2/session authentication.
  Keywords: API integration, REST endpoint, webhook, token authentication,, how to connect, external API, send data to another system, API not working, 401 error.
  OAuth, frappe.call, external connection, rate limiting.
license: MIT
compatibility: "Claude Code, Claude.ai Projects, Claude API. Frappe v14-v16."
metadata:
  author: OpenAEC-Foundation
  version: "2.0"

Frappe API Patterns

Deterministic patterns for REST, RPC, and webhook integrations with Frappe.


Decision Tree

What do you need?
├── CRUD on documents (external client)
│   ├── v14: REST /api/resource/{doctype}
│   └── v15+: REST /api/v2/document/{doctype} (new) or /api/resource/ (still works)
│
├── Call custom server logic (external client)
│   └── RPC: POST /api/method/{dotted.path.to.function}
│
├── Notify external systems on document events
│   └── Webhooks (configured in UI or via DocType)
│
├── Client-side calls (JavaScript in Frappe desk)
│   ├── frappe.xcall() — async/await (RECOMMENDED)
│   └── frappe.call() — callback/promise pattern
│
└── Authentication method?
    ├── Server-to-server integration → Token Auth (RECOMMENDED)
    ├── Third-party app / mobile → OAuth 2.0
    ├── Browser session (short-lived) → Session/Cookie Auth
    └── Quick scripting / testing → Token Auth

Authentication Methods

Token Auth (RECOMMENDED for integrations)

headers = {
    'Authorization': 'token api_key:api_secret',
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

Generate keys: User > Settings > API Access > Generate Keys. ALWAYS store API secret immediately — it is shown only once.

Basic Auth (alternative token format)

import base64
credentials = base64.b64encode(b'api_key:api_secret').decode()
headers = {'Authorization': f'Basic {credentials}'}

OAuth 2.0 (third-party apps)

# Step 1: Authorization redirect
GET /api/method/frappe.integrations.oauth2.authorize
    ?client_id={id}&response_type=code&scope=openid all
    &redirect_uri={uri}&state={random}

# Step 2: Exchange code for token
POST /api/method/frappe.integrations.oauth2.get_token
    grant_type=authorization_code&code={code}
    &redirect_uri={uri}&client_id={id}

# Step 3: Use bearer token
Authorization: Bearer {access_token}

# Refresh token
POST /api/method/frappe.integrations.oauth2.get_token
    grant_type=refresh_token&refresh_token={token}&client_id={id}

Session/Cookie Auth

session = requests.Session()
session.post(url + '/api/method/login', json={'usr': 'email', 'pwd': 'pass'})
# Subsequent requests use session cookie automatically

Session cookies expire after ~3 days. NEVER use for long-running integrations.


REST API: Resource CRUD

Endpoints

Operation Method v14 Endpoint v15+ v2 Endpoint
List GET /api/resource/{doctype} /api/v2/document/{doctype}
Create POST /api/resource/{doctype} /api/v2/document/{doctype}
Read GET /api/resource/{doctype}/{name} /api/v2/document/{doctype}/{name}
Update PUT /api/resource/{doctype}/{name} PATCH /api/v2/document/{doctype}/{name}
Delete DELETE /api/resource/{doctype}/{name} DELETE /api/v2/document/{doctype}/{name}
Copy — — GET /api/v2/document/{doctype}/{name}/copy [v15+]
Doc Method — — POST /api/v2/document/{doctype}/{name}/method/{method} [v15+]

ALWAYS include Accept: application/json header — without it, Frappe MAY return HTML.

List Parameters

Parameter Type Description Default
fields JSON array Fields to return ["name"]
filters JSON array AND conditions none
or_filters JSON array OR conditions none
order_by string Sort expression modified desc
limit_start int Pagination offset 0
limit_page_length int Page size 20
limit int Alias for limit_page_length [v15+] —
debug bool Show SQL in response false

Filter Operators

filters = [["status", "=", "Open"]]
filters = [["amount", ">", 1000]]
filters = [["status", "in", ["Open", "Pending"]]]
filters = [["date", "between", ["2024-01-01", "2024-12-31"]]]
filters = [["reference", "is", "set"]]       # NOT NULL
filters = [["reference", "is", "not set"]]   # IS NULL
filters = [["name", "like", "%INV%"]]
filters = [["status", "not in", ["Cancelled"]]]

Full operator list: =, !=, >, <, >=, <=, like, not like, in, not in, is, between.

Pagination Pattern

import json, requests

def get_all_records(doctype, headers, base_url, page_size=100):
    all_data, offset = [], 0
    while True:
        params = {
            'fields': json.dumps(["name", "modified"]),
            'limit_start': offset,
            'limit_page_length': page_size
        }
        resp = requests.get(f'{base_url}/api/resource/{doctype}',
                            params=params, headers=headers)
        data = resp.json().get('data', [])
        if not data:
            break
        all_data.extend(data)
        if len(data) < page_size:
            break
        offset += page_size
    return all_data

Create with Child Table

requests.post(f'{base_url}/api/resource/Sales Order', json={
    "customer": "CUST-001",
    "items": [
        {"item_code": "ITEM-001", "qty": 5, "rate": 100},
        {"item_code": "ITEM-002", "qty": 2, "rate": 250}
    ]
}, headers=headers)

Update (Partial)

# Only specified fields are changed
requests.put(f'{base_url}/api/resource/Customer/CUST-001',
             json={"customer_group": "Premium"}, headers=headers)

File Upload

requests.post(f'{base_url}/api/method/upload_file',
    files={'file': ('doc.pdf', open('doc.pdf', 'rb'), 'application/pdf')},
    data={'doctype': 'Customer', 'docname': 'CUST-001', 'is_private': 1},
    headers={'Authorization': 'token api_key:api_secret'})
# NOTE: Do NOT set Content-Type header — requests sets multipart boundary automatically

RPC API: Custom Methods

Server-Side Endpoint

@frappe.whitelist()
def get_balance(customer):
    """GET /api/method/myapp.api.get_balance?customer=CUST-001"""
    return frappe.db.get_value("Customer", customer, "outstanding_amount")

@frappe.whitelist(methods=["POST"])
def create_payment(customer, amount):
    """POST /api/method/myapp.api.create_payment"""
    if not frappe.has_permission("Payment Entry", "create"):
        frappe.throw(_("Not permitted"), frappe.PermissionError)
    pe = frappe.new_doc("Payment Entry")
    pe.party_type = "Customer"
    pe.party = customer
    pe.paid_amount = float(amount)
    pe.insert()
    return pe.name

@frappe.whitelist(allow_guest=True)
def public_status():
    """No authentication required."""
    return {"status": "ok"}

Decorator Options

Option Effect Version
allow_guest=True No authentication needed All
methods=["POST"] Restrict HTTP methods [v14+]
xss_safe=True Skip XSS escaping on response All

Response Structure

// RPC success
{"message": "return_value"}

// REST success
{"data": {...}}

// Error
{"exc_type": "ValidationError", "_server_messages": "[{\"message\": \"...\"}]"}

Client-Side Calls (JavaScript)

// RECOMMENDED: async/await with frappe.xcall
const result = await frappe.xcall('myapp.api.get_balance', {
    customer: 'CUST-001'
});

// Alternative: frappe.call with promise
frappe.call({
    method: 'myapp.api.get_balance',
    args: {customer: 'CUST-001'},
    freeze: true,
    freeze_message: __('Loading...')
}).then(r => console.log(r.message));

// Document method (frm.call)
frm.call('get_linked_doc', {throw_if_missing: true})
    .then(r => console.log(r.message));

Standard frappe.client Methods

Method Endpoint Purpose
frappe.client.get_value POST Get single field value
frappe.client.get_list POST List with filters
frappe.client.get POST Get full document
frappe.client.insert POST Create document
frappe.client.save POST Update document
frappe.client.delete POST Delete document
frappe.client.submit POST Submit document
frappe.client.cancel POST Cancel document
frappe.client.get_count POST Count documents

Webhooks

Configure via Webhook DocType in the UI. Events:

Event Trigger
after_insert New document created
on_update Every save
on_submit After submit (docstatus=1)
on_cancel After cancel (docstatus=2)
on_trash Before delete
on_update_after_submit After amendment
on_change On every change

Security: ALWAYS set a Webhook Secret. Frappe adds X-Frappe-Webhook-Signature header with base64-encoded HMAC-SHA256 of payload. Verify on receiving end.

Conditions: Use Jinja2 — {{ doc.grand_total > 10000 }}.

See references/webhooks-reference.md for complete handler examples.


HTTP Status Codes

Code Meaning Common Cause
200 Success —
400 Bad request Validation error
401 Unauthorized Missing or invalid auth
403 Forbidden No permission for operation
404 Not found Document does not exist
417 Expectation failed Server exception (frappe.throw)
429 Rate limited Too many requests
500 Server error Unhandled exception

Critical Rules

  1. ALWAYS include Accept: application/json header in API requests
  2. ALWAYS add permission checks in @frappe.whitelist() methods
  3. ALWAYS validate and sanitize input in whitelisted methods
  4. ALWAYS use parameterized queries — NEVER string-interpolate SQL
  5. ALWAYS use timeout=30 on external requests calls
  6. ALWAYS store credentials in frappe.conf or env vars — NEVER hardcode
  7. ALWAYS verify webhook signatures with HMAC-SHA256
  8. ALWAYS paginate list responses — NEVER return unbounded result sets
  9. NEVER use allow_guest=True on state-changing endpoints
  10. NEVER log credentials or sensitive data
  11. NEVER use Administrator API keys for integrations — create dedicated API users

Anti-Patterns

Do NOT Do Instead
No permission check in whitelist frappe.has_permission() before action
frappe.db.sql(f"...{user_input}") Parameterized %s queries
allow_guest=True + state change Require authentication
Return all records without limit Paginate with limit_page_length
Hardcode API credentials frappe.conf.get("api_key")
Synchronous heavy processing frappe.enqueue() for long tasks
No timeout on external calls requests.get(url, timeout=30)
Inconsistent response format ALWAYS return {"status": "...", "data": ...}

Version Differences

Feature v14 v15 v16
/api/resource/ (v1) Yes Yes Yes
/api/v2/document/ (v2) No Yes Yes
/api/v2/doctype/{dt}/meta No Yes Yes
/api/v2/doctype/{dt}/count No Yes Yes
limit alias parameter No Yes Yes
PKCE for OAuth2 Limited Yes Yes
Server Script rate limiting No Yes Yes
Doc method via v2 URL No Yes Yes

Reference Files

File Contents
authentication-methods.md Token, Session, OAuth2 with code examples
rest-api-reference.md Complete REST CRUD with filters and pagination
rpc-api-reference.md Whitelisted methods, frappe.call, frappe.xcall
webhooks-reference.md Webhook config, security, handler examples
anti-patterns.md Common mistakes with fixes
examples.md Python/JS/cURL client implementations

Related Skills

  • frappe-core-permissions — Permission system for API endpoints
  • frappe-core-database — Database queries behind API methods
  • frappe-syntax-hooks — Hook configuration for webhooks
  • frappe-syntax-controllers — Controller methods called via API

Verified against Frappe docs 2026-03-20 | Frappe v14/v15/v16

版本历史

  1. v3.1.1 GitHub ↗
    原版更新说明

    ## What's new Expanded Keywords in all skill descriptions with user-friendly, non-technical discovery terms. Skills are now easier to find when users describe problems in plain language instead of technical terminology. Examples of added terms: - Symptom-based: "app is slow", "nothing shows", "container won't start" - Beginner-friendly: "how do I start", "what is", "getting started" - Error messages: literal error text users would paste - Alternative names: common synonyms and abbreviations No skill content was changed. Only the Keywords line in SKILL.md frontmatter was expanded.

  2. v3.1.0 GitHub ↗
    原版更新说明

    ## What's new - package.json with agents.skills[] manifest for external discovery (60 skills) - agents/openai.yaml for OpenAI Codex - GitHub topic agentskills added - SKILLS_LOG.md added to .gitignore - Em-dashes replaced with colons in 31 SKILL.md section headings Enables discovery via npx skills add, skills.sh, LobeHub, and other platforms.

  3. v3.0.0 GitHub ↗
    原版更新说明

    ## Summary - **60 deterministic skills** for Frappe Framework v14-v16 (up from 53 in v2.0) - **~95% surface area coverage** (up from ~85%) - 7 new skills + 12 existing skills extended with new reference files ## New Skills (7) | Skill | Category | Coverage | |-------|----------|----------| | `frappe-core-translation` | core | i18n, _(), __(), CSV/PO files, string extraction | | `frappe-core-utils` | core | 140+ date, number, string, validation functions | | `frappe-syntax-print` | syntax | Print formats, PDF generation, Letter Head | | `frappe-syntax-query-builder` | syntax | frappe.qb, joins, aggregation, cross-DB | | `frappe-impl-workspace` | impl | Workspace builder, number cards, charts | | `frappe-core-logging` | core | frappe.logger(), Error Log, Sentry integration | | `frappe-core-search` | core | Link search, global search, SQLiteSearch FTS5 | ## Extended Skills (12) 13 new reference files added to existing skills covering: Controls API, Tree View, Portal Generators, Print Format decision tree, Email system, Module/Workspace shipping, complete Document API, custom bench commands, request lifecycle, advanced debugging (VS Code DAP), Frappe Packages, data masking (v16+), and Python type stubs. ## Stats | Category | Count | |----------|:-----:| | syntax/ | 13 | | core/ | 11 | | impl/ | 14 | | errors/ | 7 | | ops/ | 8 | | agents/ | 5 | | testing/ | 2 | | **Total** | **60** | ## Install ```bash git clone https://github.com/OpenAEC-Foundation/Frappe_Claude_Skill_Package.git cp -r Frappe_Claude_Skill_Package/skills/source/* ~/.claude/skills/ ```

  4. v2.0.0 GitHub ↗
    原版更新说明

    ## Frappe Claude Skill Package v2.0.0 Massive upgrade from 28 ERPNext-specific skills to **53 Frappe Framework skills** covering ~85% of the Frappe surface area. ### What's New - **25 new skills** across 3 new categories (ops, testing, agents) - **28 existing skills** fully rewritten with fresh research - **Renamed** from `erpnext-*` to `frappe-*` (all skills are Frappe Framework, not ERPNext-specific) - **7 categories**: syntax (11), core (7), impl (13), errors (7), ops (8), agents (5), testing (2) ### New Categories - **ops/** — Bench CLI, deployment, backup, performance, upgrades, frontend build, cloud - **testing/** — Unit/integration tests, CI/CD with GitHub Actions - **3 new agents** — debugger, migrator, architect ### Key Improvements - All skills verified against official Frappe docs (March 2026) - v16 features documented: `extend_doctype_class`, data masking, type annotations - MIT license (was LGPL-3.0) - Deterministic language throughout (ALWAYS/NEVER) 🤖 Generated with [Claude Code](https://claude.com/claude-code)

  5. v1.1.0 GitHub ↗
    原版更新说明

    V16 compatibility update and documentation improvements. ## Added - USAGE.md with platform-specific guides (Claude.ai, Claude Code, API) - Complete README overhaul with quick start guide ## Changed - All 28 skills updated for ERPNext/Frappe V16 compatibility - Agent Skills now follow standard skill structure - Improved validation: 28/28 skills pass all checks ## Fixed - V16-specific syntax changes in 9 skills - Agent SKILL.md files now under 500 lines

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

2.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供 ERPNext/Frappe API 集成的完整模式,涵盖 REST、RPC、Webhook、认证、速率限制等核心功能
  • 面向开发者解决实际集成痛点,受众广泛,实用价值高
触发精准95/100

待提升项

  • description 关键词标点重复 原报告严重程度:轻微

    description 中 'token authentication,,' 存在多余逗号

    改进建议:修正为 'token authentication,'

亮点

  • 触发词精准完整,覆盖多种变体,边界清晰
结构规范80/100

待提升项

  • 文档过长 原报告严重程度:轻微

    主文档约1800行,超过建议的500行限制

    改进建议:考虑将部分内容移至引用文件中,保持主文档简洁

  • frontmatter compatibility 字段内容不相关 原报告严重程度:轻微

    compatibility 字段包含 'Claude Code, Claude.ai Projects, Claude API',与 OpenClaw 平台无关

    改进建议:移除或替换为 OpenClaw 平台相关信息

亮点

  • 结构清晰,包含决策树、认证方法、REST API、RPC API、Webhooks等完整章节
  • 提供端到端示例和反模式指导,便于开发者理解执行
执行可靠90/100

亮点

  • 工具来源明确,参数正确,覆盖主要异常处理
  • 强调关键安全规则(如权限检查、输入验证、超时设置),提升执行可靠性
证据可验 (前四项均值)88/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 读取本地文件

    限定到你选择的文件或项目目录;避免读取无关的个人资料、密钥和配置文件。

    主文档提及 · 第 197 行
  • 保存或修改文件

    先确认输出目录和同名文件是否会被覆盖;重要文件保留备份,优先写入新的输出目录。

    主文档提及 · 第 197 行
  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 8, 42, 55, 67, 68 行
  • 管理员或提升权限

    确认确有必要再提升权限;不要关闭防护、绕过证书验证或扩大整个系统的访问权限。

    主文档提及 · 第 340 行

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。