erpnext-api-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ERPNext API Patterns

ERPNext API 模式

API Type Decision Tree

API类型决策树

What do you want to achieve?
├─► CRUD operations on documents
│   └─► REST API: /api/resource/{doctype}
├─► Call custom business logic
│   └─► RPC API: /api/method/{path}
├─► Notify external systems on events
│   └─► Configure Webhooks
└─► Client-side server calls (JavaScript)
    └─► frappe.call() or frappe.xcall()
你想要实现什么?
├─► 文档的CRUD操作
│   └─► REST API: /api/resource/{doctype}
├─► 调用自定义业务逻辑
│   └─► RPC API: /api/method/{path}
├─► 事件触发时通知外部系统
│   └─► 配置Webhook
└─► 客户端向服务器发起调用(JavaScript)
    └─► frappe.call() 或 frappe.xcall()

Quick Reference

快速参考

Authentication Headers

认证请求头

python
undefined
python
undefined

Token Auth (RECOMMENDED for integrations)

令牌认证(集成推荐使用)

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

Bearer Token (OAuth2)

Bearer令牌(OAuth2)

headers = {'Authorization': 'Bearer {access_token}'}
undefined
headers = {'Authorization': 'Bearer {access_token}'}
undefined

REST API CRUD

REST API CRUD操作

OperationMethodEndpoint
List
GET
/api/resource/{doctype}
Create
POST
/api/resource/{doctype}
Read
GET
/api/resource/{doctype}/{name}
Update
PUT
/api/resource/{doctype}/{name}
Delete
DELETE
/api/resource/{doctype}/{name}
操作请求方法端点
列表查询
GET
/api/resource/{doctype}
创建
POST
/api/resource/{doctype}
读取
GET
/api/resource/{doctype}/{name}
更新
PUT
/api/resource/{doctype}/{name}
删除
DELETE
/api/resource/{doctype}/{name}

Filter Operators

过滤器操作符

python
undefined
python
undefined

Basic filters

基础过滤器

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
undefined
filters = [["status", "=", "Open"]] filters = [["amount", ">", 1000]] filters = [["status", "in", ["Open", "Pending"]]] filters = [["date", "between", ["2024-01-01", "2024-12-31"]]] filters = [["reference", "is", "set"]] # 非空
undefined

RPC Method Call

RPC方法调用

python
undefined
python
undefined

Server-side: mark with decorator

服务端:使用装饰器标记

@frappe.whitelist() def my_function(param1, param2): return {"result": "value"}
@frappe.whitelist() def my_function(param1, param2): return {"result": "value"}

API call

API调用

POST /api/method/my_app.api.my_function {"param1": "value1", "param2": "value2"}
undefined
POST /api/method/my_app.api.my_function {"param1": "value1", "param2": "value2"}
undefined

Client-Side Calls (JavaScript)

客户端调用(JavaScript)

javascript
// Async/await pattern (RECOMMENDED)
const result = await frappe.xcall('my_app.api.my_function', {
    param1: 'value'
});

// Promise pattern
frappe.call({
    method: 'my_app.api.my_function',
    args: {param1: 'value'},
    freeze: true,
    freeze_message: __('Processing...')
}).then(r => console.log(r.message));
javascript
// Async/await模式(推荐使用)
const result = await frappe.xcall('my_app.api.my_function', {
    param1: 'value'
});

// Promise模式
frappe.call({
    method: 'my_app.api.my_function',
    args: {param1: 'value'},
    freeze: true,
    freeze_message: __('Processing...')
}).then(r => console.log(r.message));

Response Structure

响应结构

REST API Success:
json
{"data": {...}}
RPC API Success:
json
{"message": "return_value"}
Error Response:
json
{
    "exc_type": "ValidationError",
    "_server_messages": "[{\"message\": \"Error details\"}]"
}
REST API 成功响应:
json
{"data": {...}}
RPC API 成功响应:
json
{"message": "return_value"}
错误响应:
json
{
    "exc_type": "ValidationError",
    "_server_messages": "[{\"message\": \"Error details\"}]"
}

HTTP Status Codes

HTTP状态码

CodeMeaning
200
Success
400
Validation error
401
No authentication
403
No permissions
404
Document not found
417
Server exception
429
Rate limit exceeded
状态码含义
200
成功
400
验证错误
401
未认证
403
无权限
404
文档未找到
417
服务器异常
429
超出速率限制

Critical Rules

重要规则

  1. ALWAYS include
    Accept: application/json
    header
  2. ALWAYS add permission checks in whitelisted methods
  3. NEVER hardcode credentials - use
    frappe.conf
  4. NEVER write SQL injection vulnerable queries
  5. GET for read-only, POST for state-changing operations
  1. 务必包含
    Accept: application/json
    请求头
  2. 务必在白名单方法中添加权限校验
  3. 绝对不要硬编码凭证 - 使用
    frappe.conf
  4. 绝对不要编写存在SQL注入风险的查询
  5. GET用于只读操作,POST用于修改状态的操作

Reference Files

参考文件

FileContents
authentication-methods.mdToken, Session, OAuth2 implementation
rest-api-reference.mdComplete REST API with filters and pagination
rpc-api-reference.mdWhitelisted methods and frappe.call patterns
webhooks-reference.mdWebhook configuration and security
anti-patterns.mdCommon mistakes and fixes
文件内容
authentication-methods.md令牌、会话、OAuth2实现
rest-api-reference.md包含过滤器和分页的完整REST API
rpc-api-reference.md白名单方法与frappe.call模式
webhooks-reference.mdWebhook配置与安全
anti-patterns.md常见错误与修复方案

Version Notes (v14 vs v15)

版本说明(v14 vs v15)

Featurev14v15
expand_links
parameter
Server Script rate limiting
PKCE for OAuth2Limited
功能v14v15
expand_links
参数
服务器脚本速率限制
OAuth2的PKCE支持有限支持