This is an automated email from the ASF dual-hosted git repository. diveshdut pushed a commit to branch codex/sync-ai-agent-rest-skills in repository https://gitbox.apache.org/repos/asf/ofbiz-plugins.git
commit 4fa62f1142aeb2e4332c40a383e8b23e68a4ffd0 Author: diveshdut <[email protected]> AuthorDate: Fri Jul 10 14:31:19 2026 +0530 Add REST API guidance to AI agent skills --- ai-agent-skills/SKILLS_SUMMARY.md | 1 + ai-agent-skills/manage-api-integration/SKILL.md | 16 +++- ai-agent-skills/manage-rest-api/SKILL.md | 89 ++++++++++++++++++++++ .../references/rest-contract-checklist.md | 39 ++++++++++ .../references/service-wrapper-patterns.md | 67 ++++++++++++++++ 5 files changed, 209 insertions(+), 3 deletions(-) diff --git a/ai-agent-skills/SKILLS_SUMMARY.md b/ai-agent-skills/SKILLS_SUMMARY.md index 89a4afc42..1057ac4ac 100644 --- a/ai-agent-skills/SKILLS_SUMMARY.md +++ b/ai-agent-skills/SKILLS_SUMMARY.md @@ -60,6 +60,7 @@ This document provides a high-level summary of the specialized skills developed | Skill | Description | | :--- | :--- | | **manage-api-integration** | Expose services via REST or SOAP and handle JSON/XML data mapping. | +| **manage-rest-api** | Design, refactor, and verify OFBiz REST APIs with native services and contract-safe wrappers. | | **manage-email-services** | Configure SMTP, manage email templates, and automate outgoing communications. | ## 🔐 Advanced Management diff --git a/ai-agent-skills/manage-api-integration/SKILL.md b/ai-agent-skills/manage-api-integration/SKILL.md index 86a164da0..5b325fe90 100644 --- a/ai-agent-skills/manage-api-integration/SKILL.md +++ b/ai-agent-skills/manage-api-integration/SKILL.md @@ -28,7 +28,9 @@ Integration patterns for exposing OFBiz services via REST and SOAP, and handling ## REST API (rest-api) -OFBiz uses the `rest-api` (based on Jersey) to declaratively expose services. +OFBiz uses the `rest-api` plugin (based on Jersey) to declaratively expose services. + +For REST API design/refactoring, wrapper decisions, contract safety, and PWA/API consumer compatibility, also read the `manage-rest-api` skill. This skill remains the broader integration guide for REST mechanics, SOAP integration, and controller JSON responses. ### REST API Definitions @@ -58,6 +60,13 @@ Parameter mapping from REST requests to OFBiz services is **implicit**. The `res All extracted parameters are aggregated into a single context. The `ServiceRequestHandler` then uses `dispatcher.getDispatchContext().makeValidContext()` to select only those parameters that are defined as IN parameters for the target service. +When implementing endpoint logic, do not assume helper methods from a local `RestApiUtil` or similar framework utility exist in upstream OFBiz. Verify helper availability in the target branch before using it; otherwise prefer service typing, `EntityQuery`, and small local logic. + +### Multi-Column Keys +When a REST operation targets an OFBiz entity keyed by multiple columns, prefer sending the native key fields in the request body for create, update, and remove operations. This often allows the REST endpoint or client to call native OFBiz services directly instead of adding wrapper services only to decode a composite path ID. + +Use a stable composite REST ID only when the API shape truly needs a single identifier segment, such as a list/detail link or a client-side row key. Keep composite ID encoding at the API edge and do not distort the underlying OFBiz entity or service model. + ### Security and Response Handling * **Authentication:** Controlled by the `auth="true|false"` attribute on the `<operation>` element. * **Responses:** Services return their OUT parameters (excluding internal ones) as a JSON object. The response is automatically prefixed with `&&&START&&&` for XSSI protection. @@ -72,7 +81,7 @@ OFBiz allows services to be exposed as REST APIs directly via attributes in the ### Pattern: - **Attributes**: Set `export="true"` and `action="VERB"` (e.g., `action="GET"`). -- **Result**: The service becomes reachable as a REST endpoint (e.g., `/rest/public/findProductById` or similar depending on the rest-api plugin configuration). +- **Result**: The service becomes reachable as a REST endpoint (e.g., `/rest/public/findProductById` or similar depending on the `rest-api` plugin configuration). ```xml <service name="findProductById" engine="java" auth="true" export="true" action="GET" ...> @@ -83,6 +92,7 @@ OFBiz allows services to be exposed as REST APIs directly via attributes in the ### Key Considerations: - **Simplicity**: No need for separate `rest.xml` or controller mappings. - **Contract-first**: The service signature defines the API request/response. +- **Native OFBiz Types**: Prefer `Timestamp`, `BigDecimal`, `Double`, `Long`, and similar native types in service attributes so the Service Engine performs coercion before service logic runs. - **Auth**: Inherits service engine authentication rules. ## JSON Responses @@ -122,6 +132,6 @@ Use the `soap-engine` or `SOAPClientEngine`. ## Security & Data Mapping -- **Authentication**: REST API typically uses JWT or API Keys (configured in `rest-api` common filters). +- **Authentication**: REST API authentication depends on the `rest-api` plugin configuration and the invoked service security. - **Permissions**: Every service invoked should have proper `permission-service` or `check-permission` logic. - **Data Mapping**: JSON/XML fields must precisely match service IN attributes for automatic mapping. Use `ServiceUtil.getAndValidateParameters` pattern in custom Java events if manual mapping is needed. diff --git a/ai-agent-skills/manage-rest-api/SKILL.md b/ai-agent-skills/manage-rest-api/SKILL.md new file mode 100644 index 000000000..a7c656cfa --- /dev/null +++ b/ai-agent-skills/manage-rest-api/SKILL.md @@ -0,0 +1,89 @@ +--- +name: manage-rest-api +description: Design, expose, refactor, and verify OFBiz REST APIs using the `rest-api` plugin, service engine contracts, native OFBiz services, and contract-safe wrapper patterns. Use when working with `.rest.xml` files, REST-exposed services, PWA/API consumers, service export settings, or backend REST response contracts. +--- + +# Skill: Manage REST APIs + +## Goal +Build OFBiz REST APIs that are thin, service-native, contract-safe, and easy to upstream into OFBiz. + +Use OFBiz services, service definitions, entity utilities, and `rest-api` plugin conventions first. Add REST wrapper services only when they adapt a transport contract, aggregate read data, or preserve compatibility for an existing consumer. + +For low-level REST XML syntax, direct service export mechanics, SOAP integration, or controller JSON response patterns, also read the `manage-api-integration` skill. + +## Core Workflow +1. **Map the contract first** + - Find the REST mapping, service definition, service implementation, and active consumers. + - Search frontend/API clients before removing request parameters or response fields. + - Identify whether the endpoint is a generic service API, a read aggregate, or a compatibility adapter. + +2. **Prefer native OFBiz services** + - Reuse existing services before creating wrapper services. + - Expose native services directly when their inputs and outputs are already suitable for the REST contract. + - Keep write wrappers thin: resolve REST convenience parameters, delegate to native services, return the agreed response shape. + +3. **Let the service engine validate and coerce** + - Define service attributes with precise native types such as `Timestamp`, `BigDecimal`, `Double`, `Long`, and `Integer`. + - Avoid manual parsing in Groovy/Java when service XML already declares the correct type. + - Use OFBiz conversion utilities only when conversion is genuinely needed inside service logic. + +4. **Use native query and paging utilities** + - Prefer `EntityQuery`, `filterByDate`, `queryCount`, and helper methods that already exist in the target codebase over custom query loops. + - Avoid N+1 queries by batch-loading related data and mapping in memory. + - Use database-level filtering/counting where possible instead of loading full rows and filtering manually. + +5. **Promote shared mechanics carefully** + - Reuse existing OFBiz/framework/component utilities before adding local helpers. + - Promote repeated mechanical patterns to the narrowest appropriate shared utility. + - Do not promote domain-specific behavior into generic utilities just because the method is small. + +6. **Verify with project-standard checks** + - Run the repository's standard backend compilation, static analysis, and relevant tests. + - Use the runtime/JDK version required by the project build configuration. + - If a full check is blocked by environment or unrelated project issues, run the narrowest equivalent verification and report that it was targeted. + +## Upstream Safety +- Do not assume local-only framework helpers are available in upstream OFBiz just because they exist in a developer's local framework checkout. +- Before using a helper for paging, partial-list slicing, case-insensitive parameter lookup, composite REST ID handling, or REST error shaping, confirm that the helper exists in the target repository/branch. +- If a helper is not present upstream, prefer native `EntityQuery`, service engine typing/validation, and small local endpoint logic over referencing non-existent framework APIs. + +## Wrapper Decision Rules +Create or keep a wrapper when it: +- Aggregates multiple native service/entity reads for a REST/PWA screen. +- Preserves a published REST contract that differs from native OFBiz service shape. +- Resolves REST-friendly identifiers into native key fields when the client cannot send native keys directly. +- Adds read-side display metadata that avoids excessive client round trips. + +Remove or avoid a wrapper when it: +- Only duplicates a native CRUD service call. +- Manually validates what the service definition or native service already validates. +- Re-parses typed service parameters. +- Adds local formatting/conversion helpers already available in OFBiz. + +Read [service-wrapper-patterns.md](references/service-wrapper-patterns.md) before adding or removing wrapper services. + +## Contract Safety +Before changing a REST response: +- Search active consumers for every field you plan to remove. +- Update frontend/client mappers and tests in the same change when intentionally changing a contract. +- Keep compatibility fields only when still used or intentionally supported. +- Prefer stable semantic field names over implementation-detail names. + +Read [rest-contract-checklist.md](references/rest-contract-checklist.md) before changing existing API inputs, paths, response fields, or service export settings. + +## REST Mapping Guidance +- Keep REST XML mappings declarative and close to service names. +- Prefer path parameters for stable resource identity and query parameters for filtering/paging. +- Use request bodies for create/update/remove payloads, especially when native OFBiz services require multiple key fields. +- For multi-column keys, prefer native key fields in the body when that enables direct native service use. Use a stable composite REST identifier only when the REST contract truly needs one path/id value. Do not distort the underlying entity model. +- Ensure services exposed through REST are intentionally exported and authorized. + +## Utility Promotion Test +Before adding a helper, answer: +- Is this already available in OFBiz? +- Is this repeated mechanical logic, or domain behavior? +- Is the helper useful outside this one endpoint? +- What is the narrowest appropriate owner: existing framework utility, component utility, or local script? + +Good utility candidates are mechanical patterns such as batch lookup, case-insensitive ID search, pagination wrappers, or composite ID creation, but only when those helpers already exist in the target codebase or are being introduced in the same change. Poor candidates are domain queries such as "routing task associations" or "BOM component rows"; keep those near the service that owns the domain meaning. diff --git a/ai-agent-skills/manage-rest-api/references/rest-contract-checklist.md b/ai-agent-skills/manage-rest-api/references/rest-contract-checklist.md new file mode 100644 index 000000000..c72253cb6 --- /dev/null +++ b/ai-agent-skills/manage-rest-api/references/rest-contract-checklist.md @@ -0,0 +1,39 @@ +# REST Contract Checklist + +Use this checklist before changing existing OFBiz REST endpoints or service exports. + +## Discover +- Find the `.rest.xml` operation or direct service export. +- Find the service definition and implementation. +- Find active consumers, including PWAs, tests, scripts, and API clients. +- Confirm whether the endpoint is public, authenticated, or internal. + +## Inputs +- Preserve path, query, and body parameter names unless consumers are updated together. +- Prefer precise service attribute types so the service engine handles validation and coercion. +- Avoid manual parsing of already-typed service parameters. +- Keep required/optional flags aligned with real REST usage. +- Confirm service `export` settings are intentional for REST access. + +## Outputs +- Search consumers before removing any response field. +- Keep fields that drive visible UI, filters, badges, links, or client-side update/delete calls. +- Remove unused metadata when contract consumers are updated and tests cover the change. +- Avoid returning native internal fields that are not part of the REST contract. +- Do not stringify timestamps, quantities, or money unless the endpoint is explicitly presentation/export oriented. + +## Paths and Keys +- Prefer stable resource paths for common single-key resources. +- For multi-column native keys, prefer request-body fields for create/update/remove operations when that enables native OFBiz service calls. +- Use composite REST IDs only when the contract truly needs one path/id value, and keep encoding/decoding at the API edge. +- Do not modify OFBiz entity keys just to make REST paths shorter. + +## Compatibility +- If a frontend/PWA uses a legacy field name, either preserve it or update the frontend/client mapper in the same change. +- When simplifying payloads, update type definitions, mappers, and contract tests together. +- Document intentional contract changes in the commit/PR summary. + +## Verification +- Run project-standard backend compile/static analysis/tests. +- Run consumer contract tests when clients are in scope. +- If only targeted verification was possible, state exactly what was and was not verified. diff --git a/ai-agent-skills/manage-rest-api/references/service-wrapper-patterns.md b/ai-agent-skills/manage-rest-api/references/service-wrapper-patterns.md new file mode 100644 index 000000000..8a86147fd --- /dev/null +++ b/ai-agent-skills/manage-rest-api/references/service-wrapper-patterns.md @@ -0,0 +1,67 @@ +# Service Wrapper Patterns + +Use these patterns when deciding whether a REST-facing service should exist. + +## Prefer Direct Native Service Exposure +Use an existing OFBiz service directly when: +- The service already performs the business operation. +- The service attributes match the REST inputs closely. +- The output is acceptable to the consumer. +- The service has correct validation, auth, and export settings. + +Do not create a wrapper only to copy fields from REST input to the same native service input. + +## Thin Write Adapter +Use a thin wrapper when REST uses convenience parameters that differ from native keys and the client cannot reasonably send native key fields directly. + +The wrapper should: +- Validate only what the service definition cannot express. +- Resolve convenience identifiers into native service fields. +- Call the native OFBiz service. +- Check `ServiceUtil.isError(result)` and return the native error when appropriate. +- Return only the agreed REST response fields. + +Avoid adding duplicate business validation already enforced by the native service. + +## Read Aggregate Wrapper +Use a read wrapper when one API call intentionally serves a screen or workflow by combining data from several entities/services. + +The wrapper should: +- Batch-load related records instead of querying per row. +- Use `EntityQuery`, `filterByDate`, `queryCount`, and paging helpers. +- Keep response fields screen/use-case oriented, not raw database dumps. +- Avoid heavy summaries that are not displayed or otherwise consumed. + +## Lookup/Search Endpoint +Use a lookup endpoint when multiple clients need the same typeahead or option list. + +The service should: +- Accept generic filters where practical. +- Use case-insensitive search helpers or OFBiz-native search utilities only when they already exist in the target codebase. +- Page or cap result sizes. +- Return stable IDs plus display names/labels. +- Avoid embedding one component's business assumptions into a generic lookup. + +## Utility Promotion +Promote helper code only when it is repeated mechanical logic. + +Good candidates: +- Load entities by ID list and return a map keyed by ID. +- Search an entity across configured fields and return IDs. +- Count/group rows by a selected field. +- Build stable composite identifiers from key parts. + +When a candidate depends on helper methods that are only present in a local framework checkout, do not reference those helpers in upstream-targeted work unless the same change also introduces them upstream. + +Poor candidates: +- Domain relationship queries. +- Screen-specific payload assembly. +- Business validation rules. +- Helpers used by only one endpoint with no clear reuse. + +## Deletion Check +Before deleting a wrapper: +- Confirm the native service is exported and authorized correctly. +- Confirm REST clients can send the native key fields. +- Confirm response handling still works, or update client mappers/tests. +- Keep a wrapper if it protects clients from unstable internal service details.

