iDempiere REST API
Overview
- What you’ll learn:
- How to enable and configure iDempiere’s RESTful API for external system integrations
- How to perform CRUD operations and use query parameters for filtering, sorting, pagination, and field selection
- How to handle authentication, error responses, batch operations, and security considerations when building API integrations
- Prerequisites: Lesson 2 — iDempiere Architecture Overview, Lesson 3 — Installing iDempiere (running instance required)
- Estimated reading time: 22 minutes
Introduction
Modern enterprise systems rarely operate in isolation. Organizations need their ERP to communicate with e-commerce platforms, mobile applications, business intelligence tools, and third-party services. iDempiere addresses this need through a comprehensive RESTful API that exposes business data and operations over standard HTTP, enabling external systems to create, read, update, and delete records without direct database access.
The iDempiere REST API follows OData-inspired conventions, providing a consistent and predictable interface for interacting with any table and window defined in the Application Dictionary. In this lesson, you will learn how to enable the API, authenticate your requests, perform CRUD operations, and leverage query parameters for powerful data retrieval. Every concept is demonstrated with practical curl commands you can execute against your own iDempiere instance.
REST API Overview and Setup
The iDempiere REST API is provided by the org.idempiere.rest plugin bundle, which ships with iDempiere but may need to be explicitly enabled depending on your installation. The API exposes iDempiere’s Application Dictionary-defined windows and tables as RESTful resources.
Enabling the REST API
In most modern iDempiere installations (version 10 and later), the REST API plugin is included by default. To verify it is active:
- Log in to iDempiere as System Administrator.
- Navigate to the OSGi console or check the bundle status using the Felix web console (typically at
http://localhost:8080/osgi/system/console/bundles). - Search for
org.idempiere.restbundles — ensure they are in the Active state.
If the bundles are not active, you can start them from the OSGi console or add them to your server configuration.
API Base URL and Versioning
The REST API is accessible at a base URL following this pattern:
http://<host>:<port>/api/v1/
For a local development installation, this is typically:
http://localhost:8080/api/v1/
The v1 segment represents the API version. As the API evolves, new versions may be introduced while maintaining backward compatibility with existing versions. Always include the version prefix in your API calls to ensure consistent behavior across iDempiere upgrades.
Authentication Methods
Every API request must be authenticated. iDempiere’s REST API supports token-based authentication as its primary mechanism.
Token-Based Authentication
The recommended approach is to obtain an authentication token by sending credentials to the auth endpoint, then including that token in subsequent requests:
# Step 1: Obtain a token
curl -X PUT \
http://localhost:8080/api/v1/auth/tokens \
-H 'Content-Type: application/json' \
-d '{
"userName": "GardenAdmin",
"password": "GardenAdmin"
}'
A successful response returns a JSON object containing the token and context selection options:
{
"clients": [
{
"id": 11,
"name": "GardenWorld",
"roles": [
{
"id": 102,
"name": "GardenWorld Admin",
"organizations": [
{ "id": 0, "name": "*" },
{ "id": 11, "name": "HQ" }
],
"warehouses": [
{ "id": 103, "name": "HQ Warehouse" }
]
}
]
}
],
"token": "eyJhbGciOiJIUzUxMiJ9..."
}
Setting the Context
After obtaining a token, you must set the working context (client, role, organization, warehouse) — the same context you select when logging in through the web UI:
# Step 2: Set context using the token
curl -X PUT \
http://localhost:8080/api/v1/auth/tokens \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...' \
-d '{
"clientId": 11,
"roleId": 102,
"organizationId": 11,
"warehouseId": 103,
"language": "en_US"
}'
Using the Token in Requests
Include the token in every subsequent API request using the Authorization header:
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...'
CRUD Operations
The REST API maps standard HTTP methods to CRUD operations on iDempiere records. Resources are accessed through window slugs (URL-friendly names derived from window names in the Application Dictionary).
GET — Retrieve Records
Use GET requests to retrieve single records or lists of records.
Retrieve a List of Records
# Get all business partners
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer <token>'
The response includes a JSON array of records with their fields:
{
"page-count": 5,
"records-size": 50,
"skip-records": 0,
"row-count": 234,
"array-count": 50,
"records": [
{
"id": 118,
"uid": "abc12345-...",
"Value": "JoeBlock",
"Name": "Joe Block",
"IsCustomer": true,
"IsVendor": false,
...
},
...
]
}
Retrieve a Single Record
# Get business partner with ID 118
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>'
POST — Create Records
Use POST requests to create new records. The request body contains the field values as a JSON object:
# Create a new business partner
curl -X POST \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"Value": "NEWCUST001",
"Name": "New Customer Inc.",
"IsCustomer": true,
"IsVendor": false,
"C_BP_Group_ID": 104
}'
A successful creation returns HTTP status 201 Created with the complete record, including system-generated fields like id, Created, and CreatedBy.
PUT — Update Records
Use PUT requests to update existing records. Include only the fields you want to modify:
# Update business partner name
curl -X PUT \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"Name": "Joe Block International"
}'
The API returns HTTP status 200 OK with the updated record.
DELETE — Remove Records
Use DELETE requests to deactivate or remove records:
# Delete a business partner record
curl -X DELETE \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>'
Note that in iDempiere, deletion may be restricted by business rules. Referenced records (for example, a business partner with existing orders) cannot be deleted. The API will return an appropriate error message in such cases.
Query Parameters for Filtering and Retrieval
The REST API supports OData-style query parameters that give you fine-grained control over which records are returned and how they are presented.
Filtering with $filter
Use the $filter parameter to apply conditions to your queries:
# Get only customers (not vendors)
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true' \
-H 'Authorization: Bearer <token>'
# Filter by name containing a string
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=Name contains Joe' \
-H 'Authorization: Bearer <token>'
# Combine multiple conditions
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true and IsActive eq true' \
-H 'Authorization: Bearer <token>'
Supported filter operators include: eq (equal), neq (not equal), gt (greater than), lt (less than), ge (greater than or equal), le (less than or equal), contains, startswith, endswith, and, or.
Sorting with $orderby
Control the order of results using the $orderby parameter:
# Sort by name ascending
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$orderby=Name asc' \
-H 'Authorization: Bearer <token>'
# Sort by creation date descending
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$orderby=Created desc' \
-H 'Authorization: Bearer <token>'
Pagination with $top and $skip
For large datasets, use pagination parameters to retrieve records in manageable pages:
# Get the first 10 records
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$top=10' \
-H 'Authorization: Bearer <token>'
# Skip the first 20 records and get the next 10 (page 3)
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$top=10&$skip=20' \
-H 'Authorization: Bearer <token>'
Field Selection with $select
Reduce response payload size by requesting only specific fields:
# Get only ID, Value, and Name fields
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$select=Value,Name' \
-H 'Authorization: Bearer <token>'
Expanding Related Records with $expand
The $expand parameter retrieves child tab records in a single request, avoiding the need for multiple API calls:
# Get a sales order with its order lines
curl -X GET \
'http://localhost:8080/api/v1/windows/sales-order/104?$expand=order-line' \
-H 'Authorization: Bearer <token>'
The expanded records appear as a nested array within the parent record’s JSON response.
Combining Query Parameters
All query parameters can be combined for precise data retrieval:
# Active customers, sorted by name, page 2 (10 per page), limited fields
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true and IsActive eq true&$orderby=Name asc&$top=10&$skip=10&$select=Value,Name,TotalOpenBalance' \
-H 'Authorization: Bearer <token>'
Working with Detail Tabs
iDempiere windows often have parent-child relationships expressed as header and detail tabs. The API represents these as nested resources:
# Get order lines for a specific sales order
curl -X GET \
http://localhost:8080/api/v1/windows/sales-order/104/order-line \
-H 'Authorization: Bearer <token>'
# Create a new order line on an existing order
curl -X POST \
http://localhost:8080/api/v1/windows/sales-order/104/order-line \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"M_Product_ID": 134,
"QtyOrdered": 10,
"PriceEntered": 25.00
}'
Process Execution via API
Beyond CRUD operations, the API allows you to invoke iDempiere processes, such as document completion:
# Run a process (e.g., complete a document)
curl -X PUT \
http://localhost:8080/api/v1/windows/sales-order/104/doc-action \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"DocAction": "CO"
}'
Common document actions include: CO (Complete), CL (Close), VO (Void), RE (Reverse Correct), PR (Prepare).
Error Responses and Status Codes
The REST API uses standard HTTP status codes to indicate the result of operations:
| Status Code | Meaning | Common Cause |
|---|---|---|
200 OK |
Successful retrieval or update | Normal success response |
201 Created |
Record successfully created | Successful POST request |
400 Bad Request |
Invalid request | Missing required fields, invalid field values |
401 Unauthorized |
Authentication failed | Missing or expired token |
403 Forbidden |
Insufficient permissions | Role lacks access to the window or record |
404 Not Found |
Resource not found | Invalid window slug or record ID |
500 Internal Server Error |
Server error | Business rule violation, database constraint |
Error responses include a JSON body with details about the failure:
{
"title": "Save error",
"status": 500,
"detail": "Cannot delete record because it is referenced by other records."
}
Security Considerations
Exposing an API adds an attack surface to your iDempiere installation. Follow these best practices to secure your deployment.
CORS Configuration
Cross-Origin Resource Sharing (CORS) controls which domains can make API requests from a browser. Configure CORS to allow only trusted origins:
- In production, restrict allowed origins to specific domains rather than using a wildcard (
*). - Configure CORS headers in your reverse proxy (Apache or Nginx) or in the iDempiere REST plugin settings.
API Token Security
- Never embed tokens in client-side JavaScript or mobile app source code.
- Store tokens securely and transmit them only over HTTPS.
- Implement token rotation — periodically re-authenticate to obtain fresh tokens.
- Use roles with minimum required permissions for API access. Create dedicated API roles that grant access only to the specific windows and records needed by the integration.
Rate Limiting
While iDempiere does not include built-in rate limiting, you should implement it at the infrastructure level using your reverse proxy:
# Nginx rate limiting example
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://localhost:8080;
}
HTTPS
Always use HTTPS in production to encrypt API traffic. Configure SSL/TLS termination at your reverse proxy or load balancer. Never transmit authentication tokens over unencrypted HTTP connections.
Common Integration Patterns
Here are several practical patterns for integrating external systems with iDempiere through the REST API.
E-Commerce Order Sync
Synchronize orders from an online store into iDempiere:
- Authenticate and obtain a token.
- Look up or create the business partner using a GET with
$filter, then POST if not found. - Create a sales order header via POST to
/windows/sales-order. - Create order lines via POST to
/windows/sales-order/{id}/order-linefor each cart item. - Complete the order using a document action PUT.
Inventory Polling
External systems can poll iDempiere for current stock levels:
# Get product inventory (Storage on Hand)
curl -X GET \
'http://localhost:8080/api/v1/windows/material-receipt?$filter=M_Product_ID eq 134&$select=QtyOnHand' \
-H 'Authorization: Bearer <token>'
Reporting Data Extraction
Business intelligence tools can extract data for dashboards and reports by querying the API with specific filters and field selections, paginating through large result sets as needed.
Summary
The iDempiere REST API transforms iDempiere from a standalone ERP into an integration-ready platform. You learned how to authenticate using tokens, perform full CRUD operations, leverage query parameters for efficient data retrieval, handle errors gracefully, and secure your API deployment. In the next lesson, you will build on this foundation by creating custom REST endpoints that expose your own business logic to external systems.
繁體中文翻譯
概覽
- 您將學到:
- 如何啟用和設定 iDempiere 的 RESTful API 以進行外部系統整合
- 如何執行 CRUD 操作,以及使用查詢參數進行篩選、排序、分頁和欄位選擇
- 如何在建構 API 整合時處理驗證、錯誤回應、批次操作和安全性考量
- 先備知識: 第 2 課 — iDempiere 架構概覽、第 3 課 — 安裝 iDempiere(需要執行中的實例)
- 預估閱讀時間: 22 分鐘
簡介
現代企業系統很少單獨運作。組織需要其 ERP 與電子商務平台、行動應用程式、商業智慧工具和第三方服務進行通訊。iDempiere 透過全面的 RESTful API 來滿足這一需求,該 API 透過標準 HTTP 公開業務資料和操作,使外部系統能夠在不直接存取資料庫的情況下建立、讀取、更新和刪除記錄。
iDempiere REST API 遵循 OData 風格的慣例,為與應用程式字典中定義的任何表格和視窗互動提供一致且可預測的介面。在本課中,您將學習如何啟用 API、驗證您的請求、執行 CRUD 操作,以及利用查詢參數進行強大的資料擷取。每個概念都有實際的 curl 指令示範,您可以在自己的 iDempiere 實例上執行。
REST API 概覽與設定
iDempiere REST API 由 org.idempiere.rest 外掛套件提供,該套件隨 iDempiere 一起發布,但可能需要根據您的安裝情況明確啟用。該 API 將 iDempiere 應用程式字典定義的視窗和表格公開為 RESTful 資源。
啟用 REST API
在大多數現代 iDempiere 安裝中(版本 10 及更高版本),REST API 外掛預設包含。要驗證它是否處於啟用狀態:
- 以系統管理員身分登入 iDempiere。
- 導覽至 OSGi 主控台或使用 Felix Web 主控台檢查套件狀態(通常在
http://localhost:8080/osgi/system/console/bundles)。 - 搜尋
org.idempiere.rest套件 — 確保它們處於 Active(啟用)狀態。
如果套件未啟用,您可以從 OSGi 主控台啟動它們或將它們加入伺服器設定。
API 基礎 URL 與版本控制
REST API 可透過以下模式的基礎 URL 存取:
http://<host>:<port>/api/v1/
對於本機開發安裝,通常為:
http://localhost:8080/api/v1/
v1 段代表 API 版本。隨著 API 的演進,可能會引入新版本,同時保持與現有版本的向後相容性。請務必在 API 呼叫中包含版本前綴,以確保在 iDempiere 升級時行為一致。
驗證方法
每個 API 請求都必須經過驗證。iDempiere 的 REST API 支援基於權杖的驗證作為其主要機制。
基於權杖的驗證
建議的方法是透過向驗證端點發送憑證來取得驗證權杖,然後在後續請求中包含該權杖:
# 步驟 1:取得權杖
curl -X PUT \
http://localhost:8080/api/v1/auth/tokens \
-H 'Content-Type: application/json' \
-d '{
"userName": "GardenAdmin",
"password": "GardenAdmin"
}'
成功的回應會傳回包含權杖和上下文選擇選項的 JSON 物件:
{
"clients": [
{
"id": 11,
"name": "GardenWorld",
"roles": [
{
"id": 102,
"name": "GardenWorld Admin",
"organizations": [
{ "id": 0, "name": "*" },
{ "id": 11, "name": "HQ" }
],
"warehouses": [
{ "id": 103, "name": "HQ Warehouse" }
]
}
]
}
],
"token": "eyJhbGciOiJIUzUxMiJ9..."
}
設定上下文
取得權杖後,您必須設定工作上下文(用戶端、角色、組織、倉庫)— 與您透過 Web UI 登入時選擇的上下文相同:
# 步驟 2:使用權杖設定上下文
curl -X PUT \
http://localhost:8080/api/v1/auth/tokens \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...' \
-d '{
"clientId": 11,
"roleId": 102,
"organizationId": 11,
"warehouseId": 103,
"language": "en_US"
}'
在請求中使用權杖
在每個後續 API 請求中使用 Authorization 標頭包含權杖:
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...'
CRUD 操作
REST API 將標準 HTTP 方法對應到 iDempiere 記錄的 CRUD 操作。資源透過視窗別名(從應用程式字典中的視窗名稱衍生的 URL 友善名稱)來存取。
GET — 擷取記錄
使用 GET 請求來擷取單一記錄或記錄清單。
擷取記錄清單
# 取得所有業務夥伴
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer <token>'
回應包含帶有欄位的 JSON 記錄陣列:
{
"page-count": 5,
"records-size": 50,
"skip-records": 0,
"row-count": 234,
"array-count": 50,
"records": [
{
"id": 118,
"uid": "abc12345-...",
"Value": "JoeBlock",
"Name": "Joe Block",
"IsCustomer": true,
"IsVendor": false,
...
},
...
]
}
擷取單一記錄
# 取得 ID 為 118 的業務夥伴
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>'
POST — 建立記錄
使用 POST 請求來建立新記錄。請求主體包含作為 JSON 物件的欄位值:
# 建立新的業務夥伴
curl -X POST \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"Value": "NEWCUST001",
"Name": "New Customer Inc.",
"IsCustomer": true,
"IsVendor": false,
"C_BP_Group_ID": 104
}'
成功建立後傳回 HTTP 狀態碼 201 Created,以及完整的記錄,包括系統產生的欄位如 id、Created 和 CreatedBy。
PUT — 更新記錄
使用 PUT 請求來更新現有記錄。僅包含您要修改的欄位:
# 更新業務夥伴名稱
curl -X PUT \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"Name": "Joe Block International"
}'
API 傳回 HTTP 狀態碼 200 OK 以及更新後的記錄。
DELETE — 移除記錄
使用 DELETE 請求來停用或移除記錄:
# 刪除業務夥伴記錄
curl -X DELETE \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>'
請注意,在 iDempiere 中,刪除可能受到業務規則的限制。被參照的記錄(例如,有現有訂單的業務夥伴)無法被刪除。在這種情況下,API 會傳回適當的錯誤訊息。
用於篩選和擷取的查詢參數
REST API 支援 OData 風格的查詢參數,讓您能精確控制傳回哪些記錄以及如何呈現。
使用 $filter 進行篩選
使用 $filter 參數對查詢套用條件:
# 僅取得客戶(非供應商)
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true' \
-H 'Authorization: Bearer <token>'
# 依名稱包含字串篩選
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=Name contains Joe' \
-H 'Authorization: Bearer <token>'
# 組合多個條件
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true and IsActive eq true' \
-H 'Authorization: Bearer <token>'
支援的篩選運算子包括:eq(等於)、neq(不等於)、gt(大於)、lt(小於)、ge(大於或等於)、le(小於或等於)、contains、startswith、endswith、and、or。
使用 $orderby 排序
使用 $orderby 參數控制結果的排列順序:
# 依名稱升冪排列
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$orderby=Name asc' \
-H 'Authorization: Bearer <token>'
# 依建立日期降冪排列
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$orderby=Created desc' \
-H 'Authorization: Bearer <token>'
使用 $top 和 $skip 進行分頁
對於大型資料集,使用分頁參數以可管理的頁面擷取記錄:
# 取得前 10 筆記錄
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$top=10' \
-H 'Authorization: Bearer <token>'
# 跳過前 20 筆記錄並取得接下來的 10 筆(第 3 頁)
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$top=10&$skip=20' \
-H 'Authorization: Bearer <token>'
使用 $select 選擇欄位
透過僅請求特定欄位來減少回應的承載大小:
# 僅取得 ID、Value 和 Name 欄位
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$select=Value,Name' \
-H 'Authorization: Bearer <token>'
使用 $expand 展開關聯記錄
$expand 參數在單一請求中擷取子頁籤記錄,避免需要多次 API 呼叫:
# 取得銷售訂單及其訂單明細
curl -X GET \
'http://localhost:8080/api/v1/windows/sales-order/104?$expand=order-line' \
-H 'Authorization: Bearer <token>'
展開的記錄以巢狀陣列的形式出現在父記錄的 JSON 回應中。
組合查詢參數
所有查詢參數可以組合使用以精確擷取資料:
# 有效客戶、依名稱排序、第 2 頁(每頁 10 筆)、限定欄位
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true and IsActive eq true&$orderby=Name asc&$top=10&$skip=10&$select=Value,Name,TotalOpenBalance' \
-H 'Authorization: Bearer <token>'
使用明細頁籤
iDempiere 視窗通常具有以表頭和明細頁籤表示的父子關係。API 將這些表示為巢狀資源:
# 取得特定銷售訂單的訂單明細
curl -X GET \
http://localhost:8080/api/v1/windows/sales-order/104/order-line \
-H 'Authorization: Bearer <token>'
# 在現有訂單上建立新的訂單明細
curl -X POST \
http://localhost:8080/api/v1/windows/sales-order/104/order-line \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"M_Product_ID": 134,
"QtyOrdered": 10,
"PriceEntered": 25.00
}'
透過 API 執行流程
除了 CRUD 操作外,API 還允許您呼叫 iDempiere 流程,例如文件完成:
# 執行流程(例如完成文件)
curl -X PUT \
http://localhost:8080/api/v1/windows/sales-order/104/doc-action \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"DocAction": "CO"
}'
常見的文件動作包括:CO(完成)、CL(關閉)、VO(作廢)、RE(反轉更正)、PR(準備)。
錯誤回應與狀態碼
REST API 使用標準 HTTP 狀態碼來指示操作的結果:
| 狀態碼 | 含義 | 常見原因 |
|---|---|---|
200 OK |
擷取或更新成功 | 正常的成功回應 |
201 Created |
記錄建立成功 | 成功的 POST 請求 |
400 Bad Request |
無效的請求 | 缺少必填欄位、無效的欄位值 |
401 Unauthorized |
驗證失敗 | 缺少或過期的權杖 |
403 Forbidden |
權限不足 | 角色缺少對視窗或記錄的存取權限 |
404 Not Found |
找不到資源 | 無效的視窗別名或記錄 ID |
500 Internal Server Error |
伺服器錯誤 | 業務規則違規、資料庫約束 |
錯誤回應包含帶有失敗詳情的 JSON 主體:
{
"title": "Save error",
"status": 500,
"detail": "Cannot delete record because it is referenced by other records."
}
安全性考量
公開 API 會為您的 iDempiere 安裝增加攻擊面。請遵循以下最佳實務來保護您的部署。
CORS 設定
跨來源資源共享(CORS)控制哪些網域可以從瀏覽器發出 API 請求。設定 CORS 以僅允許受信任的來源:
- 在正式環境中,將允許的來源限制為特定網域,而不是使用萬用字元(
*)。 - 在反向代理(Apache 或 Nginx)或 iDempiere REST 外掛設定中設定 CORS 標頭。
API 權杖安全性
- 絕不要將權杖嵌入用戶端 JavaScript 或行動應用程式原始碼中。
- 安全地儲存權杖,並僅透過 HTTPS 傳輸。
- 實施權杖輪換 — 定期重新驗證以取得新的權杖。
- 使用具有最低所需權限的角色來存取 API。建立專用的 API 角色,僅授予整合所需的特定視窗和記錄的存取權限。
速率限制
雖然 iDempiere 不包含內建的速率限制,但您應該在基礎設施層級使用反向代理來實施:
# Nginx 速率限制範例
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://localhost:8080;
}
HTTPS
在正式環境中始終使用 HTTPS 來加密 API 流量。在反向代理或負載平衡器上設定 SSL/TLS 終止。絕不要透過未加密的 HTTP 連線傳輸驗證權杖。
常見整合模式
以下是透過 REST API 將外部系統與 iDempiere 整合的幾種實用模式。
電子商務訂單同步
將線上商店的訂單同步到 iDempiere:
- 驗證並取得權杖。
- 使用帶有
$filter的 GET 查詢或建立業務夥伴,如果找不到則使用 POST。 - 透過 POST 到
/windows/sales-order建立銷售訂單表頭。 - 為每個購物車項目透過 POST 到
/windows/sales-order/{id}/order-line建立訂單明細。 - 使用文件動作 PUT 完成訂單。
庫存輪詢
外部系統可以輪詢 iDempiere 以取得目前庫存水準:
# 取得產品庫存(庫存現量)
curl -X GET \
'http://localhost:8080/api/v1/windows/material-receipt?$filter=M_Product_ID eq 134&$select=QtyOnHand' \
-H 'Authorization: Bearer <token>'
報表資料擷取
商業智慧工具可以透過使用特定篩選器和欄位選擇查詢 API 來擷取資料用於儀表板和報表,並根據需要分頁瀏覽大型結果集。
總結
iDempiere REST API 將 iDempiere 從獨立的 ERP 轉變為可整合的平台。您學習了如何使用權杖進行驗證、執行完整的 CRUD 操作、利用查詢參數進行高效的資料擷取、優雅地處理錯誤,以及保護您的 API 部署。在下一課中,您將在此基礎上建立自訂 REST 端點,將您自己的業務邏輯公開給外部系統。
日本語翻訳
概要
- 学習内容:
- 外部システム統合のために iDempiere の RESTful API を有効化および設定する方法
- CRUD 操作を実行し、フィルタリング、ソート、ページネーション、フィールド選択のためのクエリパラメータを使用する方法
- API 統合を構築する際の認証、エラーレスポンス、バッチ操作、セキュリティの考慮事項を処理する方法
- 前提条件: レッスン 2 — iDempiere アーキテクチャ概要、レッスン 3 — iDempiere のインストール(実行中のインスタンスが必要)
- 推定読了時間: 22 分
はじめに
現代のエンタープライズシステムが単独で運用されることはほとんどありません。組織は ERP を EC プラットフォーム、モバイルアプリケーション、ビジネスインテリジェンスツール、サードパーティサービスと連携させる必要があります。iDempiere は包括的な RESTful API を通じてこのニーズに対応し、標準的な HTTP を介してビジネスデータと操作を公開することで、外部システムがデータベースに直接アクセスすることなくレコードの作成、読み取り、更新、削除を行えるようにします。
iDempiere REST API は OData にインスパイアされた規約に従い、アプリケーションディクショナリで定義された任意のテーブルやウィンドウと対話するための一貫性のある予測可能なインターフェースを提供します。このレッスンでは、API の有効化、リクエストの認証、CRUD 操作の実行、強力なデータ取得のためのクエリパラメータの活用方法を学びます。すべての概念は、お使いの iDempiere インスタンスで実行できる実用的な curl コマンドで実演します。
REST API の概要とセットアップ
iDempiere REST API は org.idempiere.rest プラグインバンドルによって提供され、iDempiere に同梱されていますが、インストール状況によっては明示的に有効化する必要がある場合があります。この API は iDempiere のアプリケーションディクショナリで定義されたウィンドウとテーブルを RESTful リソースとして公開します。
REST API の有効化
最近の iDempiere インストール(バージョン 10 以降)では、REST API プラグインはデフォルトで含まれています。アクティブであることを確認するには:
- システム管理者として iDempiere にログインします。
- OSGi コンソールに移動するか、Felix Web コンソール(通常
http://localhost:8080/osgi/system/console/bundles)でバンドルのステータスを確認します。 org.idempiere.restバンドルを検索し、Active(アクティブ)状態であることを確認します。
バンドルがアクティブでない場合は、OSGi コンソールから起動するか、サーバー設定に追加できます。
API ベース URL とバージョニング
REST API は以下のパターンのベース URL でアクセスできます:
http://<host>:<port>/api/v1/
ローカル開発環境では、通常以下のようになります:
http://localhost:8080/api/v1/
v1 セグメントは API バージョンを表します。API の進化に伴い、既存バージョンとの後方互換性を維持しながら新しいバージョンが導入される場合があります。iDempiere のアップグレード時に一貫した動作を確保するため、API 呼び出しには常にバージョンプレフィックスを含めてください。
認証方法
すべての API リクエストは認証が必要です。iDempiere の REST API は、主要な認証メカニズムとしてトークンベースの認証をサポートしています。
トークンベースの認証
推奨されるアプローチは、認証エンドポイントに資格情報を送信して認証トークンを取得し、後続のリクエストにそのトークンを含める方法です:
# ステップ 1:トークンを取得する
curl -X PUT \
http://localhost:8080/api/v1/auth/tokens \
-H 'Content-Type: application/json' \
-d '{
"userName": "GardenAdmin",
"password": "GardenAdmin"
}'
成功したレスポンスは、トークンとコンテキスト選択オプションを含む JSON オブジェクトを返します:
{
"clients": [
{
"id": 11,
"name": "GardenWorld",
"roles": [
{
"id": 102,
"name": "GardenWorld Admin",
"organizations": [
{ "id": 0, "name": "*" },
{ "id": 11, "name": "HQ" }
],
"warehouses": [
{ "id": 103, "name": "HQ Warehouse" }
]
}
]
}
],
"token": "eyJhbGciOiJIUzUxMiJ9..."
}
コンテキストの設定
トークンを取得した後、作業コンテキスト(クライアント、ロール、組織、倉庫)を設定する必要があります。これは Web UI からログインする際に選択するコンテキストと同じです:
# ステップ 2:トークンを使用してコンテキストを設定する
curl -X PUT \
http://localhost:8080/api/v1/auth/tokens \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...' \
-d '{
"clientId": 11,
"roleId": 102,
"organizationId": 11,
"warehouseId": 103,
"language": "en_US"
}'
リクエストでのトークン使用
後続のすべての API リクエストで Authorization ヘッダーを使用してトークンを含めます:
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9...'
CRUD 操作
REST API は標準的な HTTP メソッドを iDempiere レコードの CRUD 操作にマッピングします。リソースはウィンドウスラッグ(アプリケーションディクショナリのウィンドウ名から派生した URL フレンドリーな名前)を通じてアクセスされます。
GET — レコードの取得
GET リクエストを使用して単一のレコードまたはレコードのリストを取得します。
レコードリストの取得
# すべてのビジネスパートナーを取得
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer <token>'
レスポンスにはフィールドを含む JSON レコードの配列が含まれます:
{
"page-count": 5,
"records-size": 50,
"skip-records": 0,
"row-count": 234,
"array-count": 50,
"records": [
{
"id": 118,
"uid": "abc12345-...",
"Value": "JoeBlock",
"Name": "Joe Block",
"IsCustomer": true,
"IsVendor": false,
...
},
...
]
}
単一レコードの取得
# ID 118 のビジネスパートナーを取得
curl -X GET \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>'
POST — レコードの作成
POST リクエストを使用して新しいレコードを作成します。リクエストボディには JSON オブジェクトとしてフィールド値が含まれます:
# 新しいビジネスパートナーを作成
curl -X POST \
http://localhost:8080/api/v1/windows/business-partner \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"Value": "NEWCUST001",
"Name": "New Customer Inc.",
"IsCustomer": true,
"IsVendor": false,
"C_BP_Group_ID": 104
}'
作成が成功すると、HTTP ステータス 201 Created と、id、Created、CreatedBy などのシステム生成フィールドを含む完全なレコードが返されます。
PUT — レコードの更新
PUT リクエストを使用して既存のレコードを更新します。変更したいフィールドのみを含めます:
# ビジネスパートナー名を更新
curl -X PUT \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"Name": "Joe Block International"
}'
API は HTTP ステータス 200 OK と更新されたレコードを返します。
DELETE — レコードの削除
DELETE リクエストを使用してレコードを無効化または削除します:
# ビジネスパートナーレコードを削除
curl -X DELETE \
http://localhost:8080/api/v1/windows/business-partner/118 \
-H 'Authorization: Bearer <token>'
iDempiere では、削除はビジネスルールによって制限される場合があります。参照されているレコード(例えば、既存の受注があるビジネスパートナー)は削除できません。このような場合、API は適切なエラーメッセージを返します。
フィルタリングと取得のためのクエリパラメータ
REST API は OData スタイルのクエリパラメータをサポートしており、返されるレコードとその表示方法をきめ細かく制御できます。
$filter によるフィルタリング
$filter パラメータを使用してクエリに条件を適用します:
# 顧客のみを取得(仕入先を除く)
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true' \
-H 'Authorization: Bearer <token>'
# 名前に文字列を含むものでフィルタ
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=Name contains Joe' \
-H 'Authorization: Bearer <token>'
# 複数の条件を組み合わせる
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true and IsActive eq true' \
-H 'Authorization: Bearer <token>'
サポートされているフィルタ演算子:eq(等しい)、neq(等しくない)、gt(より大きい)、lt(より小さい)、ge(以上)、le(以下)、contains、startswith、endswith、and、or。
$orderby によるソート
$orderby パラメータを使用して結果の順序を制御します:
# 名前の昇順でソート
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$orderby=Name asc' \
-H 'Authorization: Bearer <token>'
# 作成日の降順でソート
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$orderby=Created desc' \
-H 'Authorization: Bearer <token>'
$top と $skip によるページネーション
大規模なデータセットの場合、ページネーションパラメータを使用して管理しやすいページ単位でレコードを取得します:
# 最初の 10 件のレコードを取得
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$top=10' \
-H 'Authorization: Bearer <token>'
# 最初の 20 件をスキップして次の 10 件を取得(3 ページ目)
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$top=10&$skip=20' \
-H 'Authorization: Bearer <token>'
$select によるフィールド選択
特定のフィールドのみをリクエストしてレスポンスペイロードのサイズを削減します:
# ID、Value、Name フィールドのみを取得
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$select=Value,Name' \
-H 'Authorization: Bearer <token>'
$expand による関連レコードの展開
$expand パラメータは、単一のリクエストで子タブのレコードを取得し、複数の API 呼び出しの必要性を回避します:
# 受注とその明細行を取得
curl -X GET \
'http://localhost:8080/api/v1/windows/sales-order/104?$expand=order-line' \
-H 'Authorization: Bearer <token>'
展開されたレコードは、親レコードの JSON レスポンス内にネストされた配列として表示されます。
クエリパラメータの組み合わせ
すべてのクエリパラメータを組み合わせて正確なデータ取得が可能です:
# 有効な顧客、名前でソート、2 ページ目(1 ページ 10 件)、限定フィールド
curl -X GET \
'http://localhost:8080/api/v1/windows/business-partner?$filter=IsCustomer eq true and IsActive eq true&$orderby=Name asc&$top=10&$skip=10&$select=Value,Name,TotalOpenBalance' \
-H 'Authorization: Bearer <token>'
明細タブの操作
iDempiere のウィンドウは、ヘッダーと明細タブとして表現される親子関係を持つことがよくあります。API はこれらをネストされたリソースとして表現します:
# 特定の受注の明細行を取得
curl -X GET \
http://localhost:8080/api/v1/windows/sales-order/104/order-line \
-H 'Authorization: Bearer <token>'
# 既存の受注に新しい明細行を作成
curl -X POST \
http://localhost:8080/api/v1/windows/sales-order/104/order-line \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"M_Product_ID": 134,
"QtyOrdered": 10,
"PriceEntered": 25.00
}'
API によるプロセス実行
CRUD 操作に加えて、API では伝票完了などの iDempiere プロセスを呼び出すことができます:
# プロセスを実行(例:伝票を完了する)
curl -X PUT \
http://localhost:8080/api/v1/windows/sales-order/104/doc-action \
-H 'Authorization: Bearer <token>' \
-H 'Content-Type: application/json' \
-d '{
"DocAction": "CO"
}'
一般的な伝票アクション:CO(完了)、CL(クローズ)、VO(無効化)、RE(逆仕訳訂正)、PR(準備)。
エラーレスポンスとステータスコード
REST API は操作の結果を示すために標準的な HTTP ステータスコードを使用します:
| ステータスコード | 意味 | 一般的な原因 |
|---|---|---|
200 OK |
取得または更新の成功 | 通常の成功レスポンス |
201 Created |
レコードの作成成功 | 成功した POST リクエスト |
400 Bad Request |
無効なリクエスト | 必須フィールドの欠落、無効なフィールド値 |
401 Unauthorized |
認証失敗 | トークンの欠落または期限切れ |
403 Forbidden |
権限不足 | ロールにウィンドウまたはレコードへのアクセス権がない |
404 Not Found |
リソースが見つからない | 無効なウィンドウスラッグまたはレコード ID |
500 Internal Server Error |
サーバーエラー | ビジネスルール違反、データベース制約 |
エラーレスポンスには、失敗の詳細を含む JSON ボディが含まれます:
{
"title": "Save error",
"status": 500,
"detail": "Cannot delete record because it is referenced by other records."
}
セキュリティの考慮事項
API を公開すると、iDempiere インストールに攻撃対象領域が追加されます。デプロイメントを保護するために、以下のベストプラクティスに従ってください。
CORS 設定
Cross-Origin Resource Sharing(CORS)は、ブラウザから API リクエストを行えるドメインを制御します。信頼できるオリジンのみを許可するように CORS を設定します:
- 本番環境では、ワイルドカード(
*)を使用せず、許可するオリジンを特定のドメインに制限します。 - リバースプロキシ(Apache または Nginx)または iDempiere REST プラグインの設定で CORS ヘッダーを設定します。
API トークンのセキュリティ
- クライアントサイドの JavaScript やモバイルアプリのソースコードにトークンを埋め込まないでください。
- トークンは安全に保存し、HTTPS を通じてのみ送信してください。
- トークンローテーションを実装してください — 定期的に再認証して新しいトークンを取得します。
- API アクセスには最小限の必要な権限を持つロールを使用してください。統合に必要な特定のウィンドウとレコードへのアクセスのみを付与する専用の API ロールを作成してください。
レート制限
iDempiere には組み込みのレート制限は含まれていませんが、リバースプロキシを使用してインフラストラクチャレベルで実装する必要があります:
# Nginx レート制限の例
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://localhost:8080;
}
HTTPS
本番環境では常に HTTPS を使用して API トラフィックを暗号化してください。リバースプロキシまたはロードバランサーで SSL/TLS ターミネーションを設定してください。暗号化されていない HTTP 接続を介して認証トークンを送信しないでください。
一般的な統合パターン
REST API を通じて外部システムを iDempiere と統合するための実用的なパターンをいくつか紹介します。
EC 受注同期
オンラインストアの受注を iDempiere に同期します:
- 認証してトークンを取得します。
$filter付きの GET を使用してビジネスパートナーを検索するか、見つからない場合は POST で作成します。/windows/sales-orderへの POST で受注ヘッダーを作成します。- 各カート商品に対して
/windows/sales-order/{id}/order-lineへの POST で受注明細行を作成します。 - 伝票アクション PUT を使用して受注を完了します。
在庫ポーリング
外部システムは iDempiere をポーリングして現在の在庫レベルを取得できます:
# 製品在庫(手持在庫)を取得
curl -X GET \
'http://localhost:8080/api/v1/windows/material-receipt?$filter=M_Product_ID eq 134&$select=QtyOnHand' \
-H 'Authorization: Bearer <token>'
レポートデータの抽出
ビジネスインテリジェンスツールは、特定のフィルタとフィールド選択を使用して API をクエリし、ダッシュボードやレポート用のデータを抽出できます。必要に応じて大規模な結果セットをページネーションで取得します。
まとめ
iDempiere REST API は、iDempiere をスタンドアロンの ERP から統合可能なプラットフォームへと変革します。トークンを使用した認証、完全な CRUD 操作の実行、効率的なデータ取得のためのクエリパラメータの活用、エラーの適切な処理、API デプロイメントのセキュリティ確保について学びました。次のレッスンでは、この基盤の上に構築し、独自のビジネスロジックを外部システムに公開するカスタム REST エンドポイントを作成します。