AI Fitness & Nutrition Coach - Frontend Development Prompts

AI-assisted frontend development prompts for AI Fitness & Nutrition Coach

This document contains all frontend development prompts that can be used to build the user interface for this project. Each prompt provides detailed specifications for implementing specific frontend features.


Table of Contents


Introduction

Project Overview

AI Fitness & Nutrition Coach

Version : 1.0.146

aifitapp is a subscription-based, AI-powered fitness and nutrition platform that generates personalized training programs and dietary plans using evidence-based principles. Users interact with an intelligent chatbot to receive customized workout regimes, meal recommendations, exercise and food alternatives, and educational guidance—all governed by strict safety and scientific protocols.

How to Use Project Documents

The Aifitapp project has been designed and generated using Mindbricks, a powerful microservice-based backend generation platform. All documentation is automatically produced by the Mindbricks Genesis Engine, based on the high-level architectural patterns defined by the user or inferred by AI.

This documentation set is intended for both AI agents and human developers—including frontend and backend engineers—who need precise and structured information about how to interact with the backend services of this project. Each document reflects the live architecture of the system, providing a reliable reference for API consumption, data models, authentication flows, and business logic.

By following this documentation, developers can seamlessly integrate with the backend, while AI agents can use it to reason about the service structure, make accurate decisions, or even generate compatible client-side code.

Accessing Project Services

Each service generated by Mindbricks is exposed via a dedicated REST API endpoint. Every service documentation set includes the base URL of that service along with the specific API paths for each available route.

Before consuming any API, developers or agents must understand the service URL structure and environment-specific endpoints.

Service Endpoint Structure

Environment URL Pattern Example
Preview https://appaili.prw.mindbricks.com/auth-api
Staging https://appaili-stage.mindbricks.co/auth-api
Production https://appaili.mindbricks.co/auth-api

Replace auth with the actual service name as lower case (e.g., order-api, bff-service, customermanagement-api etc.).

Environment Usage Notes

Frontend applications should be designed to easily switch between environments, allowing dynamic endpoint targeting for Preview, Staging, and Production.

Getting Started: Use the Auth Service First

Before interacting with other services in the Aifitapp project, AI agents and developers should begin by integrating with the Auth Service.

Mindbricks automatically generates a dedicated authentication microservice based on the project’s authentication definitions provided by the architect. This service provides the essential user and access management foundation for the project.

Agents should first utilize the Auth Service to:

Auth Service Documentation

Use the following resources to understand and integrate the Auth Service:

Note: For most frontend use cases, the REST API Guide will be the primary source. The Event Guide and Service Design documents are especially useful when integrating with other backend microservices or building systems that interact with the auth service indirectly.

Using the BFF (Backend-for-Frontend) Service

In Mindbricks, all backend services are designed with an advanced CQRS (Command Query Responsibility Segregation) architecture. Within this architecture, business services are responsible for managing their respective domains and ensuring the accuracy and freshness of domain data.

The BFF service complements these business services by providing a read-only aggregation and query layer tailored specifically for frontend and client-side applications.

Key Principles of the BFF Service

BFF Service Documentation

Tip: Use the BFF service as the main entry point for all frontend data queries. It simplifies access, reduces round-trips, and ensures that data is shaped appropriately for the UI layer.

Business Services Overview

The AI Fitness & Nutrition Coach project consists of multiple business services, each responsible for managing a specific domain within the system. These services expose their own REST APIs and documentation sets, and are accessible based on the environment (Preview, Staging, Production).

Usage Guidance

Business services are primarily designed to:

For advanced query needs across multiple services or aggregated views, prefer using the BFF service.

Available Business Services

aiCoach Service

Description: AI-powered fitness coaching service that generates personalized evidence-based training programs and nutrition plans, manages chatbowt interactions with full validation chains, handles dynamic program modifications via AI tool calls, tracks weaight measurements, enforces moderation and quotas, and provides admin endpoints for moderation history and usage analytics.a

Documentation:

Base URL Examples:

Environment URL
Preview https://appaili.prw.mindbricks.com/aicoach-api
Staging https://appaili-stage.mindbricks.co/aicoach-api
Production https://appaili.mindbricks.co/aicoach-api

subscription Service

Description: Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z

Documentation:

Base URL Examples:

Environment URL
Preview https://appaili.prw.mindbricks.com/subscription-api
Staging https://appaili-stage.mindbricks.co/subscription-api
Production https://appaili.mindbricks.co/subscription-api

agentHub Service

Description: AI Agent Hub

Documentation:

Base URL Examples:

Environment URL
Preview https://appaili.prw.mindbricks.com/agenthub-api
Staging https://appaili-stage.mindbricks.co/agenthub-api
Production https://appaili.mindbricks.co/agenthub-api

Connect via MCP (Model Context Protocol)

All backend services in the Aifitapp project expose their Business APIs as MCP tools. These tools are aggregated by the MCP-BFF service into a single unified endpoint that external AI tools can connect to.

Unified MCP Endpoint

Environment StreamableHTTP (recommended) SSE (legacy fallback)
Preview https://appaili.prw.mindbricks.com/mcpbff-api/mcp https://appaili.prw.mindbricks.com/mcpbff-api/mcp/sse
Staging https://appaili-stage.mindbricks.co/mcpbff-api/mcp https://appaili-stage.mindbricks.co/mcpbff-api/mcp/sse
Production https://appaili.mindbricks.co/mcpbff-api/mcp https://appaili.mindbricks.co/mcpbff-api/mcp/sse

Authentication

MCP connections require authentication via the Authorization header:

OAuth is not supported for MCP connections at this time.

Connecting from Cursor

Add the following to your project’s .cursor/mcp.json:

{
  "mcpServers": {
    "appaili": {
      "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp",
      "headers": {
        "Authorization": "Bearer sk_mbx_your_api_key_here"
      }
    }
  }
}

Connecting from Claude Desktop

Add to your Claude Desktop configuration (claude_desktop_config.json):

{
  "mcpServers": {
    "appaili": {
      "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp",
      "headers": {
        "Authorization": "Bearer sk_mbx_your_api_key_here"
      }
    }
  }
}

What’s Available

Once connected, the AI tool can discover and call all Business API tools from all services — CRUD operations, custom queries, file operations, and more. The MCP-BFF handles routing each tool call to the correct backend service and propagates your authentication context.


Conclusion

This documentation set provides a comprehensive guide for understanding and consuming the AI Fitness & Nutrition Coach backend, generated by the Mindbricks platform. It is structured to support both AI agents and human developers in navigating authentication, data access, service responsibilities, and system architecture.

To summarize:

Each service offers a complete set of documentation—REST API guides, event interface definitions, and design insights—to help you integrate efficiently and confidently.

Whether you are building a frontend application, configuring an automation agent, or simply exploring the architecture, this documentation is your primary reference for working with the backend of this project.

For environment-specific access, ensure you’re using the correct base URLs (Preview, Staging, Production), and coordinate with the project owner for any custom deployments.


How to Use These Prompts

These prompts are designed to be used with AI coding assistants to help build frontend features. Each prompt includes:

  1. Feature Description - What the feature does and its purpose
  2. Data Models - The backend data structures to work with
  3. API Endpoints - Available REST APIs for the feature
  4. UI Requirements - Specific user interface requirements
  5. Implementation Guidelines - Best practices and patterns to follow

When using these prompts with an AI assistant:


Frontend Development Prompts

AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Project Introduction & Setup

This is the introductory document for the aifitapp frontend project. It is designed for AI agents that will generate frontend code to consume the project’s backend. Read it carefully — it describes the project scope, architecture, API conventions, and initial screens you must build before proceeding to the feature-specific prompts that follow.

This prompt will help you set up the project infrastructure, create the initial layout, home page, navigation, and any dummy screens. The subsequent prompts will provide detailed API documentation for each feature area.

Project Introduction

aifitapp is a subscription-based, AI-powered fitness and nutrition platform that generates personalized training programs and dietary plans using evidence-based principles. Users interact with an intelligent chatbot to receive customized workout regimes, meal recommendations, exercise and food alternatives, and educational guidance—all governed by strict safety and scientific protocols.

Project Services Overview

The project has 1 auth service, 1 notification service, 1 BFF service, and 3 business services, plus other helper services such as bucket and realtime.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

# Service Description API Prefix
1 auth Authentication and user management /auth-api
2 aiCoach AI-powered fitness coaching service that generates personalized evidence-based training programs and nutrition plans, manages chatbowt interactions with full validation chains, handles dynamic program modifications via AI tool calls, tracks weaight measurements, enforces moderation and quotas, and provides admin endpoints for moderation history and usage analytics.a /aiCoach-api
3 subscription Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z /subscription-api
4 agentHub AI Agent Hub /agentHub-api

Detailed API documentation for each service will be given in the following prompts. In this document, you will build the initial project structure, home pages, and navigation.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Accessing the Backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

The base URL of the application in each environment is as follows:

For the auth service, the base URLs are:

For each other service, append /{serviceName}-api to the environment base URL.

Any request that requires login must include a valid token in the Bearer authorization header.

Please note that for each service in the project (which will be introduced in following prompts) will use a different address so it is a good practice to define a separate client for each service in the frontend application lib source. Not only the different base urls, some services even may need different access rules when shaping the request.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Home Page

First build a home page which shows some static content about the application, and has got login and registration (if is public) buttons. The home page should be updated later according to the content that each service provides, as a frontend developer use best and common practices to reflect the service content to the home page. User may also give extra information for the home page content in addition to this prompt.

Note that this page should include a deployment (environment) selection option to set the base URL. Set the default to production.

After user logs in, page header should show the current login state as in modern web pages, logged in user fullname, avatar, email and with a logout link, make a fancy current user component. The home page may have different views before and after login.

Initial Navigation Structure

Build the initial navigation/sidebar with placeholder pages for each area of the application. These will be implemented in detail by the subsequent prompts:

Create these as placeholder/dummy pages with a title and “Coming soon” note. They will be filled in by the following prompts.

What To Build Now

With this prompt, build:

  1. Project infrastructure — routing, layout, environment config, API client setup (one client per service)
  2. Home page with environment selector, login/register buttons, project description
  3. Placeholder pages for all navigation items listed above
  4. Common components — header with user info, navigation sidebar/menu, layout wrapper

Do not implement authentication flows, registration, or any service-specific features yet — those will be covered in the next prompts.

Common Reminders

  1. When the application starts, please ensure that the baseUrl is set to the production server URL, and that the environment selector dropdown has the Production option selected by default.
  2. Note that any API call to the application backend is based on a service base URL. Auth APIs use /auth-api prefix, and each business service uses /{serviceName}-api prefix after the application’s base URL.
  3. The deployment environment selector will only be used in the home page. If any page is called directly bypassing the home page, the page will use the stored or default environment.

AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Authentication Management

This document covers the authentication features of the aifitapp project: registration, login, logout, and session management. The project introduction, API conventions, base URLs, home page, and multi-tenancy setup were covered in the previous introductory prompt — make sure those are implemented before proceeding.

All auth APIs use the auth service base URL with the /auth-api prefix (e.g., https://appaili.mindbricks.co/auth-api).

FRONTEND_URL

The FRONTEND_URL environment variable is automatically set on the auth service from the project’s frontendUrl setting in Basic Project Settings. It contains the base URL of the frontend application for the current deployment environment (e.g., http://localhost:5173 for dev, https://myapp.com for production). Defaults if not configured:

Environment Default
dev http://localhost:5173
test https://appaili.prw.mindbricks.com
stage https://appaili-stage.mindbricks.co
prod https://appaili.mindbricks.co

This variable is used by the auth service for:

You can customize FRONTEND_URL per environment by configuring the frontendUrl field in your project’s Basic Project Settings (e.g., when using a custom domain).

Registration Management

User Registration

User registration is public in the application. Please create a simple and polished registration page that includes only the necessary fields of the registration API.

Using the registeruser route of the auth API, send the required fields from your registration page.

The registerUser API in the auth service is described with the request and response structure below.

Note that since the registerUser API is a business API, it is versioned; call it with the given version like /v1/registeruser.

Register User API

This api is used by public users to register themselves

Rest Route

The registerUser API REST controller can be triggered via the following route:

/v1/registeruser

Rest Request Parameters

The registerUser api has got 15 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
email String true request.body?.[“email”]
activityLevel Enum false request.body?.[“activityLevel”]
availableEquipment String false request.body?.[“availableEquipment”]
country String false request.body?.[“country”]
dateOfBirth Date false request.body?.[“dateOfBirth”]
dietaryRestrictions String false request.body?.[“dietaryRestrictions”]
fitnessGoal Enum false request.body?.[“fitnessGoal”]
height Float false request.body?.[“height”]
sex Enum true request.body?.[“sex”]
trainingExperience Enum false request.body?.[“trainingExperience”]
weeklyTrainingDays Integer false request.body?.[“weeklyTrainingDays”]
weight Float false request.body?.[“weight”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
password : The password defined by the the user that is being registered.
fullname : The fullname defined by the the user that is being registered.
email : The email defined by the the user that is being registered.
activityLevel : User’s general daily activity level, used as the TDEE activity multiplier.
availableEquipment : List of equipment available to the user for training program generation.
country : User’s country of residence, used for regional food suggestions and cuisine preferences.
dateOfBirth : User’s date of birth, used for age-based calorie and program calculations.
dietaryRestrictions : List of user dietary restrictions or allergies for meal plan customization.
fitnessGoal : User’s primary fitness goal driving program and nutrition recommendations.
height : User’s height in centimeters, used for BMR and TDEE calculations.
sex : User’s biological sex, used for BMR calculations and program customization.
trainingExperience : User’s training experience level, influencing program complexity and progression rates.
weeklyTrainingDays : Number of days per week the user is available to train, used for program split selection.
weight : User’s current body weight in kilograms, used for calorie and macro calculations.

REST Request To access the api you can use the REST controller with the path POST /v1/registeruser

  axios({
    method: 'POST',
    url: '/v1/registeruser',
    data: {
            avatar:"String",  
            password:"String",  
            fullname:"String",  
            email:"String",  
            activityLevel:"Enum",  
            availableEquipment:"String",  
            country:"String",  
            dateOfBirth:"Date",  
            dietaryRestrictions:"String",  
            fitnessGoal:"Enum",  
            height:"Float",  
            sex:"Enum",  
            trainingExperience:"Enum",  
            weeklyTrainingDays:"Integer",  
            weight:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After a successful registration, the frontend code should handle any verification requirements. Verification Management will be given in the next prompt.

The registration response will include a user object in the root envelope; this object contains user information with an id field.

Login Management

Login Identifier Model

The primary login identifier for this application is the email address. Users register and log in using their email and password. No mobile field is stored in the user data model. The login page should include an email input and a password input.

Login Flow

After successful registration and completing any required verifications, the user can log in. Please create a minimal, polished login page as described above. Note that this page should respect the deployment (environment) selection option made in the home page to set the base URL. If the user reaches this page directly skipping home page, the default production deployment will be used.

The login API returns a created session. This session can be retrieved later with the access token using the /currentuser system route.

Any request that requires login must include a valid token. When a user logs in successfully, the response JSON includes a JWT access token in the accessToken field. Under normal conditions, this token is also set as a cookie and consumed automatically. However, since AI coding agents’ preview options may fail to use cookies, ensure that each request includes the access token in the Bearer authorization header.

If the login fails due to verification requirements, the response JSON includes an errCode. If it is EmailVerificationNeeded, start the email verification flow; if it is MobileVerificationNeeded, start the mobile verification flow.

After a successful login, you can access session (user) information at any time with the /currentuser API. On inner pages, show brief profile information (avatar, name, etc.) using the session information from this API.

Note that the currentuser API returns a session object, so there is no id property; instead, the values for the user and session are exposed as userId and sessionId. The response combines user and session information.

The login, logout, and currentuser APIs are as follows. They are system routes and are not versioned.

POST /login — User Login

Purpose: Verifies user credentials and creates an authenticated session with a JWT access token.

Access Routes:

Request Parameters

Parameter Type Required Source
username String Yes request.body.username
password String Yes request.body.password

Behavior

Example

axios.post("/login", {
  email: "user@example.com",
  password: "securePassword"
});

Success Response

{
  "sessionId": "e81c7d2b-4e95-9b1e-842e-3fb9c8c1df38",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  //...
  "accessToken": "ey7....",
  "userBucketToken": "e56d....",
  "sessionNeedsEmail2FA": true,
  "sessionNeedsMobile2FA": true,

}

Note on bucket tokens: The userBucketToken is for the external bucket service (used for general file uploads like documents and product images). User avatars do not use the external bucket service — they are uploaded via database buckets (dbBuckets) built into the auth service using the regular accessToken. See the Profile or Bucket Management sections for dbBucket avatar upload details.

Two-Factor Authentication (2FA): When the login response contains sessionNeedsEmail2FA: true or sessionNeedsMobile2FA: true, the session is not yet fully authorized. The accessToken is valid but all protected API calls will return 403 until 2FA is completed. Do not treat this login as successful — instead, store the accessToken, userId, and sessionId, and navigate the user to a 2FA verification page. The 2FA flow details are covered in the Verification Management prompt.

Error Responses


POST /logout — User Logout

Purpose: Terminates the current session and clears associated authentication tokens.

Behavior

Example

axios.post("/logout", {}, {
  headers: { "Authorization": "Bearer your-jwt-token" }
});

Notes

Success Response

{ "status": "OK", "message": "User logged out successfully" }

GET /currentuser — Current Session

Purpose Returns the currently authenticated user’s session.

Route Type sessionInfo

Authentication Requires a valid access token (header or cookie).

Request

No parameters.

Example

axios.get("/currentuser", {
  headers: { Authorization: "Bearer <jwt>" }
});

Success (200)

Returns the session object (identity, tenancy, token metadata):

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  "...": "..."
}

Note that the currentuser API returns a session object, so there is no id property, instead, the values for the user and session are exposed as userId and sessionId. The response is a mix of user and session information.

Errors

Notes

After you complete this step, please ensure you have not made the following common mistakes:

  1. The /currentuser API returns a mix of session and user data. There is no id property —use userId and sessionId.
  2. Note that any API call to the auth service should use the /auth-api prefix after the application’s base URL.

After this prompt, the user may give you new instructions to update your output or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Verification Management

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document includes the verification processes for the autheitcation flow. Please read it carefully and implement all requirements described here.

The project has 1 auth service, 1 notification service, 1 BFF service, and 3 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

For the auth service, the base URLs are:

Any request that requires login must include a valid token in the Bearer authorization header.

After User Registration

Frontend should also be aware of verification after any login attempt. The login request may return a 401 or 403 with the error codes that indicates the verification needs.

{
  //...
  "errCode": "EmailVerificationNeeded",
  // or
  "errCode": "MobileVerificationNeeded",
}

Email Verification

In the registration response, check the emailVerificationNeeded property in the response root. If it is true, start the email verification flow.

After the login process, if you receive an HTTP error and the response contains an errCode with the value EmailVerificationNeeded, start the email verification flow.

  1. Call the email verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the provided email address. The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the secretCode property of the response.
  2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. If the secretCode is sent to the frontend for testing, display it on the input page so the user can copy and paste it.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen.
  4. When the user submits the code, complete the email verification using the complete route of the backend (described below) with the user’s email and the secret code.
  5. After a successful email verification response, please check the response object to have the property ‘mobileVerificationNeeded’ as true, if so navigate to the mobile verification flow as described below. If no mobile verification is needed then just navigate the login page.

Below are the start and complete routes for email verification. These are system routes and therefore are not versioned.

POST /verification-services/email-verification/start

Purpose: Starts email verification by generating and sending a secret code.

Parameter Type Required Description
email String Yes User’s email address to verify

Example Request

{ "email": "user@example.com" }

Success Response

{
  "status": "OK", 
  "codeIndex": 1,
  // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
  // expireTime: in seconds
  "expireTime": 86400,
  "verificationType": "byLink",

  // in testMode
  "secretCode": "123456",
  "userId": "user-uuid"
}

⚠️ In production, secretCode is not returned — it is only sent via email.

Error Responses


POST /verification-services/email-verification/complete

Purpose: Completes verification using the received code.

Parameter Type Required Description
email String Yes User’s email
secretCode String Yes Verification code

Success Response

{
  "status": "OK", 
  "isVerified": true,
  "email": "user@email.com",
  // in testMode
  "userId": "user-uuid"
}

Error Responses


Mobile Verification

Mobile numbers must be in E.164 format (+ followed by country code and subscriber number, e.g. +905551234567). Use the PhoneInput component for mobile number inputs on verification pages.

In the registration response, check the mobileVerificationNeeded property in the response root. If it is true, start the mobile verification flow.

After the login process, if you receive a 403 error and the response contains an errCode with the value MobileVerificationNeeded, start the mobile verification flow.

  1. Call the mobile verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the user’s mobile number. If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the secretCode property.
  2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. If the secretCode is returned for testing, display it on the input page for easy copy/paste.
  3. When the user submits the code, complete mobile verification using the complete route of the backend (described below) with the user’s email and the secret code.
  4. The start response includes a codeIndex property. Display its value on the input page so the user can match the index shown in the message with the one on the screen.
  5. After a successful mobile verification response, navigate to the login page.

Verification Order If both emailVerificationNeeded and mobileVerificationNeeded are true, handle both verification flows in order. First complete email verification, then mobile verification.

Below are the start and complete routes for mobile verification. These are system routes and therefore are not versioned.

POST /verification-services/mobile-verification/start

Parameter Type Required Description
email String Yes User’s email to locate mobile record

Success Response

{
  "status": "OK", 
  "codeIndex": 1,
  // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
  // expireTime: in seconds
  "expireTime": 180,
  "verificationType": "byCode",

  // in testMode
  "secretCode": "123456",
  "userId": "user-uuid"
}

⚠️ secretCode is returned only in development.

Errors


POST /verification-services/mobile-verification/complete

Parameter Type Required Description
email String Yes Associated email
secretCode String Yes Code received via SMS

Success Response

{
  "status": "OK", 
  "isVerified": true,
  "mobile": "+1 333 ...",
  // in testMode
  "userId": "user-uuid"
}

Resetting Password

Users can reset their forgotten passwords without a login required, through email and mobile verification. To be able to start a password reset flow, users will click on the “Reset Password” link in the login page.

Since there are two verification methods, by email or by mobile, for password reset, when the reset password link is clicked, frontend should ask user if they want to make the verification through email of mobile. According to the users selection the frontend shoudl start the related flow as explaned below step by step.

Password Reset By Email Flow

  1. Call the password reset by email verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the provided email address. The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the secretCode property of the response.
  2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. If the secretCode is sent to the frontend for testing, display it on the input page so the user can copy and paste it.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen.
  4. The input page should also include a double input area for the user to enter and confirm their new password.
  5. When the user submits the code and the new password, complete the password reset by email using the complete route of the backend (described below) with the user’s email , the secret code and new password.
  6. After a successful verification response, navigate to the login page.

Below are the start and complete routes for password reset by email verification. These are system routes and therefore are not versioned.

POST /verification-services/password-reset-by-email/start

Purpose:
Starts the password reset process by generating and sending a secret verification code.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
{
  "email": "user@example.com"
}

Success Response

Returns secret code details (only in development environment) and confirmation that the verification step has been started.

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "codeIndex": 1,
  "secretCode": "123456", 
  "timeStamp": 1765484354,
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z",
  "verificationType": "byLink",
}

⚠️ In production, the secret code is only sent via email and not exposed in the API response.

Error Responses


POST /verification-services/password-reset-by-email/complete

Purpose:
Completes the password reset process by validating the secret code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via email
password String Yes The new password the user wants to set
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "newSecurePassword123"
}

Success Response

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "isVerified": true
}

Error Responses


Password Reset By Mobile Flow

  1. Call the password reset by mobile verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the user’s mobile number. If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the secretCode property.
  2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. If the secretCode is returned for testing, display it on the input page for easy copy/paste.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen. Also display the half masked mobilenumber that comes in the response, to tell the user that their code is sent to this number.
  4. The input page should also include a double input area for the user to enter and confirm their new password.
  5. When the user submits the code, complete mobile verification using the complete route of the backend (described below) with the user’s email and the secret code.
  6. After a successful mobile verification response, navigate to the login page.

Below are the start and complete routes for password reset by mobile verification. These are system routes and therefore are not versioned.

POST /verification-services/password-reset-by-mobile/start

Purpose:
Initiates the mobile-based password reset by sending a verification code to the user’s mobile.

Request Body

Parameter Type Required Description
email String Yes The email of the user that resets the password
{
  "email": "user@user.com"
}

Success Response

Returns the verification context (code returned only in development):

{
  "status": "OK",
  "codeIndex": 1,
  timeStamp: 133241255,
  "mobile": "+905.....67",
  "secretCode": "123456", 
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z",
  verificationType: "byLink"
}

⚠️ In production, the secretCode is not included in the response and is only sent via SMS.

Error Responses


POST /verification-services/password-reset-by-mobile/complete

Purpose:
Finalizes the password reset process by validating the received verification code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via SMS
password String Yes The new password to assign
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "NewSecurePassword123!"
}

Success Response

{
  "userId": "user-uuid",
  "isVerified": true
}

Two-Factor Authentication (2FA)

This project has email and mobile two-factor authentication enabled. 2FA is different from email/mobile verification: verification proves ownership during registration (one-time), while 2FA runs on every login as an additional security layer.

How 2FA Works After Login

When a user logs in successfully, the login response includes accessToken, userId, sessionId, and all session data. However, when 2FA is active, the response also contains one or both of these flags:

When any of these flags are true, the session is NOT fully authorized. The accessToken is valid only for calling the 2FA verification endpoints. All other protected API calls will return 403 Forbidden with error code EmailTwoFactorNeeded or MobileTwoFactorNeeded until 2FA is completed.

2FA Frontend Flow

  1. After a successful login, check the response for sessionNeedsEmail2FA or sessionNeedsMobile2FA.
  2. If either is true, do not treat the user as authenticated. Store the accessToken, userId, and sessionId temporarily.
  3. Navigate the user to a 2FA verification page.
  4. On the 2FA page, immediately call the 2FA start endpoint (described below) with the userId and sessionId. This triggers sending the verification code to the user’s email or mobile.
  5. Display a 6-digit code input. If the response contains secretCode (test/development mode), display it on the page so the user can copy and paste it.
  6. The start response includes a codeIndex property. Display its value on the page so the user can match the index in the message with the one on the screen.
  7. When the user submits the code, call the 2FA complete endpoint with userId, sessionId, and secretCode.
  8. On success, the complete endpoint returns the updated session object with the 2FA flag cleared. Now set the user as fully authenticated and navigate to the main application page.
  9. Provide a “Resend Code” button with a 60-second cooldown to prevent spam.
  10. Provide a “Cancel” option that discards the partial session and returns the user to the login page.

2FA Type Selection

When both email and mobile 2FA are enabled, the login response may have both sessionNeedsEmail2FA: true and sessionNeedsMobile2FA: true. In this case, handle email 2FA first, then mobile 2FA — similar to the verification order for email and mobile verification.

Email 2FA Endpoints

POST /verification-services/email-2factor-verification/start

Purpose: Starts email-based 2FA by generating and sending a verification code to the user’s email.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID

Example Request

{
  "userId": "user-uuid",
  "sessionId": "session-uuid"
}

Success Response

{
  "status": "OK",
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "codeIndex": 1,
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300",
  "expireTime": 86400,
  "verificationType": "byCode",

  // in testMode only
  "secretCode": "123456"
}

⚠️ In production, secretCode is not returned — it is only sent via email.

Error Responses


POST /verification-services/email-2factor-verification/complete

Purpose: Completes email 2FA by validating the code and clearing the session 2FA flag.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The session ID
secretCode String Yes Verification code from email

Success Response

Returns the updated session with sessionNeedsEmail2FA: false:

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "sessionNeedsEmail2FA": false,
  "accessToken": "jwt-token",
  "...": "..."
}

Error Responses


Mobile 2FA Endpoints

Important: Mobile 2FA requires that the user has a verified mobile number. If the user’s mobile is not verified, the start endpoint will return a 403 error.

POST /verification-services/mobile-2factor-verification/start

Purpose: Starts mobile-based 2FA by generating and sending a verification code via SMS.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID

Example Request

{
  "userId": "user-uuid",
  "sessionId": "session-uuid"
}

Success Response

{
  "status": "OK",
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "codeIndex": 1,
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300",
  "expireTime": 300,
  "verificationType": "byCode",

  // in testMode only
  "secretCode": "654321"
}

⚠️ In production, secretCode is not returned — it is only sent via SMS.

Error Responses


POST /verification-services/mobile-2factor-verification/complete

Purpose: Completes mobile 2FA by validating the code and clearing the session 2FA flag.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The session ID
secretCode String Yes Code received via SMS

Success Response

Returns the updated session with sessionNeedsMobile2FA: false:

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "mobile": "+15551234567",
  "fullname": "John Doe",
  "roleId": "user",
  "sessionNeedsMobile2FA": false,
  "accessToken": "jwt-token",
  "...": "..."
}

Error Responses


Important 2FA Notes

** Please dont forget to arrange the code to be able to navigate to the verification pages both after registrations and login attempts if verification is needed.**

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - Profile Management

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document includes information and api descriptions about building a profile page in the frontend using the auth service profile api calls. Avatar images are stored in the auth service’s database buckets — no external bucket service is needed for avatars.

The project has 1 auth service, 1 notification service, 1 BFF service, and 3 business services, plus other helper services such as bucket and realtime. In this document you will use the auth service (including its database bucket endpoints for avatar uploads).

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the register and login pages include a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

The base URL of the application in each environment is as follows:

For the auth service, service urls are as follows:

For each other service, the service URL will be given in the service sections.

Any request that requires login must include a valid token in the Bearer authorization header.

Avatar Storage (Database Buckets)

User avatars and tenant avatars are stored directly in the auth service database using database buckets (dbBuckets). This means avatar files are uploaded to and downloaded from the auth service itself — no external bucket service is needed.

The auth service provides these avatar buckets:

User Avatar Bucket

Upload: POST {authBaseUrl}/bucket/userAvatars/upload Download by ID: GET {authBaseUrl}/bucket/userAvatars/download/{fileId} Download by Key: GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}

Upload example (multipart/form-data):

const formData = new FormData();
formData.append('file', croppedImageBlob, 'avatar.png');

const response = await fetch(`${authBaseUrl}/bucket/userAvatars/upload`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
  body: formData,
});

const result = await response.json();
// result.file.id — the file ID (use for download URL)
// result.file.accessKey — 12-char key for public sharing
// result.file.fileName, result.file.mimeType, result.file.fileSize

After uploading, update the user’s avatar field with the download URL:

const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/${result.file.id}`;
// OR use the access key for a shorter, shareable URL:
const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`;

await updateProfile({ avatar: avatarUrl });

Displaying avatars: Since read access is public, avatar URLs can be used directly in <img> tags without any authentication token:

<img src={user.avatar} alt="Avatar" />

Listing and Deleting Avatars

The auth service also provides metadata APIs for each bucket (auto-generated):

API Method Path Description
getUserAvatarsFile GET /v1/userAvatarsFiles/:id Get file metadata (no binary)
listUserAvatarsFiles GET /v1/userAvatarsFiles List files with filtering
deleteUserAvatarsFile DELETE /v1/userAvatarsFiles/:id Delete file and its data

Profile Page

Design a profile page to manage (view and edit) user information. The profile page should include an avatar upload component that uploads to the database bucket.

On the profile page, you will need 4 business APIs: getUser , updateProfile, updateUserPassword and archiveProfile. Do not rely on the /currentuser response for profile data, because it contains session information. The most recent user data is in the user database and should be accessed via the getUser business API.

The updateProfile, updateUserPassword and archiveProfile api can only be called by the users themselves. They are designed specific to the profile page.

Avatar upload workflow:

  1. User selects an image → crop with react-easy-crop (install it, do not implement your own)
  2. Convert cropped area to a Blob
  3. Upload to POST {authBaseUrl}/bucket/userAvatars/upload with the access token
  4. Get back the file metadata (id, accessKey)
  5. Construct the download URL: {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}
  6. Call updateProfile({ avatar: downloadUrl }) to save it

Note that the user cannot change/update their email or roleId.

For password update you should make a separate block in the UI, so that user can enter old password, new password and confirm new password before calling the updateUserPassword.

Here are the 3 auth APIs—getUser , updateProfile and updateUserPassword— as follows: You can access these APIs through the auth service base URL, {appUrl}/auth-api.

Get User API

This api is used by admin roles or the users themselves to get the user profile information.

Rest Route

The getUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The getUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/users/:userId

  axios({
    method: 'GET',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Profile API

This route is used by users to update their profiles.

Rest Route

The updateProfile API REST controller can be triggered via the following route:

/v1/profile/:userId

Rest Request Parameters

The updateProfile api has got 14 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
activityLevel Enum false request.body?.[“activityLevel”]
availableEquipment String false request.body?.[“availableEquipment”]
country String false request.body?.[“country”]
dateOfBirth Date false request.body?.[“dateOfBirth”]
dietaryRestrictions String false request.body?.[“dietaryRestrictions”]
fitnessGoal Enum false request.body?.[“fitnessGoal”]
height Float false request.body?.[“height”]
sex Enum false request.body?.[“sex”]
trainingExperience Enum false request.body?.[“trainingExperience”]
weeklyTrainingDays Integer false request.body?.[“weeklyTrainingDays”]
weight Float false request.body?.[“weight”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
activityLevel : User’s general daily activity level, used as the TDEE activity multiplier.
availableEquipment : List of equipment available to the user for training program generation.
country : User’s country of residence, used for regional food suggestions and cuisine preferences.
dateOfBirth : User’s date of birth, used for age-based calorie and program calculations.
dietaryRestrictions : List of user dietary restrictions or allergies for meal plan customization.
fitnessGoal : User’s primary fitness goal driving program and nutrition recommendations.
height : User’s height in centimeters, used for BMR and TDEE calculations.
sex : User’s biological sex, used for BMR calculations and program customization.
trainingExperience : User’s training experience level, influencing program complexity and progression rates.
weeklyTrainingDays : Number of days per week the user is available to train, used for program split selection.
weight : User’s current body weight in kilograms, used for calorie and macro calculations.

REST Request To access the api you can use the REST controller with the path PATCH /v1/profile/:userId

  axios({
    method: 'PATCH',
    url: `/v1/profile/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            activityLevel:"Enum",  
            availableEquipment:"String",  
            country:"String",  
            dateOfBirth:"Date",  
            dietaryRestrictions:"String",  
            fitnessGoal:"Enum",  
            height:"Float",  
            sex:"Enum",  
            trainingExperience:"Enum",  
            weeklyTrainingDays:"Integer",  
            weight:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpassword API

This route is used to update the password of users in the profile page by users themselves

Rest Route

The updateUserPassword API REST controller can be triggered via the following route:

/v1/userpassword/:userId

Rest Request Parameters

The updateUserPassword api has got 3 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
oldPassword String true request.body?.[“oldPassword”]
newPassword String true request.body?.[“newPassword”]
userId : This id paremeter is used to select the required data object that will be updated
oldPassword : The old password of the user that will be overridden bu the new one. Send for double check.
newPassword : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpassword/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpassword/${userId}`,
    data: {
            oldPassword:"String",  
            newPassword:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Archiving A Profile

A user may want to archive their profile. So the profile page should include an archive section for the users to archive their accounts. When an account is archived, it is marked as archived and an aarchiveDate is atteched to the profile. All user data is kept in the database for 1 month after user archived. If user tries to login or register with the same email, the account will be activated again. But if no login or register occures in 1 month after archiving, the profile and its related data will be deleted permanenetly. So in the profile page,

  1. The arcihve options should be accepted after user writes a text like (“ARCHİVE MY ACCOUNT”) to a confirmation dialog, so that frontend UX can ensure this is not an unconscious request.
  2. The user should be warned about the process, that his account will be available for a restore for 1 month.

The archive api, can only be called by the users themselves and its used as follows.

Archive Profile API

This api is used by users to archive their profiles.

Rest Route

The archiveProfile API REST controller can be triggered via the following route:

/v1/archiveprofile/:userId

Rest Request Parameters

The archiveProfile api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/archiveprofile/:userId

  axios({
    method: 'DELETE',
    url: `/v1/archiveprofile/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After you complete this step, please ensure you have not made the following common mistakes:

  1. Avatar uploads go to the auth service’s database bucket endpoints (/bucket/userAvatars/upload), not to an external bucket service. Use the same accessToken (Bearer header) for both auth APIs and avatar bucket uploads — no bucket-specific tokens are needed.
  2. Note that any api call to the application backend is based on a service base url, in this prompt all auth apis (including avatar bucket endpoints) should be called by the auth service base url.
  3. On the profile page, fetch the latest user data from the service using getUser. The /currentuser API is session-stored data; the latest data is in the database.
  4. When you upload the avatar image on the profile page, use the returned download URL as the user’s avatar property and update the user record when the Save button is clicked.

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - User Management

This document is the 2nd part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for administrative user management.

Service Access

User management is handled through auth service again.

Auth service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the auth service, the base URLs are:

Please note that any feature in this document is open to admins only. When the user logins, the response includes a roleId field.

This roleId should one of these following admin roles. superAdmin, admin,

Scope

Auth service provides following feature for user management in aifitapp application.

These features are already handled in the previous part.

  1. User Registration
  2. User Authentication
  3. Password Reset
  4. Email (and/or) Mobile Verification
  5. Profile Management

These features will be handled in this part.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

User Management

User management will be one of the main parts of the administrative manageemnts, so there will be a minimal but fancy users page in the admin dashboard.

User Roles

The roles object is a hardcoded object in the generated code, and it contains the following roles:

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'"
}

Each user may have only one role, and it is given in /login , /currentuser or /users/:userId response as follows

{
  // ...
  "roleId":"superAdmin",
  // ...
}

Listing Users

You can list users using the listUsers api.

List Users API

The list of users is filtered by the tenantId.

Rest Route

The listUsers API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

Filter Parameters

The listUsers api supports 8 optional filter parameters for filtering list results:

email (String): A string value to represent the user’s email.

fullname (String): A string value to represent the fullname of the user

roleId (String): A string value to represent the roleId of the user.

activityLevel (Enum): User’s general daily activity level, used as the TDEE activity multiplier.

country (String): User’s country of residence, used for regional food suggestions and cuisine preferences.

fitnessGoal (Enum): User’s primary fitness goal driving program and nutrition recommendations.

sex (Enum): User’s biological sex, used for BMR calculations and program customization.

trainingExperience (Enum): User’s training experience level, influencing program complexity and progression rates.

REST Request To access the api you can use the REST controller with the path GET /v1/users

  axios({
    method: 'GET',
    url: '/v1/users',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // email: '<value>' // Filter by email
        // fullname: '<value>' // Filter by fullname
        // roleId: '<value>' // Filter by roleId
        // activityLevel: '<value>' // Filter by activityLevel
        // country: '<value>' // Filter by country
        // fitnessGoal: '<value>' // Filter by fitnessGoal
        // sex: '<value>' // Filter by sex
        // trainingExperience: '<value>' // Filter by trainingExperience
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"activityLevel": "Enum",
			"activityLevel_idx": "Integer",
			"availableEquipment": "String",
			"country": "String",
			"dateOfBirth": "Date",
			"dietaryRestrictions": "String",
			"fitnessGoal": "Enum",
			"fitnessGoal_idx": "Integer",
			"height": "Float",
			"sex": "Enum",
			"sex_idx": "Integer",
			"trainingExperience": "Enum",
			"trainingExperience_idx": "Integer",
			"weeklyTrainingDays": "Integer",
			"weight": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Searching Users

You may search users with their full names, emails. The search is done in elasticsearch index of the user table so a fast response is provided by the backend. You can send search request on each character update in the search box but start searching after 3 chars. The keyword parameter that is used in the business logic of the api, is read from the keyword query parameter.

eg: GET /v1/searchusers?keyword=Joe

When the user deletes the search keyword, use the listUsers api to get the full list again.

Search Users API

The list of users is filtered by the tenantId.

Rest Route

The searchUsers API REST controller can be triggered via the following route:

/v1/searchusers

Rest Request Parameters

The searchUsers api has got 1 regular request parameter

Parameter Type Required Population
keyword String true request.query?.[“keyword”]
keyword :

Filter Parameters

The searchUsers api supports 6 optional filter parameters for filtering list results:

roleId (String): A string value to represent the roleId of the user.

activityLevel (Enum): User’s general daily activity level, used as the TDEE activity multiplier.

country (String): User’s country of residence, used for regional food suggestions and cuisine preferences.

fitnessGoal (Enum): User’s primary fitness goal driving program and nutrition recommendations.

sex (Enum): User’s biological sex, used for BMR calculations and program customization.

trainingExperience (Enum): User’s training experience level, influencing program complexity and progression rates.

REST Request To access the api you can use the REST controller with the path GET /v1/searchusers

  axios({
    method: 'GET',
    url: '/v1/searchusers',
    data: {
    
    },
    params: {
             keyword:'"String"',  
    
        // Filter parameters (see Filter Parameters section above)
        // roleId: '<value>' // Filter by roleId
        // activityLevel: '<value>' // Filter by activityLevel
        // country: '<value>' // Filter by country
        // fitnessGoal: '<value>' // Filter by fitnessGoal
        // sex: '<value>' // Filter by sex
        // trainingExperience: '<value>' // Filter by trainingExperience
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"activityLevel": "Enum",
			"activityLevel_idx": "Integer",
			"availableEquipment": "String",
			"country": "String",
			"dateOfBirth": "Date",
			"dietaryRestrictions": "String",
			"fitnessGoal": "Enum",
			"fitnessGoal_idx": "Integer",
			"height": "Float",
			"sex": "Enum",
			"sex_idx": "Integer",
			"trainingExperience": "Enum",
			"trainingExperience_idx": "Integer",
			"weeklyTrainingDays": "Integer",
			"weight": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Pagination

When you list the users please use pagination. To be able to use pagination you should provide a pageNumber paramater in the query. The default row count for one page is 25, add an option for user to change it to 50 or 100. You can provide this value to the api through the pageRowCount parameter;

GET /users?pageNumber=1&pageRowCount=50

Creating Users

The user management console in the admin dashboard should provide UX components for user creating by admins. When creating users, it should also be possible to upload user avatar. Note that when creating, updating users, admins can not set emailVerified as true, since it is a logical mechanism and should be verified only through verification processes.

Create User API

This api is used by admin roles to create a new user manually from admin panels

Rest Route

The createUser API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

The createUser api has got 15 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
email String true request.body?.[“email”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
activityLevel Enum false request.body?.[“activityLevel”]
availableEquipment String false request.body?.[“availableEquipment”]
country String false request.body?.[“country”]
dateOfBirth Date false request.body?.[“dateOfBirth”]
dietaryRestrictions String false request.body?.[“dietaryRestrictions”]
fitnessGoal Enum false request.body?.[“fitnessGoal”]
height Float false request.body?.[“height”]
sex Enum true request.body?.[“sex”]
trainingExperience Enum false request.body?.[“trainingExperience”]
weeklyTrainingDays Integer false request.body?.[“weeklyTrainingDays”]
weight Float false request.body?.[“weight”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
email : A string value to represent the user’s email.
password : A string value to represent the user’s password. It will be stored as hashed.
fullname : A string value to represent the fullname of the user
activityLevel : User’s general daily activity level, used as the TDEE activity multiplier.
availableEquipment : List of equipment available to the user for training program generation.
country : User’s country of residence, used for regional food suggestions and cuisine preferences.
dateOfBirth : User’s date of birth, used for age-based calorie and program calculations.
dietaryRestrictions : List of user dietary restrictions or allergies for meal plan customization.
fitnessGoal : User’s primary fitness goal driving program and nutrition recommendations.
height : User’s height in centimeters, used for BMR and TDEE calculations.
sex : User’s biological sex, used for BMR calculations and program customization.
trainingExperience : User’s training experience level, influencing program complexity and progression rates.
weeklyTrainingDays : Number of days per week the user is available to train, used for program split selection.
weight : User’s current body weight in kilograms, used for calorie and macro calculations.

REST Request To access the api you can use the REST controller with the path POST /v1/users

  axios({
    method: 'POST',
    url: '/v1/users',
    data: {
            avatar:"String",  
            email:"String",  
            password:"String",  
            fullname:"String",  
            activityLevel:"Enum",  
            availableEquipment:"String",  
            country:"String",  
            dateOfBirth:"Date",  
            dietaryRestrictions:"String",  
            fitnessGoal:"Enum",  
            height:"Float",  
            sex:"Enum",  
            trainingExperience:"Enum",  
            weeklyTrainingDays:"Integer",  
            weight:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Avatar Upload

Avatars are stored in the auth service’s database bucket — no external bucket service needed. Upload the avatar image to the auth service’s userAvatars bucket endpoint:

POST {authBaseUrl}/bucket/userAvatars/upload

Use the regular access token (Bearer header) for authentication — the same token used for all other API calls. The upload body is multipart/form-data with a file field.

After upload, the response returns file metadata including id and accessKey. Construct a public download URL and save it in the user’s avatar field:

const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`;
await updateUser(userId, { avatar: avatarUrl });

Since the userAvatars bucket has public read access, avatar URLs work directly in <img> tags without auth.

Before the avatar upload, use the react-easy-crop lib for zoom, pan and crop. This component is also used in the profile page — reuse the existing code.

Updating Users

User update is possible by updateUserapi. However since this update api is also called by teh user themselves it is lmited with name and avatar change (or any other user related property). For roleId and password updates seperate apis are used. So arrange the user update UI as to update the user info, as to set roleId and as to update password.

Update User API

This route is used by admins to update user profiles.

Rest Route

The updateUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The updateUser api has got 14 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
activityLevel Enum false request.body?.[“activityLevel”]
availableEquipment String false request.body?.[“availableEquipment”]
country String false request.body?.[“country”]
dateOfBirth Date false request.body?.[“dateOfBirth”]
dietaryRestrictions String false request.body?.[“dietaryRestrictions”]
fitnessGoal Enum false request.body?.[“fitnessGoal”]
height Float false request.body?.[“height”]
sex Enum false request.body?.[“sex”]
trainingExperience Enum false request.body?.[“trainingExperience”]
weeklyTrainingDays Integer false request.body?.[“weeklyTrainingDays”]
weight Float false request.body?.[“weight”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
activityLevel : User’s general daily activity level, used as the TDEE activity multiplier.
availableEquipment : List of equipment available to the user for training program generation.
country : User’s country of residence, used for regional food suggestions and cuisine preferences.
dateOfBirth : User’s date of birth, used for age-based calorie and program calculations.
dietaryRestrictions : List of user dietary restrictions or allergies for meal plan customization.
fitnessGoal : User’s primary fitness goal driving program and nutrition recommendations.
height : User’s height in centimeters, used for BMR and TDEE calculations.
sex : User’s biological sex, used for BMR calculations and program customization.
trainingExperience : User’s training experience level, influencing program complexity and progression rates.
weeklyTrainingDays : Number of days per week the user is available to train, used for program split selection.
weight : User’s current body weight in kilograms, used for calorie and macro calculations.

REST Request To access the api you can use the REST controller with the path PATCH /v1/users/:userId

  axios({
    method: 'PATCH',
    url: `/v1/users/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            activityLevel:"Enum",  
            availableEquipment:"String",  
            country:"String",  
            dateOfBirth:"Date",  
            dietaryRestrictions:"String",  
            fitnessGoal:"Enum",  
            height:"Float",  
            sex:"Enum",  
            trainingExperience:"Enum",  
            weeklyTrainingDays:"Integer",  
            weight:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

For role updates there are some rules.

  1. Superadmin role can not be unassigned even by superadmin.
  2. Admin roles can be assgined or unassgined only by superadmin.
  3. All other roles can be assigned and unassgined by admins and superadmin.

For password updates there are some rules.

  1. Superadmin and admin passwords can be updated only by superadmin.
  2. Admins can update only non-admin passwords.

Update Userrole API

This route is used by admin roles to update the user role.The default role is user when a user is registered. A user’s role can be updated by superAdmin or admin

Rest Route

The updateUserRole API REST controller can be triggered via the following route:

/v1/userrole/:userId

Rest Request Parameters

The updateUserRole api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
roleId String true request.body?.[“roleId”]
userId : This id paremeter is used to select the required data object that will be updated
roleId : The new roleId of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userrole/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userrole/${userId}`,
    data: {
            roleId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpasswordbyadmin API

This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords

Rest Route

The updateUserPasswordByAdmin API REST controller can be triggered via the following route:

/v1/userpasswordbyadmin/:userId

Rest Request Parameters

The updateUserPasswordByAdmin api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
password String true request.body?.[“password”]
userId : This id paremeter is used to select the required data object that will be updated
password : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpasswordbyadmin/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpasswordbyadmin/${userId}`,
    data: {
            password:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Deleting Users

Deleting users is possible in certain conditions.

  1. SuperAdmin can not be deleted.
  2. Admins can be deleted by only superadmin.
  3. Users can be deleted by admins or superadmin.

Delete User API

This api is used by admins to delete user profiles.

Rest Route

The deleteUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The deleteUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/users/:userId

  axios({
    method: 'DELETE',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"activityLevel": "Enum",
		"activityLevel_idx": "Integer",
		"availableEquipment": "String",
		"country": "String",
		"dateOfBirth": "Date",
		"dietaryRestrictions": "String",
		"fitnessGoal": "Enum",
		"fitnessGoal_idx": "Integer",
		"height": "Float",
		"sex": "Enum",
		"sex_idx": "Integer",
		"trainingExperience": "Enum",
		"trainingExperience_idx": "Integer",
		"weeklyTrainingDays": "Integer",
		"weight": "Float",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

When you list user group members, a user object will also be inserted in each userGroupMember object, with fullname, avatar, email.

Avatar Storage (Database Buckets)

(This information is also covered in the Profile prompt.)

Avatars are stored in the auth service’s database buckets — uploaded to and downloaded from the auth service directly using the regular access token.

User Avatar Bucket:

When uploading an avatar (for user creation or update), send the image to the bucket, get back the accessKey, construct the download URL, and store it in the user’s avatar field via the update API.

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - MCP BFF Integration

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides comprehensive instructions for integrating the MCP BFF (Model Context Protocol - Backend for Frontend) service into the frontend application. The MCP BFF is the central gateway between the frontend AI chat and all backend services.


MCP BFF Architecture Overview

The Aifitapp application uses an MCP BFF service that aggregates multiple backend MCP servers into a single frontend-facing API. Instead of the frontend connecting to each service’s MCP endpoint directly, it communicates exclusively through the MCP BFF.

┌────────────┐     ┌───────────┐     ┌─────────────────┐
│  Frontend   │────▶│  MCP BFF  │────▶│  Auth Service    │
│  (Chat UI)  │     │  :3005    │────▶│  Business Svc 1  │
│             │◀────│           │────▶│  Business Svc N  │
└────────────┘ SSE └───────────┘     └─────────────────┘

Key Responsibilities

MCP BFF Service URLs

For the MCP BFF service, the base URLs are:

All endpoints below are relative to the MCP BFF base URL.


Authentication

All MCP BFF endpoints require authentication. The user’s access token (obtained from the Auth service login) must be included in every request:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${accessToken}`,
};

Chat API (AI Interaction)

The chat API is the primary interface for AI-powered conversations. It supports both regular HTTP responses and SSE streaming for real-time output.

POST /api/chat — Regular Chat

Send a message and receive the complete AI response.

const response = await fetch(`${mcpBffUrl}/api/chat`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Show me all orders from last week",
    conversationId: "optional-conversation-id",  // for conversation context
    context: {}  // additional context
  }),
});

POST /api/chat/stream — SSE Streaming Chat (Recommended)

Stream the AI response in real-time using Server-Sent Events (SSE). This is the recommended approach for chat UIs as it provides immediate feedback while the AI is thinking, calling tools, and generating text.

Request:

const response = await fetch(`${mcpBffUrl}/api/chat/stream`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Create a new product called Widget",
    conversationId: conversationId,       // optional, auto-generated if omitted
    disabledServices: [],                 // optional, service names to exclude
  }),
});

Response: The server responds with Content-Type: text/event-stream. Each SSE frame follows the standard format:

event: <eventType>\n
data: <JSON>\n
\n

SSE Event Types

The streaming endpoint emits the following event types in order:

Event When Data Shape
start First event, once per stream { conversationId, provider, aliasMapSummary }
text AI text token streamed (many per response) { content }
tool_start AI decided to call a tool { tool }
tool_executing Tool invocation started with resolved args { tool, args }
tool_result Tool execution completed { tool, result, success, error? }check for __frontendAction
error Unrecoverable error { message }
done Last event, once per stream { conversationId, toolCalls, processingTime, aliasMapSummary }

SSE Event Data Reference

start — Always the first event. Use conversationId for subsequent requests in the same conversation.

{
  "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453",
  "provider": "anthropic",
  "aliasMapSummary": { "enabled": true, "count": 0, "samples": [] }
}

text — Streamed token-by-token as the AI generates its response. Concatenate content fields to build the full markdown message.

{ "content": "Here" }
{ "content": "'s your" }
{ "content": " current session info" }

tool_start — The AI decided to call a tool. Use this to show a loading/spinner UI for the tool.

{ "tool": "currentuser" }

tool_executing — Tool is now executing with these arguments. Use this to display what the tool is doing.

{ "tool": "currentuser", "args": { "organizationCodename": "babil" } }

tool_result — Tool finished. Check success to determine if it succeeded. The result field contains the MCP tool response envelope.

{
  "tool": "currentuser",
  "result": {
    "success": true,
    "service": "auth",
    "tool": "currentuser",
    "result": {
      "content": [{ "type": "text", "text": "{...JSON...}" }]
    }
  },
  "success": true
}

On failure, success is false and an error string is present:

{
  "tool": "listProducts",
  "error": "Connection refused",
  "success": false
}

done — Always the last event. Contains a summary of all tool calls made and total processing time in milliseconds.

{
  "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453",
  "toolCalls": [
    { "tool": "currentuser", "result": { "success": true, "..." : "..." } }
  ],
  "processingTime": 10026,
  "aliasMapSummary": {
    "enabled": true,
    "count": 6,
    "samples": [{ "alias": "user_admin_admin_com" }, { "alias": "tenant_admin_admin_com" }]
  }
}

error — Sent when an unrecoverable error occurs (e.g., AI service unavailable). The stream ends after this event.

{ "message": "AI service not configured. Please configure OPENAI_API_KEY or ANTHROPIC_API_KEY in environment variables" }

SSE Event Lifecycle

A typical conversation stream follows this lifecycle:

start
├── text (repeated)              ← AI's initial text tokens
├── tool_start                   ← AI decides to call a tool
├── tool_executing               ← tool running with resolved args
├── tool_result                  ← tool finished
├── text (repeated)              ← AI continues writing after tool result
├── tool_start → tool_executing → tool_result   ← may repeat
├── text (repeated)              ← AI's final text tokens
done

Multiple tool calls can happen in a single stream. The AI interleaves text and tool calls — text before tools (explanation), tools in the middle (data retrieval), and text after tools (formatted response using the tool results).

Inline Segment Rendering (Critical UX Pattern)

Tool cards MUST be rendered inline inside the assistant message bubble, at the exact position where they occur in the stream — not grouped at the top, not grouped at the bottom, and not outside the bubble.

The assistant message is an ordered list of segments: text segments and tool segments, interleaved in the order they arrive. Each segment appears inside the same message bubble, in sequence:

┌─────────────────────────────────────────────────┐
│  [Rendered Markdown — text before tool call]     │
│                                                  │
│  ┌─ Tool Card ─────────────────────────────────┐ │
│  │ 🔧 currentuser                    ✓ success │ │
│  │ args: { organizationCodename: "babil" }     │ │
│  └─────────────────────────────────────────────┘ │
│                                                  │
│  [Rendered Markdown — text after tool call]       │
│                                                  │
│  ┌─ Tool Card ─────────────────────────────────┐ │
│  │ 🔧 listProducts                  ✓ success  │ │
│  └─────────────────────────────────────────────┘ │
│                                                  │
│  [Rendered Markdown — final text]                │
└─────────────────────────────────────────────────┘

To achieve this, maintain an ordered segments array. Each segment is either { type: 'text', content: string } or { type: 'tool', ... }. When SSE events arrive:

  1. text — Append to the last segment if it is a text segment; otherwise push a new text segment.
  2. tool_start — Push a new tool segment (status: running). This “cuts” the current text segment — any further text events after the tool completes will start a new text segment.
  3. tool_executing — Update the current tool segment with args.
  4. tool_result — Update the current tool segment with result, success, error. Check for __frontendAction.
  5. After tool_result, the next text event creates a new text segment (the AI is now responding after reviewing the tool result).

Render the message bubble by mapping over the segments array in order, rendering each text segment as markdown and each tool segment as a collapsible tool card.

Parsing SSE Events (Frontend Implementation)

Use the fetch API with a streaming reader. SSE frames can arrive split across chunks, so buffer partial lines:

async function streamChat(mcpBffUrl, headers, message, conversationId, onEvent) {
  const response = await fetch(`${mcpBffUrl}/api/chat/stream`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ message, conversationId }),
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const parts = buffer.split('\n\n');
    buffer = parts.pop(); // keep incomplete frame in buffer

    for (const part of parts) {
      let eventType = 'message';
      let dataStr = '';

      for (const line of part.split('\n')) {
        if (line.startsWith('event: ')) {
          eventType = line.slice(7).trim();
        } else if (line.startsWith('data: ')) {
          dataStr += line.slice(6);
        }
      }

      if (dataStr) {
        try {
          const data = JSON.parse(dataStr);
          onEvent(eventType, data);
        } catch (e) {
          console.warn('Failed to parse SSE data:', dataStr);
        }
      }
    }
  }
}

Building the Segments Array (React Example)

// segments: Array<{ type: 'text', content: string } | { type: 'tool', tool, args?, result?, success?, error?, status }>
let segments = [];

streamChat(mcpBffUrl, headers, userMessage, conversationId, (event, data) => {
  switch (event) {
    case 'start':
      conversationId = data.conversationId;
      segments = [];
      break;

    case 'text': {
      const last = segments[segments.length - 1];
      if (last && last.type === 'text') {
        last.content += data.content;        // append to current text segment
      } else {
        segments.push({ type: 'text', content: data.content }); // new text segment
      }
      rerenderBubble(segments);
      break;
    }

    case 'tool_start':
      // push a new tool segment — this "cuts" the text flow
      segments.push({ type: 'tool', tool: data.tool, status: 'running' });
      rerenderBubble(segments);
      break;

    case 'tool_executing': {
      const toolSeg = findLastToolSegment(segments, data.tool);
      if (toolSeg) toolSeg.args = data.args;
      rerenderBubble(segments);
      break;
    }

    case 'tool_result': {
      const toolSeg = findLastToolSegment(segments, data.tool);
      if (toolSeg) {
        toolSeg.status = data.success ? 'complete' : 'error';
        toolSeg.result = data.result;
        toolSeg.error = data.error;
        toolSeg.success = data.success;
        // Check for frontend action (QR code, data view, payment, secret)
        toolSeg.frontendAction = extractFrontendAction(data.result);
      }
      rerenderBubble(segments);
      break;
    }

    case 'error':
      segments.push({ type: 'text', content: `**Error:** ${data.message}` });
      rerenderBubble(segments);
      break;

    case 'done':
      // Store final metadata (processingTime, aliasMapSummary) for the message
      finalizeMessage(segments, data);
      break;
  }
});

function findLastToolSegment(segments, toolName) {
  for (let i = segments.length - 1; i >= 0; i--) {
    if (segments[i].type === 'tool' && segments[i].tool === toolName) return segments[i];
  }
  return null;
}

Rendering the Message Bubble

Render each segment in order inside a single assistant message bubble:

function AssistantMessageBubble({ segments }) {
  return (
    <div className="assistant-bubble">
      {segments.map((segment, i) => {
        if (segment.type === 'text') {
          return <MarkdownRenderer key={i} content={segment.content} />;
        }
        if (segment.type === 'tool') {
          if (segment.frontendAction) {
            return <ActionCard key={i} action={segment.frontendAction} />;
          }
          return <ToolCard key={i} segment={segment} />;
        }
        return null;
      })}
    </div>
  );
}

function ToolCard({ segment }) {
  const isRunning = segment.status === 'running';
  const isError = segment.status === 'error';

  return (
    <div className={`tool-card ${segment.status}`}>
      <div className="tool-header">
        {isRunning && <Spinner size="sm" />}
        <span className="tool-name">{segment.tool}</span>
        {!isRunning && (isError ? <ErrorIcon /> : <CheckIcon />)}
      </div>
      {segment.args && (
        <CollapsibleSection label="Arguments">
          <pre>{JSON.stringify(segment.args, null, 2)}</pre>
        </CollapsibleSection>
      )}
      {segment.result && (
        <CollapsibleSection label="Result" defaultCollapsed>
          <pre>{JSON.stringify(segment.result, null, 2)}</pre>
        </CollapsibleSection>
      )}
      {segment.error && <div className="tool-error">{segment.error}</div>}
    </div>
  );
}

The tool card should be compact by default (just tool name + status icon) with collapsible sections for args and result, so it doesn’t dominate the reading flow. While a tool is running (status: 'running'), show a spinner. When complete, show a check or error icon.

Handling __frontendAction in Tool Results

When the AI calls certain tools (e.g., QR code, data view, payment, secret reveal), the tool result contains a __frontendAction object. This signals the frontend to render a special UI component inline in the bubble at the tool segment’s position instead of the default collapsible ToolCard. This is already handled in the segments code above — when segment.frontendAction is present, render an ActionCard instead of a ToolCard.

The extractFrontendAction helper unwraps the action from various MCP response formats:

function extractFrontendAction(result) {
  if (!result) return null;
  if (result.__frontendAction) return result.__frontendAction;
  
  // Unwrap MCP wrapper format: result → result.result → content[].text → JSON
  let data = result;
  if (result?.result?.content) data = result.result;
  
  if (data?.content && Array.isArray(data.content)) {
    const textContent = data.content.find(c => c.type === 'text');
    if (textContent?.text) {
      try {
        const parsed = JSON.parse(textContent.text);
        if (parsed?.__frontendAction) return parsed.__frontendAction;
      } catch { /* not JSON */ }
    }
  }
  return null;
}

Frontend Action Types

Action Type Component Description
qrcode QrCodeActionCard Renders any string value as a QR code card
dataView DataViewActionCard Fetches a Business API route and renders a grid or gallery
payment PaymentActionCard “Pay Now” button that opens Stripe checkout modal

QR Code Action (type: "qrcode")

Triggered by the showQrCode MCP tool. Renders a QR code card from any string value.

{
  "__frontendAction": {
    "type": "qrcode",
    "value": "https://example.com/invite/ABC123",
    "title": "Invite Link",
    "subtitle": "Scan to open"
  }
}

Data View Action (type: "dataView")

Triggered by showBusinessApiListInFrontEnd or showBusinessApiGalleryInFrontEnd. Frontend calls the provided Business API route using the user’s bearer token, then renders:

{
  "__frontendAction": {
    "type": "dataView",
    "viewType": "grid",
    "title": "Recent Orders",
    "serviceName": "commerce",
    "apiName": "listOrders",
    "routePath": "/v1/listorders",
    "httpMethod": "GET",
    "queryParams": { "pageNo": 1, "pageRowCount": 10 },
    "columns": [
      { "field": "id", "label": "Order ID" },
      { "field": "orderAmount", "label": "Amount", "format": "currency" }
    ]
  }
}

Payment Action (type: "payment")

Triggered by the initiatePayment MCP tool. Renders a payment card with amount and a “Pay Now” button.

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "order",
    "serviceName": "commerce",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order #abc123"
  }
}

Conversation Management

// List user's conversations
GET /api/chat/conversations

// Get conversation history
GET /api/chat/conversations/:conversationId

// Delete a conversation
DELETE /api/chat/conversations/:conversationId

MCP Tool Discovery & Direct Invocation

The MCP BFF exposes endpoints for discovering and directly calling MCP tools (useful for debugging or building custom UIs).

GET /api/tools — List All Tools

const response = await fetch(`${mcpBffUrl}/api/tools`, { headers });
const { tools, count } = await response.json();
// tools: [{ name, description, inputSchema, service }, ...]

GET /api/tools/service/:serviceName — List Service Tools

const response = await fetch(`${mcpBffUrl}/api/tools/service/commerce`, { headers });
const { tools } = await response.json();

POST /api/tools/call — Call a Tool Directly

const response = await fetch(`${mcpBffUrl}/api/tools/call`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    toolName: "listProducts",
    args: { page: 1, limit: 10 },
  }),
});
const result = await response.json();

GET /api/tools/status — Connection Status

const status = await fetch(`${mcpBffUrl}/api/tools/status`, { headers });
// Returns health of each MCP service connection

POST /api/tools/refresh — Reconnect Services

await fetch(`${mcpBffUrl}/api/tools/refresh`, { method: 'POST', headers });
// Reconnects to all MCP services and refreshes the tool registry

Elasticsearch API

The MCP BFF provides direct access to Elasticsearch for searching, filtering, and aggregating data across all project indices.

All Elasticsearch endpoints are under /api/elastic.

GET /api/elastic/allIndices — List Project Indices

Returns all Elasticsearch indices belonging to this project (prefixed with appaili_).

const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers });
// ["appaili_products", "appaili_orders", ...]

POST /api/elastic/:indexName/rawsearch — Raw Elasticsearch Query

Execute a raw Elasticsearch query on a specific index.

const response = await fetch(`${mcpBffUrl}/api/elastic/products/rawsearch`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    query: {
      bool: {
        must: [
          { match: { status: "active" } },
          { range: { price: { gte: 10, lte: 100 } } }
        ]
      }
    },
    size: 20,
    from: 0,
    sort: [{ createdAt: "desc" }]
  }),
});
const { total, hits, aggregations, took } = await response.json();
// hits: [{ _id, _index, _score, _source: { ...document... } }, ...]

Note: The index name is automatically prefixed with appaili_ if not already prefixed.

POST /api/elastic/:indexName/search — Simplified Search

A higher-level search API with built-in support for filters, sorting, and pagination.

const response = await fetch(`${mcpBffUrl}/api/elastic/products/search`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    search: "wireless headphones",           // Full-text search
    filters: { status: "active" },           // Field filters
    sort: { field: "createdAt", order: "desc" },
    page: 1,
    limit: 25,
  }),
});

POST /api/elastic/:indexName/aggregate — Aggregations

Run aggregation queries for analytics and dashboards.

const response = await fetch(`${mcpBffUrl}/api/elastic/orders/aggregate`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    aggs: {
      status_counts: { terms: { field: "status.keyword" } },
      total_revenue: { sum: { field: "amount" } },
      monthly_orders: {
        date_histogram: { field: "createdAt", calendar_interval: "month" }
      }
    },
    query: { range: { createdAt: { gte: "now-1y" } } }
  }),
});

GET /api/elastic/:indexName/mapping — Index Mapping

Get the field mapping for an index (useful for building dynamic filter UIs).

const mapping = await fetch(`${mcpBffUrl}/api/elastic/products/mapping`, { headers });

POST /api/elastic/:indexName/ai-search — AI-Assisted Search

Uses the configured AI model to convert a natural-language query into an Elasticsearch query.

const response = await fetch(`${mcpBffUrl}/api/elastic/orders/ai-search`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    query: "orders over $100 from last month that are still pending",
  }),
});
// Returns: { total, hits, generatedQuery, ... }

Log API

The MCP BFF provides log viewing endpoints for monitoring application behavior.

GET /api/logs — Query Logs

const response = await fetch(`${mcpBffUrl}/api/logs?page=1&limit=50&logType=2&service=commerce&search=payment`, {
  headers,
});

Query Parameters:

GET /api/logs/stream — Real-time Console Stream (SSE)

Streams real-time console output from all services via Server-Sent Events.

const eventSource = new EventSource(`${mcpBffUrl}/api/logs/stream?services=commerce,auth`, {
  headers: { 'Authorization': `Bearer ${accessToken}` },
});

eventSource.addEventListener('log', (event) => {
  const logEntry = JSON.parse(event.data);
  // { service, timestamp, level, message, ... }
});

Available Services

The MCP BFF connects to the following backend services:

Service Description
auth Authentication, user management, sessions
aiCoach AI-powered fitness coaching service that generates personalized evidence-based training programs and nutrition plans, manages chatbowt interactions with full validation chains, handles dynamic program modifications via AI tool calls, tracks weaight measurements, enforces moderation and quotas, and provides admin endpoints for moderation history and usage analytics.a
subscription Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z
agentHub AI Agent Hub

Each service exposes MCP tools that the AI can call through the BFF. Use GET /api/tools to discover all available tools at runtime, or GET /api/tools/service/:serviceName to list tools for a specific service.


MCP as Internal API Gateway

The MCP-BFF service can also be used by the frontend as an internal API gateway for tool-based interactions. This is separate from external AI tool connections — it is meant for frontend code that needs to call backend tools programmatically.

Direct Tool Calls (REST)

Use the REST tool invocation endpoints for programmatic access from frontend code:

// List all available tools
const tools = await fetch(`${mcpBffUrl}/api/tools`, { headers });

// Call a specific tool directly
const result = await fetch(`${mcpBffUrl}/api/tools/call`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    toolName: 'listProducts',
    args: { page: 1, limit: 10 },
  }),
});

AI-Orchestrated Calls (Chat API)

For AI-driven interactions, use the chat streaming API documented above (POST /api/chat/stream). The AI model decides which tools to call based on the user’s message.

Both approaches use the user’s JWT access token for authentication — the MCP-BFF forwards it to the correct backend service.


MCP Connection Info for Profile Page

The user’s profile page should include an informational section explaining how to connect external AI tools (Cursor, Claude Desktop, Lovable, Windsurf, etc.) to this application’s backend via MCP.

What to Display

The MCP-BFF exposes a unified MCP endpoint that aggregates tools from all backend services into a single connection point:

Environment URL
Preview https://appaili.prw.mindbricks.com/mcpbff-api/mcp
Staging https://appaili-stage.mindbricks.co/mcpbff-api/mcp
Production https://appaili.mindbricks.co/mcpbff-api/mcp

For legacy MCP clients that don’t support StreamableHTTP, an SSE fallback is available at the same URL with /sse appended (e.g., .../mcpbff-api/mcp/sse).

Profile Page UI Requirements

Add an “MCP Connection” or “Connect External AI Tools” card/section to the profile page with:

  1. Endpoint URL — Display the MCP endpoint URL for the current environment with a copy-to-clipboard button.

  2. Ready-to-Copy Configs — Show copy-to-clipboard config snippets for popular tools:

    Cursor (.cursor/mcp.json):

    {
      "mcpServers": {
        "appaili": {
          "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp",
          "headers": {
            "Authorization": "Bearer your_access_token_here"
          }
        }
      }
    }
    

    Claude Desktop (claude_desktop_config.json):

    {
      "mcpServers": {
        "appaili": {
          "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp",
          "headers": {
            "Authorization": "Bearer your_access_token_here"
          }
        }
      }
    }
    
  3. Auth Note — Note that users should replace your_access_token_here with a valid JWT access token from the login API.

  4. OAuth Note — Display a note that OAuth authentication is not currently supported for MCP connections.

  5. Available Tools — Optionally show a summary of available tool categories (e.g., “CRUD operations for all data objects, custom business APIs, file operations”) or link to the tools discovery endpoint (GET /api/tools).


After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - AiCoach Service

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of aiCoach

Service Access

AiCoach service management is handled through service specific base urls.

AiCoach service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the aiCoach service, the base URLs are:

Scope

AiCoach Service Description

AI-powered fitness coaching service that generates personalized evidence-based training programs and nutrition plans, manages chatbowt interactions with full validation chains, handles dynamic program modifications via AI tool calls, tracks weaight measurements, enforces moderation and quotas, and provides admin endpoints for moderation history and usage analytics.a

AiCoach service provides apis and business logic for following data objects in aifitapp application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

chatMessage Data Object: Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata.

coachConversation Data Object: Chat conversation container per user for the AI fitness coach chatbot.

mealPlan Data Object: Stores AI-generated meal plans per user including calorie targets, macro distribution, and training/rest day differentiation. Created and modified exclusively by AI tool calls.

moderationRecord Data Object: Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review.

planMeal Data Object: Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls.

programExercise Data Object: Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls.

quotaConfig Data Object: System-wide message quota configuration. Admin-managed single record that defines message limits per period.

trainingProgram Data Object: Stores AI-generated training programs per user including split type, deload schedule, cardio guidelines, and step targets. Created and modified exclusively by AI tool calls.

userQuota Data Object: Per-user message quota consumption tracking against the system-wide quota configuration.

weightLog Data Object: User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach.

banAppeals Data Object:

additionalQuota Data Object:

sys_additionalQuotaPayment Data Object: A payment storage object to store the payment life cyle of orders based on additionalQuota object. It is autocreated based on the source object's checkout config

sys_paymentCustomer Data Object: A payment storage object to store the customer values of the payment platform

sys_paymentMethod Data Object: A payment storage object to store the payment methods of the platform customers

AiCoach Service Frontend Description By The Backend Architect

AI Coach Service - Frontend UX Guide

Chatbot Interface

Training Programs & Meal Plans

Weight Tracking

Quota Display

Moderation

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

ChatMessage Data Object

Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata.

ChatMessage Data Object Properties

ChatMessage data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
content Text false Yes No Message content
conversationId ID false Yes No Reference to the parent conversation
flagged Boolean false No No True if the message was detected as off-topic or abusive
role Enum false Yes No Message sender role
toolCallData Text false No No JSON string of tool call metadata from AI processing

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

conversationId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

conversationId flagged role

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

CoachConversation Data Object

Chat conversation container per user for the AI fitness coach chatbot.

CoachConversation Data Object Properties

CoachConversation data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
status Enum false Yes No Conversation status
userId ID false Yes No Reference to the user who owns this conversation

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

status userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

MealPlan Data Object

Stores AI-generated meal plans per user including calorie targets, macro distribution, and training/rest day differentiation. Created and modified exclusively by AI tool calls.

MealPlan Data Object Properties

MealPlan data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
carbGrams Float false Yes No Daily carbohydrate target in grams
dailyCalorieTarget Integer false Yes No Daily calorie target in kcal
fatGrams Float false Yes No Daily fat target in grams
notes Text false No No Additional AI-generated nutritional guidance
proteinGrams Float false Yes No Daily protein target in grams
restDayCalories Integer false No No Calorie target on rest days
restDayCarbGrams Float false No No Carb target on rest days
status Enum false Yes No Meal plan status
trainingDayCalories Integer false No No Calorie target on training days
trainingDayCarbGrams Float false No No Carb target on training days
userId ID false Yes No Reference to the user who owns this meal plan

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

status userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

ModerationRecord Data Object

Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review.

ModerationRecord Data Object Properties

ModerationRecord data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
action Enum false Yes No Moderation action taken
offenseType String false Yes No Description of the violation
reason Text false No No Detailed reason for the moderation action
suspensionExpiresAt Date false No No When a temporary suspension ends (null for lifetime bans and reversals)
userId ID false Yes No Reference to the user who was moderated
content String false Yes No

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

action userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

PlanMeal Data Object

Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls.

PlanMeal Data Object Properties

PlanMeal data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
carbs Float false Yes No Carb grams for this meal
fat Float false Yes No Fat grams for this meal
foods Text false Yes No Food items and quantities description
mealLabel String false Yes No Meal label (e.g. breakfast, lunch, dinner, snack)
mealPlanId ID false Yes No Reference to the parent meal plan
protein Float false Yes No Protein grams for this meal
sortOrder Integer false Yes No Display sort order within the meal plan
totalCalories Integer false Yes No Total calories for this meal

Relation Properties

mealPlanId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

mealPlanId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

ProgramExercise Data Object

Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls.

ProgramExercise Data Object Properties

ProgramExercise data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
dayLabel String false Yes No Training day label (e.g. pushDay, upperA, legDay)
exerciseName String false Yes No Name of the exercise
movementType Enum false Yes No Movement type classification
muscleGroup String false Yes No Target muscle group
progressionRule Text false No No Progression instructions (e.g. double progression model)
repMax Integer false Yes No Maximum rep target
repMin Integer false Yes No Minimum rep target
rirTarget Integer false Yes No Reps In Reserve target (0-3)
sets Integer false Yes No Number of working sets
sortOrder Integer false Yes No Display sort order within the training day
trainingProgramId ID false Yes No Reference to the parent training program

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

trainingProgramId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

dayLabel muscleGroup trainingProgramId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

QuotaConfig Data Object

System-wide message quota configuration. Admin-managed single record that defines message limits per period.

QuotaConfig Data Object Properties

QuotaConfig data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
quotaLimit Integer false Yes No Maximum messages allowed per period
quotaPeriod Enum false Yes No Period over which the quota is measured

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

TrainingProgram Data Object

Stores AI-generated training programs per user including split type, deload schedule, cardio guidelines, and step targets. Created and modified exclusively by AI tool calls.

TrainingProgram Data Object Properties

TrainingProgram data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
cardioDurationMinutes Integer false No No Recommended cardio duration in minutes
cardioFrequencyPerWeek Integer false No No Recommended cardio sessions per week
cardioType String false No No Type of cardio recommended (e.g. zone2)
dailyStepTarget Integer false No No Daily step target for NEAT (7000-12000)
deloadIntervalWeeks Integer false No No Weeks between deload periods, typically 6-8
notes Text false No No Additional AI-generated notes and guidance
splitType String false Yes No Training split type (e.g. fullBody, upperLower, pushPullLegs)
status Enum false Yes No Program status
userId ID false Yes No Reference to the user who owns this training program

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

status userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

UserQuota Data Object

Per-user message quota consumption tracking against the system-wide quota configuration.

UserQuota Data Object Properties

UserQuota data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
messageCount Integer false Yes No Number of messages consumed in the current period
periodEnd Date false Yes No End of the current quota period
periodStart Date false Yes No Start of the current quota period
userId ID false Yes No Reference to the user whose quota is being tracked

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

WeightLog Data Object

User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach.

WeightLog Data Object Properties

WeightLog data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
measuredAt Date false Yes No Date and time of measurement
userId ID false Yes No Reference to the user who recorded this weight
weightKg Float false Yes No Body weight in kilograms

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

BanAppeals Data Object

BanAppeals Data Object Properties

BanAppeals data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
moderationRecordId ID false Yes No id of the mod record
userId ID false Yes No
appealReason String false Yes No
status Enum false Yes No

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

moderationRecordId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

AdditionalQuota Data Object

AdditionalQuota Data Object Properties

AdditionalQuota data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
userId String false Yes No
additionalMessage Integer false Yes No
status Enum false Yes No
currency String false Yes No
pricePaid Integer false Yes No
statusUpdatedAt Date false No No
activatedAt Date false No No
cancelledAt Date false No No
periodEnd Date false No No
periodStart Date false No No
paymentConfirmation Enum false Yes No An automatic property that is used to check the confirmed status of the payment set by webhooks.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Filter Properties

paymentConfirmation

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_additionalQuotaPayment Data Object

A payment storage object to store the payment life cyle of orders based on additionalQuota object. It is autocreated based on the source object's checkout config

Sys_additionalQuotaPayment Data Object Properties

Sys_additionalQuotaPayment data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
ownerId ID false No No An ID value to represent owner user who created the order
orderId ID false Yes No an ID value to represent the orderId which is the ID parameter of the source additionalQuota object
paymentId String false Yes No A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String false Yes No A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String false Yes No A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String false No No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

Filter Properties

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_paymentCustomer Data Object

A payment storage object to store the customer values of the payment platform

Sys_paymentCustomer Data Object Properties

Sys_paymentCustomer data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
userId ID false No No An ID value to represent the user who is created as a stripe customer
customerId String false Yes No A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String false Yes No A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

Filter Properties

userId customerId platform

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_paymentMethod Data Object

A payment storage object to store the payment methods of the platform customers

Sys_paymentMethod Data Object Properties

Sys_paymentMethod data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
paymentMethodId String false Yes No A string value to represent the id of the payment method on the payment platform.
userId ID false Yes No An ID value to represent the user who owns the payment method
customerId String false Yes No A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String false No No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String false No No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String false Yes No A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object false Yes No A Json value to store the card details of the payment method.

Filter Properties

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

ChatMessage Default APIs

Operation API Name Route Explicitly Set
Create createChatMessage /v1/chatmessages Yes
Update none - Auto
Delete none - Auto
Get getChatMessage /v1/chatmessages/:chatMessageId Yes
List listChatMessages /v1/chatmessages Yes

CoachConversation Default APIs

Operation API Name Route Explicitly Set
Create createCoachConversation /v1/coachconversations Yes
Update none - Auto
Delete none - Auto
Get getCoachConversation /v1/coachconversations/:coachConversationId Yes
List listCoachConversations /v1/coachconversations Yes

MealPlan Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete deletemealplan /v1/deletemealplan/:mealPlanId Auto
Get getMealPlan /v1/mealplans/:mealPlanId Yes
List listMealPlans /v1/mealplans Yes

ModerationRecord Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update updateModerationRecord /v1/moderationrecords/:moderationRecordId Auto
Delete deleteModerationRecord /v1/moderationrecords/:moderationRecordId Auto
Get getModerationRecord /v1/moderationrecords/:moderationRecordId Yes
List listModerationRecords /v1/moderationrecords Yes

PlanMeal Default APIs

Display Label Property: mealLabel — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getPlanMeal /v1/planmeals/:planMealId Yes
List listPlanMeals /v1/planmeals Yes

ProgramExercise Default APIs

Display Label Property: exerciseName — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getProgramExercise /v1/programexercises/:programExerciseId Yes
List listProgramExercises /v1/programexercises Yes

QuotaConfig Default APIs

Operation API Name Route Explicitly Set
Create createQuotaConfig /v1/quotaconfigs Yes
Update updateQuotaConfig /v1/quotaconfigs/:quotaConfigId Yes
Delete none - Auto
Get getQuotaConfig /v1/quotaconfigs/:quotaConfigId Yes
List listQuotaConfigs /v1/quotaconfigs Yes

TrainingProgram Default APIs

Display Label Property: splitType — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete deletetrainingprogram /v1/deletetrainingprogram/:trainingProgramId Auto
Get getTrainingProgram /v1/trainingprograms/:trainingProgramId Yes
List listTrainingPrograms /v1/trainingprograms Yes

UserQuota Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getUserQuota /v1/userquotas/:userQuotaId Yes
List listUserQuotas /v1/userquotas Yes

WeightLog Default APIs

Operation API Name Route Explicitly Set
Create createWeightLog /v1/weightlogs Yes
Update none - Auto
Delete none - Auto
Get getWeightLog /v1/weightlogs/:weightLogId Yes
List listWeightLogs /v1/weightlogs Yes

BanAppeals Default APIs

Operation API Name Route Explicitly Set
Create createBanAppeal /v1/banappeal Auto
Update updateBanAppeal /v1/banappeal/:banAppealsId Auto
Delete none - Auto
Get none - Auto
List listBanAppeals /v1/banappealses Auto

AdditionalQuota Default APIs

Operation API Name Route Explicitly Set
Create createAdditionalQuota /v1/additionalquotas Auto
Update startAdditionalQuotaPayment /v1/startadditionalquotapayment/:additionalQuotaId Auto
Delete none - Auto
Get getMyAdditionalQuota /v1/myadditionalquota Auto
List none - Auto

Sys_additionalQuotaPayment Default APIs

Operation API Name Route Explicitly Set
Create createAdditionalQuotaPayment /v1/additionalquotapayment Auto
Update updateAdditionalQuotaPayment /v1/additionalquotapayment/:sys_additionalQuotaPaymentId Auto
Delete deleteAdditionalQuotaPayment /v1/additionalquotapayment/:sys_additionalQuotaPaymentId Auto
Get getAdditionalQuotaPayment /v1/additionalquotapayment/:sys_additionalQuotaPaymentId Auto
List listAdditionalQuotaPayments /v1/additionalquotapayments Auto

Sys_paymentCustomer Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getPaymentCustomerByUserId /v1/paymentcustomers/:userId Auto
List listPaymentCustomers /v1/paymentcustomers Auto

Sys_paymentMethod Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List listPaymentCustomerMethods /v1/paymentcustomermethods/:userId Auto

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Chatmessage API

[Default create API] — This is the designated default create API for the chatMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send a message to the AI fitness coach. Enforces the full validation chain: subscription check → ban status check → quota check → content flagging → AI processing → tool call execution → quota increment. Returns both the user message and the AI response.

API Frontend Description By The Backend Architect

Chat Message Creation

Rest Route

The createChatMessage API REST controller can be triggered via the following route:

/v1/chatmessages

Rest Request Parameters

The createChatMessage api has got 2 regular request parameters

Parameter Type Required Population
conversationId ID true request.body?.[“conversationId”]
content Text true request.body?.[“content”]
conversationId : The conversation to send the message to
content : The message content

REST Request To access the api you can use the REST controller with the path POST /v1/chatmessages

  axios({
    method: 'POST',
    url: '/v1/chatmessages',
    data: {
            conversationId:"ID",  
            content:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chatMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chatMessage": {
		"id": "ID",
		"content": "Text",
		"conversationId": "ID",
		"flagged": "Boolean",
		"role": "Enum",
		"role_idx": "Integer",
		"toolCallData": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Coachconversation API

[Default create API] — This is the designated default create API for the coachConversation data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new coach conversation. Requires active subscription and no active ban.

Rest Route

The createCoachConversation API REST controller can be triggered via the following route:

/v1/coachconversations

Rest Request Parameters The createCoachConversation api has got no request parameters.

REST Request To access the api you can use the REST controller with the path POST /v1/coachconversations

  axios({
    method: 'POST',
    url: '/v1/coachconversations',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "coachConversation",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"coachConversation": {
		"id": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"activeSubscriptions": "Object"
}

Create Quotaconfig API

[Default create API] — This is the designated default create API for the quotaConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a quota configuration record. Admin only.

Rest Route

The createQuotaConfig API REST controller can be triggered via the following route:

/v1/quotaconfigs

Rest Request Parameters

The createQuotaConfig api has got 2 regular request parameters

Parameter Type Required Population
quotaLimit Integer true request.body?.[“quotaLimit”]
quotaPeriod Enum true request.body?.[“quotaPeriod”]
quotaLimit : Maximum messages allowed per period
quotaPeriod : Period over which the quota is measured

REST Request To access the api you can use the REST controller with the path POST /v1/quotaconfigs

  axios({
    method: 'POST',
    url: '/v1/quotaconfigs',
    data: {
            quotaLimit:"Integer",  
            quotaPeriod:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "quotaConfig",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"quotaConfig": {
		"id": "ID",
		"quotaLimit": "Integer",
		"quotaPeriod": "Enum",
		"quotaPeriod_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Weightlog API

[Default create API] — This is the designated default create API for the weightLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Report a weight measurement. Requires active subscription and no active ban.

Rest Route

The createWeightLog API REST controller can be triggered via the following route:

/v1/weightlogs

Rest Request Parameters

The createWeightLog api has got 2 regular request parameters

Parameter Type Required Population
measuredAt Date true request.body?.[“measuredAt”]
weightKg Float true request.body?.[“weightKg”]
measuredAt : Date and time of measurement
weightKg : Body weight in kilograms

REST Request To access the api you can use the REST controller with the path POST /v1/weightlogs

  axios({
    method: 'POST',
    url: '/v1/weightlogs',
    data: {
            measuredAt:"Date",  
            weightKg:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "weightLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"weightLog": {
		"id": "ID",
		"measuredAt": "Date",
		"userId": "ID",
		"weightKg": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Chatmessage API

[Default get API] — This is the designated default get API for the chatMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a chat message by ID with parent conversation ownership validation.

Rest Route

The getChatMessage API REST controller can be triggered via the following route:

/v1/chatmessages/:chatMessageId

Rest Request Parameters

The getChatMessage api has got 1 regular request parameter

Parameter Type Required Population
chatMessageId ID true request.params?.[“chatMessageId”]
chatMessageId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/chatmessages/:chatMessageId

  axios({
    method: 'GET',
    url: `/v1/chatmessages/${chatMessageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chatMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"chatMessage": {
		"id": "ID",
		"content": "Text",
		"conversationId": "ID",
		"flagged": "Boolean",
		"role": "Enum",
		"role_idx": "Integer",
		"toolCallData": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Coachconversation API

[Default get API] — This is the designated default get API for the coachConversation data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a conversation by ID. Users see their own, admins can see any.

Rest Route

The getCoachConversation API REST controller can be triggered via the following route:

/v1/coachconversations/:coachConversationId

Rest Request Parameters

The getCoachConversation api has got 1 regular request parameter

Parameter Type Required Population
coachConversationId ID true request.params?.[“coachConversationId”]
coachConversationId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/coachconversations/:coachConversationId

  axios({
    method: 'GET',
    url: `/v1/coachconversations/${coachConversationId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "coachConversation",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"coachConversation": {
		"id": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Mealplan API

[Default get API] — This is the designated default get API for the mealPlan data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a meal plan by ID with meals. Users see their own, admins can see any.

Rest Route

The getMealPlan API REST controller can be triggered via the following route:

/v1/mealplans/:mealPlanId

Rest Request Parameters

The getMealPlan api has got 1 regular request parameter

Parameter Type Required Population
mealPlanId ID true request.params?.[“mealPlanId”]
mealPlanId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/mealplans/:mealPlanId

  axios({
    method: 'GET',
    url: `/v1/mealplans/${mealPlanId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "mealPlan",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"mealPlan": {
		"id": "ID",
		"carbGrams": "Float",
		"dailyCalorieTarget": "Integer",
		"fatGrams": "Float",
		"notes": "Text",
		"proteinGrams": "Float",
		"restDayCalories": "Integer",
		"restDayCarbGrams": "Float",
		"status": "Enum",
		"status_idx": "Integer",
		"trainingDayCalories": "Integer",
		"trainingDayCarbGrams": "Float",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"meals": [
			{
				"id": "ID",
				"carbs": "Float",
				"fat": "Float",
				"foods": "Text",
				"mealLabel": "String",
				"mealPlanId": "ID",
				"protein": "Float",
				"sortOrder": "Integer",
				"totalCalories": "Integer",
				"isActive": true,
				"recordVersion": "Integer",
				"createdAt": "Date",
				"updatedAt": "Date",
				"_owner": "ID"
			},
			{},
			{}
		]
	}
}

Get Moderationrecord API

[Default get API] — This is the designated default get API for the moderationRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a moderation record by ID. Admin only.

Rest Route

The getModerationRecord API REST controller can be triggered via the following route:

/v1/moderationrecords/:moderationRecordId

Rest Request Parameters

The getModerationRecord api has got 1 regular request parameter

Parameter Type Required Population
moderationRecordId ID true request.params?.[“moderationRecordId”]
moderationRecordId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/moderationrecords/:moderationRecordId

  axios({
    method: 'GET',
    url: `/v1/moderationrecords/${moderationRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "moderationRecord",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"moderationRecord": {
		"id": "ID",
		"action": "Enum",
		"action_idx": "Integer",
		"offenseType": "String",
		"reason": "Text",
		"suspensionExpiresAt": "Date",
		"userId": "ID",
		"content": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Get Myquota API

Get the current user’s quota usage for the active period.

Rest Route

The getMyQuota API REST controller can be triggered via the following route:

/v1/my-quota

Rest Request Parameters The getMyQuota api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/my-quota

  axios({
    method: 'GET',
    url: '/v1/my-quota',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userQuota",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userQuota": {
		"id": "ID",
		"messageCount": "Integer",
		"periodEnd": "Date",
		"periodStart": "Date",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Planmeal API

[Default get API] — This is the designated default get API for the planMeal data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a plan meal by ID with parent ownership validation.

Rest Route

The getPlanMeal API REST controller can be triggered via the following route:

/v1/planmeals/:planMealId

Rest Request Parameters

The getPlanMeal api has got 1 regular request parameter

Parameter Type Required Population
planMealId ID true request.params?.[“planMealId”]
planMealId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/planmeals/:planMealId

  axios({
    method: 'GET',
    url: `/v1/planmeals/${planMealId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "planMeal",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"planMeal": {
		"id": "ID",
		"carbs": "Float",
		"fat": "Float",
		"foods": "Text",
		"mealLabel": "String",
		"mealPlanId": "ID",
		"protein": "Float",
		"sortOrder": "Integer",
		"totalCalories": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Programexercise API

[Default get API] — This is the designated default get API for the programExercise data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a program exercise by ID with parent ownership validation.

Rest Route

The getProgramExercise API REST controller can be triggered via the following route:

/v1/programexercises/:programExerciseId

Rest Request Parameters

The getProgramExercise api has got 1 regular request parameter

Parameter Type Required Population
programExerciseId ID true request.params?.[“programExerciseId”]
programExerciseId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/programexercises/:programExerciseId

  axios({
    method: 'GET',
    url: `/v1/programexercises/${programExerciseId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "programExercise",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"programExercise": {
		"id": "ID",
		"dayLabel": "String",
		"exerciseName": "String",
		"movementType": "Enum",
		"movementType_idx": "Integer",
		"muscleGroup": "String",
		"progressionRule": "Text",
		"repMax": "Integer",
		"repMin": "Integer",
		"rirTarget": "Integer",
		"sets": "Integer",
		"sortOrder": "Integer",
		"trainingProgramId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Quotaconfig API

[Default get API] — This is the designated default get API for the quotaConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a quota configuration record.

Rest Route

The getQuotaConfig API REST controller can be triggered via the following route:

/v1/quotaconfigs/:quotaConfigId

Rest Request Parameters

The getQuotaConfig api has got 1 regular request parameter

Parameter Type Required Population
quotaConfigId ID true request.params?.[“quotaConfigId”]
quotaConfigId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/quotaconfigs/:quotaConfigId

  axios({
    method: 'GET',
    url: `/v1/quotaconfigs/${quotaConfigId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "quotaConfig",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"quotaConfig": {
		"id": "ID",
		"quotaLimit": "Integer",
		"quotaPeriod": "Enum",
		"quotaPeriod_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Trainingprogram API

[Default get API] — This is the designated default get API for the trainingProgram data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a training program by ID. Users see their own programs, admins can see any.

Rest Route

The getTrainingProgram API REST controller can be triggered via the following route:

/v1/trainingprograms/:trainingProgramId

Rest Request Parameters

The getTrainingProgram api has got 1 regular request parameter

Parameter Type Required Population
trainingProgramId ID true request.params?.[“trainingProgramId”]
trainingProgramId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/trainingprograms/:trainingProgramId

  axios({
    method: 'GET',
    url: `/v1/trainingprograms/${trainingProgramId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "trainingProgram",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"trainingProgram": {
		"id": "ID",
		"cardioDurationMinutes": "Integer",
		"cardioFrequencyPerWeek": "Integer",
		"cardioType": "String",
		"dailyStepTarget": "Integer",
		"deloadIntervalWeeks": "Integer",
		"notes": "Text",
		"splitType": "String",
		"status": "Enum",
		"status_idx": "Integer",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"exercises": [
			{
				"id": "ID",
				"dayLabel": "String",
				"exerciseName": "String",
				"movementType": "Enum",
				"movementType_idx": "Integer",
				"muscleGroup": "String",
				"progressionRule": "Text",
				"repMax": "Integer",
				"repMin": "Integer",
				"rirTarget": "Integer",
				"sets": "Integer",
				"sortOrder": "Integer",
				"trainingProgramId": "ID",
				"isActive": true,
				"recordVersion": "Integer",
				"createdAt": "Date",
				"updatedAt": "Date",
				"_owner": "ID"
			},
			{},
			{}
		]
	}
}

Get Userquota API

[Default get API] — This is the designated default get API for the userQuota data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a user quota record. Users see their own, admins can see any.

Rest Route

The getUserQuota API REST controller can be triggered via the following route:

/v1/userquotas/:userQuotaId

Rest Request Parameters

The getUserQuota api has got 1 regular request parameter

Parameter Type Required Population
userQuotaId ID true request.params?.[“userQuotaId”]
userQuotaId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/userquotas/:userQuotaId

  axios({
    method: 'GET',
    url: `/v1/userquotas/${userQuotaId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userQuota",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userQuota": {
		"id": "ID",
		"messageCount": "Integer",
		"periodEnd": "Date",
		"periodStart": "Date",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"additionalQuota": "Object"
}

Get Weightlog API

[Default get API] — This is the designated default get API for the weightLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a weight log entry by ID.

Rest Route

The getWeightLog API REST controller can be triggered via the following route:

/v1/weightlogs/:weightLogId

Rest Request Parameters

The getWeightLog api has got 1 regular request parameter

Parameter Type Required Population
weightLogId ID true request.params?.[“weightLogId”]
weightLogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/weightlogs/:weightLogId

  axios({
    method: 'GET',
    url: `/v1/weightlogs/${weightLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "weightLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"weightLog": {
		"id": "ID",
		"measuredAt": "Date",
		"userId": "ID",
		"weightKg": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Chatmessages API

[Default list API] — This is the designated default list API for the chatMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. List chat messages for a conversation with parent ownership validation.

Rest Route

The listChatMessages API REST controller can be triggered via the following route:

/v1/chatmessages

Rest Request Parameters

The listChatMessages api has got 1 regular request parameter

Parameter Type Required Population
conversationId ID true request.query?.[“conversationId”]
conversationId : The conversation to list messages for

REST Request To access the api you can use the REST controller with the path GET /v1/chatmessages

  axios({
    method: 'GET',
    url: '/v1/chatmessages',
    data: {
    
    },
    params: {
             conversationId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chatMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chatMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationId": "ID",
			"flagged": "Boolean",
			"role": "Enum",
			"role_idx": "Integer",
			"toolCallData": "Text",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Coachconversations API

[Default list API] — This is the designated default list API for the coachConversation data object. Frontend generators and AI agents should use this API for standard CRUD operations. List conversations. Users see their own, admins can see all.

Rest Route

The listCoachConversations API REST controller can be triggered via the following route:

/v1/coachconversations

Rest Request Parameters

Filter Parameters

The listCoachConversations api supports 2 optional filter parameters for filtering list results:

status (Enum): Conversation status

userId (ID): Reference to the user who owns this conversation

REST Request To access the api you can use the REST controller with the path GET /v1/coachconversations

  axios({
    method: 'GET',
    url: '/v1/coachconversations',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // status: '<value>' // Filter by status
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "coachConversations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"coachConversations": [
		{
			"id": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Mealplans API

[Default list API] — This is the designated default list API for the mealPlan data object. Frontend generators and AI agents should use this API for standard CRUD operations. List meal plans. Users see their own, admins can see all.

Rest Route

The listMealPlans API REST controller can be triggered via the following route:

/v1/mealplans

Rest Request Parameters

Filter Parameters

The listMealPlans api supports 2 optional filter parameters for filtering list results:

status (Enum): Meal plan status

userId (ID): Reference to the user who owns this meal plan

REST Request To access the api you can use the REST controller with the path GET /v1/mealplans

  axios({
    method: 'GET',
    url: '/v1/mealplans',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // status: '<value>' // Filter by status
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "mealPlans",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"mealPlans": [
		{
			"id": "ID",
			"carbGrams": "Float",
			"dailyCalorieTarget": "Integer",
			"fatGrams": "Float",
			"notes": "Text",
			"proteinGrams": "Float",
			"restDayCalories": "Integer",
			"restDayCarbGrams": "Float",
			"status": "Enum",
			"status_idx": "Integer",
			"trainingDayCalories": "Integer",
			"trainingDayCarbGrams": "Float",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Moderationrecords API

[Default list API] — This is the designated default list API for the moderationRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moderation records. Admin only. Supports filtering by userId and action.

Rest Route

The listModerationRecords API REST controller can be triggered via the following route:

/v1/moderationrecords

Rest Request Parameters

Filter Parameters

The listModerationRecords api supports 2 optional filter parameters for filtering list results:

action (Enum): Moderation action taken

userId (ID): Reference to the user who was moderated

REST Request To access the api you can use the REST controller with the path GET /v1/moderationrecords

  axios({
    method: 'GET',
    url: '/v1/moderationrecords',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // action: '<value>' // Filter by action
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "moderationRecords",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"moderationRecords": [
		{
			"id": "ID",
			"action": "Enum",
			"action_idx": "Integer",
			"offenseType": "String",
			"reason": "Text",
			"suspensionExpiresAt": "Date",
			"userId": "ID",
			"content": "String",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Planmeals API

[Default list API] — This is the designated default list API for the planMeal data object. Frontend generators and AI agents should use this API for standard CRUD operations. List meals for a meal plan with parent ownership validation.

Rest Route

The listPlanMeals API REST controller can be triggered via the following route:

/v1/planmeals

Rest Request Parameters

The listPlanMeals api has got 1 regular request parameter

Parameter Type Required Population
mealPlanId ID true request.query?.[“mealPlanId”]
mealPlanId : The meal plan ID to list meals for

REST Request To access the api you can use the REST controller with the path GET /v1/planmeals

  axios({
    method: 'GET',
    url: '/v1/planmeals',
    data: {
    
    },
    params: {
             mealPlanId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "planMeals",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"planMeals": [
		{
			"id": "ID",
			"carbs": "Float",
			"fat": "Float",
			"foods": "Text",
			"mealLabel": "String",
			"mealPlanId": "ID",
			"protein": "Float",
			"sortOrder": "Integer",
			"totalCalories": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Programexercises API

[Default list API] — This is the designated default list API for the programExercise data object. Frontend generators and AI agents should use this API for standard CRUD operations. List exercises for a training program. Validates parent program ownership.

Rest Route

The listProgramExercises API REST controller can be triggered via the following route:

/v1/programexercises

Rest Request Parameters

The listProgramExercises api has got 1 regular request parameter

Parameter Type Required Population
trainingProgramId ID true request.query?.[“trainingProgramId”]
trainingProgramId : The training program ID to list exercises for

REST Request To access the api you can use the REST controller with the path GET /v1/programexercises

  axios({
    method: 'GET',
    url: '/v1/programexercises',
    data: {
    
    },
    params: {
             trainingProgramId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "programExercises",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"programExercises": [
		{
			"id": "ID",
			"dayLabel": "String",
			"exerciseName": "String",
			"movementType": "Enum",
			"movementType_idx": "Integer",
			"muscleGroup": "String",
			"progressionRule": "Text",
			"repMax": "Integer",
			"repMin": "Integer",
			"rirTarget": "Integer",
			"sets": "Integer",
			"sortOrder": "Integer",
			"trainingProgramId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Quotaconfigs API

[Default list API] — This is the designated default list API for the quotaConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. List quota configuration records.

Rest Route

The listQuotaConfigs API REST controller can be triggered via the following route:

/v1/quotaconfigs

Rest Request Parameters The listQuotaConfigs api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/quotaconfigs

  axios({
    method: 'GET',
    url: '/v1/quotaconfigs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "quotaConfigs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"quotaConfigs": [
		{
			"id": "ID",
			"quotaLimit": "Integer",
			"quotaPeriod": "Enum",
			"quotaPeriod_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Trainingprograms API

[Default list API] — This is the designated default list API for the trainingProgram data object. Frontend generators and AI agents should use this API for standard CRUD operations. List training programs. Users see their own programs, admins can see all.

Rest Route

The listTrainingPrograms API REST controller can be triggered via the following route:

/v1/trainingprograms

Rest Request Parameters

Filter Parameters

The listTrainingPrograms api supports 2 optional filter parameters for filtering list results:

status (Enum): Program status

userId (ID): Reference to the user who owns this training program

REST Request To access the api you can use the REST controller with the path GET /v1/trainingprograms

  axios({
    method: 'GET',
    url: '/v1/trainingprograms',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // status: '<value>' // Filter by status
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "trainingPrograms",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"trainingPrograms": [
		{
			"id": "ID",
			"cardioDurationMinutes": "Integer",
			"cardioFrequencyPerWeek": "Integer",
			"cardioType": "String",
			"dailyStepTarget": "Integer",
			"deloadIntervalWeeks": "Integer",
			"notes": "Text",
			"splitType": "String",
			"status": "Enum",
			"status_idx": "Integer",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Userquotas API

[Default list API] — This is the designated default list API for the userQuota data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all user quotas. Admin only.

Rest Route

The listUserQuotas API REST controller can be triggered via the following route:

/v1/userquotas

Rest Request Parameters

Filter Parameters

The listUserQuotas api supports 1 optional filter parameter for filtering list results:

userId (ID): Reference to the user whose quota is being tracked

REST Request To access the api you can use the REST controller with the path GET /v1/userquotas

  axios({
    method: 'GET',
    url: '/v1/userquotas',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userQuotas",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userQuotas": [
		{
			"id": "ID",
			"messageCount": "Integer",
			"periodEnd": "Date",
			"periodStart": "Date",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Weightlogs API

[Default list API] — This is the designated default list API for the weightLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. List weight log entries. Users see their own, admins see all.

Rest Route

The listWeightLogs API REST controller can be triggered via the following route:

/v1/weightlogs

Rest Request Parameters The listWeightLogs api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/weightlogs

  axios({
    method: 'GET',
    url: '/v1/weightlogs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "weightLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"weightLogs": [
		{
			"id": "ID",
			"measuredAt": "Date",
			"userId": "ID",
			"weightKg": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Quotaconfig API

[Default update API] — This is the designated default update API for the quotaConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a quota configuration record. Admin only.

Rest Route

The updateQuotaConfig API REST controller can be triggered via the following route:

/v1/quotaconfigs/:quotaConfigId

Rest Request Parameters

The updateQuotaConfig api has got 3 regular request parameters

Parameter Type Required Population
quotaConfigId ID true request.params?.[“quotaConfigId”]
quotaLimit Integer false request.body?.[“quotaLimit”]
quotaPeriod Enum false request.body?.[“quotaPeriod”]
quotaConfigId : This id paremeter is used to select the required data object that will be updated
quotaLimit : Maximum messages allowed per period
quotaPeriod : Period over which the quota is measured

REST Request To access the api you can use the REST controller with the path PATCH /v1/quotaconfigs/:quotaConfigId

  axios({
    method: 'PATCH',
    url: `/v1/quotaconfigs/${quotaConfigId}`,
    data: {
            quotaLimit:"Integer",  
            quotaPeriod:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "quotaConfig",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"quotaConfig": {
		"id": "ID",
		"quotaLimit": "Integer",
		"quotaPeriod": "Enum",
		"quotaPeriod_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Moderationrecord API

Rest Route

The deleteModerationRecord API REST controller can be triggered via the following route:

/v1/moderationrecords/:moderationRecordId

Rest Request Parameters

The deleteModerationRecord api has got 1 regular request parameter

Parameter Type Required Population
moderationRecordId ID true request.params?.[“moderationRecordId”]
moderationRecordId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/moderationrecords/:moderationRecordId

  axios({
    method: 'DELETE',
    url: `/v1/moderationrecords/${moderationRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "moderationRecord",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"moderationRecord": {
		"id": "ID",
		"action": "Enum",
		"action_idx": "Integer",
		"offenseType": "String",
		"reason": "Text",
		"suspensionExpiresAt": "Date",
		"userId": "ID",
		"content": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Do Deletemealplan API

Rest Route

The deletemealplan API REST controller can be triggered via the following route:

/v1/deletemealplan/:mealPlanId

Rest Request Parameters

The deletemealplan api has got 1 regular request parameter

Parameter Type Required Population
mealPlanId ID true request.params?.[“mealPlanId”]
mealPlanId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/deletemealplan/:mealPlanId

  axios({
    method: 'DELETE',
    url: `/v1/deletemealplan/${mealPlanId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "mealPlan",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"mealPlan": {
		"id": "ID",
		"carbGrams": "Float",
		"dailyCalorieTarget": "Integer",
		"fatGrams": "Float",
		"notes": "Text",
		"proteinGrams": "Float",
		"restDayCalories": "Integer",
		"restDayCarbGrams": "Float",
		"status": "Enum",
		"status_idx": "Integer",
		"trainingDayCalories": "Integer",
		"trainingDayCarbGrams": "Float",
		"userId": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Do Deletetrainingprogram API

Rest Route

The deletetrainingprogram API REST controller can be triggered via the following route:

/v1/deletetrainingprogram/:trainingProgramId

Rest Request Parameters

The deletetrainingprogram api has got 1 regular request parameter

Parameter Type Required Population
trainingProgramId ID true request.params?.[“trainingProgramId”]
trainingProgramId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/deletetrainingprogram/:trainingProgramId

  axios({
    method: 'DELETE',
    url: `/v1/deletetrainingprogram/${trainingProgramId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "trainingProgram",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"trainingProgram": {
		"id": "ID",
		"cardioDurationMinutes": "Integer",
		"cardioFrequencyPerWeek": "Integer",
		"cardioType": "String",
		"dailyStepTarget": "Integer",
		"deloadIntervalWeeks": "Integer",
		"notes": "Text",
		"splitType": "String",
		"status": "Enum",
		"status_idx": "Integer",
		"userId": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Moderationrecord API

Rest Route

The updateModerationRecord API REST controller can be triggered via the following route:

/v1/moderationrecords/:moderationRecordId

Rest Request Parameters

The updateModerationRecord api has got 3 regular request parameters

Parameter Type Required Population
moderationRecordId ID true request.params?.[“moderationRecordId”]
action String true request.body?.[“action”]
content String false request.body?.[“content”]
moderationRecordId : This id paremeter is used to select the required data object that will be updated
action :
content :

REST Request To access the api you can use the REST controller with the path PATCH /v1/moderationrecords/:moderationRecordId

  axios({
    method: 'PATCH',
    url: `/v1/moderationrecords/${moderationRecordId}`,
    data: {
            action:"String",  
            content:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "moderationRecord",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"moderationRecord": {
		"id": "ID",
		"action": "Enum",
		"action_idx": "Integer",
		"offenseType": "String",
		"reason": "Text",
		"suspensionExpiresAt": "Date",
		"userId": "ID",
		"content": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Do Listmymoderationrecords API

Rest Route

The listmymoderationrecords API REST controller can be triggered via the following route:

/v1/listmymoderationrecords

Rest Request Parameters

Filter Parameters

The listmymoderationrecords api supports 1 optional filter parameter for filtering list results:

action (Enum): Moderation action taken

REST Request To access the api you can use the REST controller with the path GET /v1/listmymoderationrecords

  axios({
    method: 'GET',
    url: '/v1/listmymoderationrecords',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // action: '<value>' // Filter by action
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "moderationRecords",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"moderationRecords": [
		{
			"id": "ID",
			"action": "Enum",
			"action_idx": "Integer",
			"offenseType": "String",
			"reason": "Text",
			"suspensionExpiresAt": "Date",
			"userId": "ID",
			"content": "String",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Banappeals API

Rest Route

The listBanAppeals API REST controller can be triggered via the following route:

/v1/banappealses

Rest Request Parameters

The listBanAppeals api has got 2 regular request parameters

Parameter Type Required Population
userId ID false request.query?.[“userId”]
status ID false request.query?.[“status”]
userId :
status :

REST Request To access the api you can use the REST controller with the path GET /v1/banappealses

  axios({
    method: 'GET',
    url: '/v1/banappealses',
    data: {
    
    },
    params: {
             userId:'"ID"',  
             status:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "banAppealses",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"banAppealses": [
		{
			"id": "ID",
			"moderationRecordId": "ID",
			"userId": "ID",
			"appealReason": "String",
			"status": "Enum",
			"status_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"showmoderationRecord": [
				{
					"offenseType": "String",
					"reason": "Text",
					"userId": "ID",
					"content": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Banappeal API

Rest Route

The createBanAppeal API REST controller can be triggered via the following route:

/v1/banappeal

Rest Request Parameters

The createBanAppeal api has got 3 regular request parameters

Parameter Type Required Population
moderationRecordId ID true request.body?.[“moderationRecordId”]
appealReason String true request.body?.[“appealReason”]
status Enum true request.body?.[“status”]
moderationRecordId : id of the mod record
appealReason :
status :

REST Request To access the api you can use the REST controller with the path POST /v1/banappeal

  axios({
    method: 'POST',
    url: '/v1/banappeal',
    data: {
            moderationRecordId:"ID",  
            appealReason:"String",  
            status:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "banAppeals",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"banAppeals": {
		"id": "ID",
		"moderationRecordId": "ID",
		"userId": "ID",
		"appealReason": "String",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Banappeal API

Rest Route

The updateBanAppeal API REST controller can be triggered via the following route:

/v1/banappeal/:banAppealsId

Rest Request Parameters

The updateBanAppeal api has got 4 regular request parameters

Parameter Type Required Population
banAppealsId ID true request.params?.[“banAppealsId”]
status Enum true request.body?.[“status”]
moderationRecordId ID false request.body?.[“moderationRecordId”]
appealReason String false request.body?.[“appealReason”]
banAppealsId : This id paremeter is used to select the required data object that will be updated
status :
moderationRecordId : id of the mod record
appealReason :

REST Request To access the api you can use the REST controller with the path PATCH /v1/banappeal/:banAppealsId

  axios({
    method: 'PATCH',
    url: `/v1/banappeal/${banAppealsId}`,
    data: {
            status:"Enum",  
            moderationRecordId:"ID",  
            appealReason:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "banAppeals",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"banAppeals": {
		"id": "ID",
		"moderationRecordId": "ID",
		"userId": "ID",
		"appealReason": "String",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Additionalquota API

Rest Route

The createAdditionalQuota API REST controller can be triggered via the following route:

/v1/additionalquotas

Rest Request Parameters

The createAdditionalQuota api has got 9 regular request parameters

Parameter Type Required Population
additionalMessage Integer true request.body?.[“additionalMessage”]
status Enum true request.body?.[“status”]
currency String true request.body?.[“currency”]
pricePaid Integer true request.body?.[“pricePaid”]
statusUpdatedAt Date false request.body?.[“statusUpdatedAt”]
activatedAt Date false request.body?.[“activatedAt”]
cancelledAt Date false request.body?.[“cancelledAt”]
periodEnd Date false request.body?.[“periodEnd”]
periodStart Date false request.body?.[“periodStart”]
additionalMessage :
status :
currency :
pricePaid :
statusUpdatedAt :
activatedAt :
cancelledAt :
periodEnd :
periodStart :

REST Request To access the api you can use the REST controller with the path POST /v1/additionalquotas

  axios({
    method: 'POST',
    url: '/v1/additionalquotas',
    data: {
            additionalMessage:"Integer",  
            status:"Enum",  
            currency:"String",  
            pricePaid:"Integer",  
            statusUpdatedAt:"Date",  
            activatedAt:"Date",  
            cancelledAt:"Date",  
            periodEnd:"Date",  
            periodStart:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "additionalQuota",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"additionalQuota": {
		"id": "ID",
		"userId": "String",
		"additionalMessage": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"currency": "String",
		"pricePaid": "Integer",
		"statusUpdatedAt": "Date",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"periodEnd": "Date",
		"periodStart": "Date",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Myadditionalquota API

Rest Route

The getMyAdditionalQuota API REST controller can be triggered via the following route:

/v1/myadditionalquota

Rest Request Parameters The getMyAdditionalQuota api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/myadditionalquota

  axios({
    method: 'GET',
    url: '/v1/myadditionalquota',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "additionalQuota",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"additionalQuota": {
		"id": "ID",
		"userId": "String",
		"additionalMessage": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"currency": "String",
		"pricePaid": "Integer",
		"statusUpdatedAt": "Date",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"periodEnd": "Date",
		"periodStart": "Date",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"myaddQuota": "Object"
}

Get Additionalquotapayment API

This route is used to get the payment information by ID.

Rest Route

The getAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/additionalquotapayment/:sys_additionalQuotaPaymentId

Rest Request Parameters

The getAdditionalQuotaPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_additionalQuotaPaymentId ID true request.params?.[“sys_additionalQuotaPaymentId”]
sys_additionalQuotaPaymentId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/additionalquotapayment/:sys_additionalQuotaPaymentId

  axios({
    method: 'GET',
    url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_additionalQuotaPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Additionalquotapayments API

This route is used to list all payments.

Rest Route

The listAdditionalQuotaPayments API REST controller can be triggered via the following route:

/v1/additionalquotapayments

Rest Request Parameters

Filter Parameters

The listAdditionalQuotaPayments api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source additionalQuota object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path GET /v1/additionalquotapayments

  axios({
    method: 'GET',
    url: '/v1/additionalquotapayments',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayments",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_additionalQuotaPayments": [
		{
			"id": "ID",
			"ownerId": "ID",
			"orderId": "ID",
			"paymentId": "String",
			"paymentStatus": "String",
			"statusLiteral": "String",
			"redirectUrl": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Additionalquotapayment API

This route is used to create a new payment.

Rest Route

The createAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/additionalquotapayment

Rest Request Parameters

The createAdditionalQuotaPayment api has got 5 regular request parameters

Parameter Type Required Population
orderId ID true request.body?.[“orderId”]
paymentId String true request.body?.[“paymentId”]
paymentStatus String true request.body?.[“paymentStatus”]
statusLiteral String true request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
orderId : an ID value to represent the orderId which is the ID parameter of the source additionalQuota object
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path POST /v1/additionalquotapayment

  axios({
    method: 'POST',
    url: '/v1/additionalquotapayment',
    data: {
            orderId:"ID",  
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayment",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_additionalQuotaPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Additionalquotapayment API

This route is used to update an existing payment.

Rest Route

The updateAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/additionalquotapayment/:sys_additionalQuotaPaymentId

Rest Request Parameters

The updateAdditionalQuotaPayment api has got 5 regular request parameters

Parameter Type Required Population
sys_additionalQuotaPaymentId ID true request.params?.[“sys_additionalQuotaPaymentId”]
paymentId String false request.body?.[“paymentId”]
paymentStatus String false request.body?.[“paymentStatus”]
statusLiteral String false request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
sys_additionalQuotaPaymentId : This id paremeter is used to select the required data object that will be updated
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path PATCH /v1/additionalquotapayment/:sys_additionalQuotaPaymentId

  axios({
    method: 'PATCH',
    url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`,
    data: {
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayment",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_additionalQuotaPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Additionalquotapayment API

This route is used to delete a payment.

Rest Route

The deleteAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/additionalquotapayment/:sys_additionalQuotaPaymentId

Rest Request Parameters

The deleteAdditionalQuotaPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_additionalQuotaPaymentId ID true request.params?.[“sys_additionalQuotaPaymentId”]
sys_additionalQuotaPaymentId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/additionalquotapayment/:sys_additionalQuotaPaymentId

  axios({
    method: 'DELETE',
    url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayment",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_additionalQuotaPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Additionalquotapaymentbyorderid API

This route is used to get the payment information by order id.

Rest Route

The getAdditionalQuotaPaymentByOrderId API REST controller can be triggered via the following route:

/v1/additionalQuotapaymentbyorderid/:orderId

Rest Request Parameters

The getAdditionalQuotaPaymentByOrderId api has got 1 regular request parameter

Parameter Type Required Population
orderId ID true request.params?.[“orderId”]
orderId : an ID value to represent the orderId which is the ID parameter of the source additionalQuota object. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/additionalQuotapaymentbyorderid/:orderId

  axios({
    method: 'GET',
    url: `/v1/additionalQuotapaymentbyorderid/${orderId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_additionalQuotaPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Additionalquotapaymentbypaymentid API

This route is used to get the payment information by payment id.

Rest Route

The getAdditionalQuotaPaymentByPaymentId API REST controller can be triggered via the following route:

/v1/additionalQuotapaymentbypaymentid/:paymentId

Rest Request Parameters

The getAdditionalQuotaPaymentByPaymentId api has got 1 regular request parameter

Parameter Type Required Population
paymentId String true request.params?.[“paymentId”]
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/additionalQuotapaymentbypaymentid/:paymentId

  axios({
    method: 'GET',
    url: `/v1/additionalQuotapaymentbypaymentid/${paymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_additionalQuotaPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_additionalQuotaPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Start Additionalquotapayment API

Start payment for additionalQuota

Rest Route

The startAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/startadditionalquotapayment/:additionalQuotaId

Rest Request Parameters

The startAdditionalQuotaPayment api has got 2 regular request parameters

Parameter Type Required Population
additionalQuotaId ID true request.params?.[“additionalQuotaId”]
paymentUserParams Object true request.body?.[“paymentUserParams”]
additionalQuotaId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId.

REST Request To access the api you can use the REST controller with the path PATCH /v1/startadditionalquotapayment/:additionalQuotaId

  axios({
    method: 'PATCH',
    url: `/v1/startadditionalquotapayment/${additionalQuotaId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "additionalQuota",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"additionalQuota": {
		"id": "ID",
		"userId": "String",
		"additionalMessage": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"currency": "String",
		"pricePaid": "Integer",
		"statusUpdatedAt": "Date",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"periodEnd": "Date",
		"periodStart": "Date",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Refresh Additionalquotapayment API

Refresh payment info for additionalQuota from Stripe

Rest Route

The refreshAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/refreshadditionalquotapayment/:additionalQuotaId

Rest Request Parameters

The refreshAdditionalQuotaPayment api has got 2 regular request parameters

Parameter Type Required Population
additionalQuotaId ID true request.params?.[“additionalQuotaId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
additionalQuotaId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to refresh a stripe payment process

REST Request To access the api you can use the REST controller with the path PATCH /v1/refreshadditionalquotapayment/:additionalQuotaId

  axios({
    method: 'PATCH',
    url: `/v1/refreshadditionalquotapayment/${additionalQuotaId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "additionalQuota",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"additionalQuota": {
		"id": "ID",
		"userId": "String",
		"additionalMessage": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"currency": "String",
		"pricePaid": "Integer",
		"statusUpdatedAt": "Date",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"periodEnd": "Date",
		"periodStart": "Date",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Callback Additionalquotapayment API

Refresh payment values by gateway webhook call for additionalQuota

Rest Route

The callbackAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/callbackadditionalquotapayment

Rest Request Parameters

The callbackAdditionalQuotaPayment api has got 1 regular request parameter

Parameter Type Required Population
additionalQuotaId ID false request.body?.[“additionalQuotaId”]
additionalQuotaId : The order id parameter that will be read from webhook callback params

REST Request To access the api you can use the REST controller with the path POST /v1/callbackadditionalquotapayment

  axios({
    method: 'POST',
    url: '/v1/callbackadditionalquotapayment',
    data: {
            additionalQuotaId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "additionalQuota",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"additionalQuota": {
		"id": "ID",
		"userId": "String",
		"additionalMessage": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"currency": "String",
		"pricePaid": "Integer",
		"statusUpdatedAt": "Date",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"periodEnd": "Date",
		"periodStart": "Date",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymentcustomerbyuserid API

This route is used to get the payment customer information by user id.

Rest Route

The getPaymentCustomerByUserId API REST controller can be triggered via the following route:

/v1/paymentcustomers/:userId

Rest Request Parameters

The getPaymentCustomerByUserId api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers/:userId

  axios({
    method: 'GET',
    url: `/v1/paymentcustomers/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomer",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_paymentCustomer": {
		"id": "ID",
		"userId": "ID",
		"customerId": "String",
		"platform": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Paymentcustomers API

This route is used to list all payment customers.

Rest Route

The listPaymentCustomers API REST controller can be triggered via the following route:

/v1/paymentcustomers

Rest Request Parameters

Filter Parameters

The listPaymentCustomers api supports 3 optional filter parameters for filtering list results:

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers

  axios({
    method: 'GET',
    url: '/v1/paymentcustomers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // platform: '<value>' // Filter by platform
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentCustomers": [
		{
			"id": "ID",
			"userId": "ID",
			"customerId": "String",
			"platform": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Paymentcustomermethods API

This route is used to list all payment customer methods.

Rest Route

The listPaymentCustomerMethods API REST controller can be triggered via the following route:

/v1/paymentcustomermethods/:userId

Rest Request Parameters

The listPaymentCustomerMethods api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : An ID value to represent the user who owns the payment method. The parameter is used to query data.

Filter Parameters

The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomermethods/:userId

  axios({
    method: 'GET',
    url: `/v1/paymentcustomermethods/${userId}`,
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - AiCoach Service AdditionalQuota Payment Flow

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

Stripe Payment Flow For AdditionalQuota

AdditionalQuota is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database.

The ID of this data object—referenced as additionalQuotaId in the general business logic—will be used as the orderId in the payment flow.

Accessing the service API for the payment flow API

The Aifitapp application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders. To access the related APIs, use the base URL of the aiCoach service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment.

For the aiCoach service, the base URLs are:

Creating the AdditionalQuota

While creating the additionalQuota instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of additionalQuota). The payment flow begins after the object is created.

Because of the data object’s Stripe order settings, the payment flow is aware of the following fields, references, and their purposes:

Before Payment Flow Starts

It is assumed that the frontend provides a “Pay” or “Checkout” button that initiates the payment flow. The following steps occur after the user clicks this button.
Note that an additionalQuota instance must already exist to represent the order being paid, with its initial status set.

A Stripe payment flow can be implemented in several ways, but the best practice is to use a PaymentIntent and manage it jointly from the backend and frontend.
A PaymentIntent represents the intent to collect payment for a given order (or any payable entity).
In the Aifitapp application, the PaymentIntent is created in the backend, while the PaymentMethod (the user’s stored card information) is created in the frontend.
Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference.

The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to add or remove payment methods.
The user must select a Payment Method before starting the payment flow.

Listing the Payment Methods for the User

To list the payment methods of the currently logged-in user, call the following system API (unversioned):

GET /payment-methods/list

This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope.

const response = await fetch("$serviceUrl/payment-methods/list", {
  method: "GET",
  headers: { "Content-Type": "application/json" },
});

Example response:

[
  {
    "id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01",
    "paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8",
    "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
    "customerId": "cus_TNgWUw5QkmUPLa",
    "cardHolderName": "John Doe",
    "cardHolderZip": "34662",
    "platform": "stripe",
    "cardInfo": {
      "brand": "visa",
      "last4": "4242",
      "checks": {
        "cvc_check": "pass",
        "address_postal_code_check": "pass"
      },
      "funding": "credit",
      "exp_month": 11,
      "exp_year": 2033
    },
    "isActive": true,
    "createdAt": "2025-11-07T19:16:38.469Z",
    "updatedAt": "2025-11-07T19:16:38.469Z",
    "_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2"
  }
]

In each payment method object, the following fields are useful for displaying to the user:

for (const method of paymentMethods) {
  const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons
  const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow
  const cardHolderName = method.cardHolderName; // show in list
  const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number
  const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date
  const id = method.id; // internal DB record ID, used for deletion
  const customerId = method.customerId; // Stripe customer reference
}

If the list is empty, prompt the user to add a new payment method.

Creating a Payment Method

The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled entirely through Stripe.js on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse.

Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns.

To initialize Stripe on the frontend, include your public key:

<script src="https://js.stripe.com/v3/?advancedFraudSignals=false"></script>
const stripe = Stripe("pk_test_51POkqt4..................");
const elements = stripe.elements();

const cardNumberElement = elements.create("cardNumber", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardNumberElement.mount("#card-number-element");

const cardExpiryElement = elements.create("cardExpiry", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardExpiryElement.mount("#card-expiry-element");

const cardCvcElement = elements.create("cardCvc", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardCvcElement.mount("#card-cvc-element");

// Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure).

You can dynamically show the card brand while typing:

cardNumberElement.on("change", (event) => {
  const cardBrand = event.brand;
  const cardNumberDiv = document.getElementById("card-number-element");
  cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand);
});

Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code.

const { paymentMethod, error } = await stripe.createPaymentMethod({
  type: "card",
  card: cardNumberElement,
  billing_details: {
    name: cardholderName.value,
    address: { postal_code: cardholderZip.value },
  },
});

When a paymentMethod is successfully created, send its ID to your backend to attach it to the logged-in user’s account.

Use the system API (unversioned):

POST /payment-methods/add

Example:

const response = await fetch("$serviceUrl/payment-methods/add", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ paymentMethodId: paymentMethod.id }),
});

When addPaymentMethod is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use.

Example response:

{
  "isActive": true,
  "cardHolderName": "John Doe",
  "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
  "customerId": "cus_TNgWUw5QkmUPLa",
  "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
  "platform": "stripe",
  "cardHolderZip": "34662",
  "cardInfo": {
    "brand": "visa",
    "last4": "4242",
    "funding": "credit",
    "exp_month": 11,
    "exp_year": 2033
  },
  "id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf",
  "createdAt": "2025-11-07T20:16:55.451Z",
  "updatedAt": "2025-11-07T20:16:55.451Z"
}

You can append this new entry directly to the UI list or refresh the list using the listPaymentMethods API.

Deleting a Payment Method

To remove a saved payment method from the current user’s account, call the system API (unversioned):

DELETE /payment-methods/delete/:paymentMethodId

Example:

await fetch(
  `$serviceUrl/payment-methods/delete/${paymentMethodId}`,
  {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  }
);

Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object

The payment flow is initiated in the backend through the startAdditionalQuotaPayment API.
This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend forces the user to select a payment method before initiating the payment.

The startAdditionalQuotaPayment API is a versioned Business Logic API and follows the same structure as other business APIs.

In the Aifitapp application, the payment flow starts by creating a Stripe PaymentIntent and confirming it in a single step within the backend.
In a typical (“happy”) path, when the startAdditionalQuotaPayment API is called, the response will include a successful or failed PaymentIntent result inside the paymentResult object, along with the additionalQuota object.

However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately.
In such cases, control should return to a frontend page to allow the user to finish the process.
To enable this, a return_url must be provided during the PaymentIntent creation step.

Although technically optional, it is strongly recommended to include a return_url.
This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction.
The return_url must be a frontend URL.

The paymentUserParams parameter of the startAdditionalQuotaPayment API contains the data necessary to create the Stripe PaymentIntent.

Call the API as follows:

const response = await fetch(
  `$serviceUrl/v1/startadditionalQuotapayment/${orderId}`,
  {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      paymentUserParams: {
        paymentMethodId,
        return_url: `${yourFrontendReturnUrl}`,
      },
    }),
  }
);

The API response will contain a paymentResult object. If an error occurs, it will begin with { "result": "ERR" }. Otherwise, it will include the PaymentIntent information:

{
  "paymentResult": {
    "success": true,
    "paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
    "paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
      "clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg",
      "publicKey": "pk_test_51POkqWP5uU",
      "status": "succeeded"
    },
    "statusLiteral": "success",
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10",
    "metadata": {
      "order": "Purchase-Purchase-order",
      "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
      "checkoutName": "babilOrder"
    },
    "paymentUserParams": {
      "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
      "return_url": "${yourFrontendReturnUrl}"
    }
  }
}

Start Additionalquotapayment API

Start payment for additionalQuota

Rest Route

The startAdditionalQuotaPayment API REST controller can be triggered via the following route:

/v1/startadditionalquotapayment/:additionalQuotaId

Rest Request Parameters

The startAdditionalQuotaPayment api has got 2 regular request parameters

Parameter Type Required Population
additionalQuotaId ID true request.params?.[“additionalQuotaId”]
paymentUserParams Object true request.body?.[“paymentUserParams”]
additionalQuotaId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId.

REST Request To access the api you can use the REST controller with the path PATCH /v1/startadditionalquotapayment/:additionalQuotaId

  axios({
    method: 'PATCH',
    url: `/v1/startadditionalquotapayment/${additionalQuotaId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "additionalQuota",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"additionalQuota": {
		"id": "ID",
		"userId": "String",
		"additionalMessage": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"currency": "String",
		"pricePaid": "Integer",
		"statusUpdatedAt": "Date",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"periodEnd": "Date",
		"periodStart": "Date",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Analyzing the API Response

After calling the startAdditionalQuotaPayment API, the most common expected outcome is a confirmed and completed payment. However, several alternate cases should be handled on the frontend.

System Error Case

The API may return a classic service-level error (unrelated to payment). Check the HTTP status code of the response. It should be 200 or 201. Any 400, 401, 403, or 404 indicates a system error.

{
  "result": "ERR",
  "status": 404,
  "message": "Record not found",
  "date": "2025-11-08T00:57:54.820Z"
}

Handle system errors on the payment page (show a retry option). Do not navigate to the result page.

Payment Error Case

The API performs both database operations and the Stripe payment operation. If the payment fails but the service logic succeeds, the API may still return a 200 OK status, with the failure recorded in the paymentResult.

In this case, show an error message and allow the user to retry.

{
  "status": "OK",
  "statusCode": "200",
  "additionalQuota": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "failed"
  },
  "paymentResult": {
    "result": "ERR",
    "status": 500,
    "message": "Stripe error message: Your card number is incorrect.",
    "errCode": "invalid_number",
    "date": "2025-11-08T00:57:54.820Z"
  }
}

Payment errors should be handled on the payment page (retry option). Do not go to the result page.


Happy Case

When both the service and payment result succeed, this is considered the happy path. In this case, use the additionalQuota and paymentResult objects in the response to display a success message to the user.

amount and description values are included to help you show payment details on the result page.

{
  "status": "OK",
  "statusCode": "200",
  "order": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "paid"
  },
  "paymentResult": {
    "success": true,
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "status": "succeeded"
    },
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10"
  }
}

To verify success:

if (paymentResult.paymentIntentInfo.status === "succeeded") {
  // Redirect to result page
}

Note: A successful result does not trigger fulfillment immediately. Fulfillment begins only after the Stripe webhook updates the database. It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page.

Handle the happy case in the result page by sending the additionalQuotaId and the payment intent secret.

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

Edge Cases

Although startAdditionalQuotaPayment is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required.

You must handle these cases in both the payment page and the result page, because some next actions are available immediately, while others occur only after a redirect.

If the paymentIntentInfo.status equals "requires_action", handle it using Stripe.js as shown below:

if (paymentResult.paymentIntentInfo.status === "requires_action") {
  await runNextAction(
    paymentResult.paymentIntentInfo.clientSecret,
    paymentResult.paymentIntentInfo.publicKey
  );
}

Helper function:

async function runNextAction(clientSecret, publicKey) {
  const stripe = Stripe(publicKey);
  const { error } = await stripe.handleNextAction({ clientSecret });
  if (error) {
    console.log("next_action error:", error);
    showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500");
    throw new Error(error.message);
  }
}

After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page.

const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

if (paymentIntent.status === "succeeded") {
  showToast("Payment successful!", "fa-circle-check text-green-500");
} else if (paymentIntent.status === "processing") {
  showToast("Payment is processing…", "fa-circle-info text-blue-500");
} else if (paymentIntent.status === "requires_payment_method") {
  showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500");
}

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

The Result Page

The payment result page should handle the following steps:

  1. Read orderId and payment_intent_client_secret from the query parameters.
  2. Retrieve the PaymentIntent from Stripe and check its status.
  3. If required, handle any next_action and re-fetch the PaymentIntent.
  4. If the status is "succeeded", display a clear visual confirmation.
  5. Fetch the additionalQuota instance from the backend to display any additional order or fulfillment details.

Note that paymentIntent status only gives information about the Stripe side. The additionalQuota instance in the service should also ve updated to start the fulfillment. In most cases, the startadditionalQuotaPayment api updates the status of the order using the response of the paymentIntent confirmation, but as stated above in some cases this update can be done only when the webhook executes. So in teh result page always get the final payment status in the `additionalQuota.

To ensure that service i To fetch the additionalQuota instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the additionalQuota instance.

if (additionalQuota.paymentConfirmation == "canceled") {
  // the payment is canceled, user can be informed that they should try again
} if (additionalQuota.paymentConfirmation == "paid") {
  // service knows that payment is done, user can be informed that fullfillment started
} else {
  // it may be pending, processing
  // Fetch the object again until a canceled or paid status
}

Payment Flow via MCP (AI Chat Integration)

The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The aiCoach service exposes an initiatePayment MCP tool that the AI can call when the user wants to pay for an order.

How initiatePayment Works in MCP

  1. User asks to pay — e.g., “I want to pay for my order”
  2. AI calls initiatePayment MCP tool with orderId (and orderType if multiple order types exist)
  3. Tool validates the order exists, is payable, and the user is authorized
  4. Tool returns __frontendAction with type: "payment" — this is NOT a direct payment execution
  5. Frontend chat UI renders a PaymentActionCard with a “Pay Now” button
  6. User clicks “Pay Now” — the frontend opens a payment modal with CheckoutForm
  7. Standard Stripe flow proceeds (payment method selection, 3DS handling, etc.)

Frontend Action Response Format

The initiatePayment MCP tool returns:

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "additionalQuota",
    "serviceName": "aiCoach",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order description"
  },
  "message": "Payment is ready. Click the button below to proceed."
}

MCP Client Architecture

The frontend communicates with MCP tools through the MCP BFF (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides:

The PaymentActionCard component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - Subscription Service

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of subscription

Service Access

Subscription service management is handled through service specific base urls.

Subscription service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the subscription service, the base URLs are:

Scope

Subscription Service Description

Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z

Subscription service provides apis and business logic for following data objects in aifitapp application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

pricingConfig Data Object: Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record.

subscription Data Object: Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates.

sys_subscriptionPayment Data Object: A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object's checkout config

sys_paymentCustomer Data Object: A payment storage object to store the customer values of the payment platform

sys_paymentMethod Data Object: A payment storage object to store the payment methods of the platform customers

Subscription Service Frontend Description By The Backend Architect

Subscription Service UX Guide

This service manages premium subscriptions. Key UX behaviors:

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

PricingConfig Data Object

Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record.

PricingConfig Data Object Properties

PricingConfig data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
currency String false Yes No Currency code for pricing (e.g., usd).
description Text false No No Human-readable description of the subscription plan.
price Integer false Yes No Current subscription price in cents (e.g., 999 = $9.99).
type Enum false Yes No

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Subscription Data Object

Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates.

Subscription Data Object Properties

Subscription data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
activatedAt Date false No No Timestamp when the subscription was activated after successful payment.
cancelledAt Date false No No Timestamp when the subscription was cancelled by the user.
currency String false Yes No Currency code for the payment (e.g., usd).
pricePaid Integer false Yes No Amount paid in cents at the time of subscription activation.
status Enum false No No Current subscription status managed by Stripe payment flow.
statusUpdatedAt Date false No No Timestamp of the last status update, auto-managed by Stripe payment flow.
userId ID false Yes No Reference to the user who owns this subscription.
paymentConfirmation Enum false Yes No An automatic property that is used to check the confirmed status of the payment set by webhooks.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

status userId paymentConfirmation

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_subscriptionPayment Data Object

A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object's checkout config

Sys_subscriptionPayment Data Object Properties

Sys_subscriptionPayment data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
ownerId ID false No No An ID value to represent owner user who created the order
orderId ID false Yes No an ID value to represent the orderId which is the ID parameter of the source subscription object
paymentId String false Yes No A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String false Yes No A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String false Yes No A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String false No No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

Filter Properties

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_paymentCustomer Data Object

A payment storage object to store the customer values of the payment platform

Sys_paymentCustomer Data Object Properties

Sys_paymentCustomer data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
userId ID false No No An ID value to represent the user who is created as a stripe customer
customerId String false Yes No A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String false Yes No A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

Filter Properties

userId customerId platform

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_paymentMethod Data Object

A payment storage object to store the payment methods of the platform customers

Sys_paymentMethod Data Object Properties

Sys_paymentMethod data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
paymentMethodId String false Yes No A string value to represent the id of the payment method on the payment platform.
userId ID false Yes No An ID value to represent the user who owns the payment method
customerId String false Yes No A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String false No No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String false No No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String false Yes No A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object false Yes No A Json value to store the card details of the payment method.

Filter Properties

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

PricingConfig Default APIs

Display Label Property: description — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).

Operation API Name Route Explicitly Set
Create createPricingConfig /v1/pricingconfigs Yes
Update updatePricingConfig /v1/pricingconfigs/:pricingConfigId Yes
Delete deletePricingConfig /v1/pricingconfigs/:pricingConfigId Yes
Get getPricingConfig /v1/pricingconfigs/:pricingConfigId Yes
List listPricingConfigs /v1/pricingconfigs Yes

Subscription Default APIs

Operation API Name Route Explicitly Set
Create createSubscription /v1/subscriptions Auto
Update cancelSubscription /v1/subscriptions/:subscriptionId/cancel Auto
Delete none - Auto
Get getSubscription /v1/subscriptions/:subscriptionId Yes
List listSubscriptions /v1/subscriptions Yes

Sys_subscriptionPayment Default APIs

Operation API Name Route Explicitly Set
Create createSubscriptionPayment /v1/subscriptionpayment Auto
Update updateSubscriptionPayment /v1/subscriptionpayment/:sys_subscriptionPaymentId Auto
Delete deleteSubscriptionPayment /v1/subscriptionpayment/:sys_subscriptionPaymentId Auto
Get getSubscriptionPayment /v1/subscriptionpayment/:sys_subscriptionPaymentId Auto
List listSubscriptionPayments /v1/subscriptionpayments Auto

Sys_paymentCustomer Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getPaymentCustomerByUserId /v1/paymentcustomers/:userId Auto
List listPaymentCustomers /v1/paymentcustomers Auto

Sys_paymentMethod Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List listPaymentCustomerMethods /v1/paymentcustomermethods/:userId Auto

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Cancel Subscription API

Cancel the authenticated user’s active subscription. Sets the subscription status to cancelled and records the cancellation timestamp.

API Frontend Description By The Backend Architect

Call this endpoint when the user confirms they want to cancel their subscription. After successful cancellation, inform the user that they will lose access to AI features. The response contains the updated subscription record with status ‘cancelled’.

Rest Route

The cancelSubscription API REST controller can be triggered via the following route:

/v1/subscriptions/:subscriptionId/cancel

Rest Request Parameters

The cancelSubscription api has got 1 regular request parameter

Parameter Type Required Population
subscriptionId ID true request.params?.[“subscriptionId”]
subscriptionId : This id paremeter is used to select the required data object that will be updated

REST Request To access the api you can use the REST controller with the path POST /v1/subscriptions/:subscriptionId/cancel

  axios({
    method: 'POST',
    url: `/v1/subscriptions/${subscriptionId}/cancel`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Check Subscriptionstatus API

Machine-to-machine endpoint for other services to validate if a user has an active subscription. Returns the active subscription record if one exists, or an empty list if not.

Rest Route

The checkSubscriptionStatus API REST controller can be triggered via the following route:

/v1/check-status

Rest Request Parameters

The checkSubscriptionStatus api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.body?.[“userId”]
userId : The user ID to check subscription status for.

REST Request To access the api you can use the REST controller with the path POST /v1/check-status

  axios({
    method: 'POST',
    url: '/v1/check-status',
    data: {
            userId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscriptions",
	"method": "POST",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"subscriptions": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Pricingconfig API

[Default create API] — This is the designated default create API for the pricingConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new pricing configuration record. Admin-only operation for setting up subscription pricing.

Rest Route

The createPricingConfig API REST controller can be triggered via the following route:

/v1/pricingconfigs

Rest Request Parameters

The createPricingConfig api has got 4 regular request parameters

Parameter Type Required Population
currency String true request.body?.[“currency”]
description Text false request.body?.[“description”]
price Integer true request.body?.[“price”]
type Enum true request.body?.[“type”]
currency : Currency code for pricing (e.g., usd).
description : Human-readable description of the subscription plan.
price : Current subscription price in cents (e.g., 999 = $9.99).
type :

REST Request To access the api you can use the REST controller with the path POST /v1/pricingconfigs

  axios({
    method: 'POST',
    url: '/v1/pricingconfigs',
    data: {
            currency:"String",  
            description:"Text",  
            price:"Integer",  
            type:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "pricingConfig",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"pricingConfig": {
		"id": "ID",
		"currency": "String",
		"description": "Text",
		"price": "Integer",
		"type": "Enum",
		"type_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Pricingconfig API

[Default delete API] — This is the designated default delete API for the pricingConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a pricing configuration record. Admin-only operation.

Rest Route

The deletePricingConfig API REST controller can be triggered via the following route:

/v1/pricingconfigs/:pricingConfigId

Rest Request Parameters

The deletePricingConfig api has got 1 regular request parameter

Parameter Type Required Population
pricingConfigId ID true request.params?.[“pricingConfigId”]
pricingConfigId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/pricingconfigs/:pricingConfigId

  axios({
    method: 'DELETE',
    url: `/v1/pricingconfigs/${pricingConfigId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "pricingConfig",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"pricingConfig": {
		"id": "ID",
		"currency": "String",
		"description": "Text",
		"price": "Integer",
		"type": "Enum",
		"type_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Mysubscription API

Retrieve the currently authenticated user’s active subscription. Returns the active subscription if one exists.

API Frontend Description By The Backend Architect

Use this endpoint to check if the current user has an active subscription before allowing access to AI features. If a 404 is returned, the user does not have an active subscription and should be prompted to subscribe.

Rest Route

The getMySubscription API REST controller can be triggered via the following route:

/v1/my-subscription

Rest Request Parameters The getMySubscription api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/my-subscription

  axios({
    method: 'GET',
    url: '/v1/my-subscription',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Pricingconfig API

[Default get API] — This is the designated default get API for the pricingConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Retrieve a pricing configuration record. Accessible to all authenticated users to view current subscription pricing.

API Frontend Description By The Backend Architect

Use this endpoint to display the current subscription price to users before they initiate payment.

Rest Route

The getPricingConfig API REST controller can be triggered via the following route:

/v1/pricingconfigs/:pricingConfigId

Rest Request Parameters

The getPricingConfig api has got 1 regular request parameter

Parameter Type Required Population
pricingConfigId ID true request.params?.[“pricingConfigId”]
pricingConfigId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/pricingconfigs/:pricingConfigId

  axios({
    method: 'GET',
    url: `/v1/pricingconfigs/${pricingConfigId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "pricingConfig",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"pricingConfig": {
		"id": "ID",
		"currency": "String",
		"description": "Text",
		"price": "Integer",
		"type": "Enum",
		"type_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Subscription API

[Default get API] — This is the designated default get API for the subscription data object. Frontend generators and AI agents should use this API for standard CRUD operations. Retrieve a subscription record by its ID. Owners can view their own subscriptions; admins can view any.

Rest Route

The getSubscription API REST controller can be triggered via the following route:

/v1/subscriptions/:subscriptionId

Rest Request Parameters

The getSubscription api has got 1 regular request parameter

Parameter Type Required Population
subscriptionId ID true request.params?.[“subscriptionId”]
subscriptionId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/subscriptions/:subscriptionId

  axios({
    method: 'GET',
    url: `/v1/subscriptions/${subscriptionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Pricingconfigs API

[Default list API] — This is the designated default list API for the pricingConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all pricing configuration records. Accessible to authenticated users.

Rest Route

The listPricingConfigs API REST controller can be triggered via the following route:

/v1/pricingconfigs

Rest Request Parameters The listPricingConfigs api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/pricingconfigs

  axios({
    method: 'GET',
    url: '/v1/pricingconfigs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "pricingConfigs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"pricingConfigs": [
		{
			"id": "ID",
			"currency": "String",
			"description": "Text",
			"price": "Integer",
			"type": "Enum",
			"type_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Subscriptions API

[Default list API] — This is the designated default list API for the subscription data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all subscriptions. Admin-only endpoint for monitoring subscription records.

Rest Route

The listSubscriptions API REST controller can be triggered via the following route:

/v1/subscriptions

Rest Request Parameters

Filter Parameters

The listSubscriptions api supports 3 optional filter parameters for filtering list results:

status (Enum): Current subscription status managed by Stripe payment flow.

userId (ID): Reference to the user who owns this subscription.

paymentConfirmation (Enum): An automatic property that is used to check the confirmed status of the payment set by webhooks.

REST Request To access the api you can use the REST controller with the path GET /v1/subscriptions

  axios({
    method: 'GET',
    url: '/v1/subscriptions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // status: '<value>' // Filter by status
        // userId: '<value>' // Filter by userId
        // paymentConfirmation: '<value>' // Filter by paymentConfirmation
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscriptions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"subscriptions": [
		{
			"id": "ID",
			"activatedAt": "Date",
			"cancelledAt": "Date",
			"currency": "String",
			"pricePaid": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"statusUpdatedAt": "Date",
			"userId": "ID",
			"paymentConfirmation": "Enum",
			"paymentConfirmation_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Pricingconfig API

[Default update API] — This is the designated default update API for the pricingConfig data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update the subscription pricing configuration. Admin-only operation for adjusting price, currency, or description without code deployment.

Rest Route

The updatePricingConfig API REST controller can be triggered via the following route:

/v1/pricingconfigs/:pricingConfigId

Rest Request Parameters

The updatePricingConfig api has got 5 regular request parameters

Parameter Type Required Population
pricingConfigId ID true request.params?.[“pricingConfigId”]
currency String false request.body?.[“currency”]
description Text false request.body?.[“description”]
price Integer false request.body?.[“price”]
type Enum false request.body?.[“type”]
pricingConfigId : This id paremeter is used to select the required data object that will be updated
currency : Currency code for pricing (e.g., usd).
description : Human-readable description of the subscription plan.
price : Current subscription price in cents (e.g., 999 = $9.99).
type :

REST Request To access the api you can use the REST controller with the path PATCH /v1/pricingconfigs/:pricingConfigId

  axios({
    method: 'PATCH',
    url: `/v1/pricingconfigs/${pricingConfigId}`,
    data: {
            currency:"String",  
            description:"Text",  
            price:"Integer",  
            type:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "pricingConfig",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"pricingConfig": {
		"id": "ID",
		"currency": "String",
		"description": "Text",
		"price": "Integer",
		"type": "Enum",
		"type_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Subscription API

Rest Route

The createSubscription API REST controller can be triggered via the following route:

/v1/subscriptions

Rest Request Parameters

The createSubscription api has got 5 regular request parameters

Parameter Type Required Population
activatedAt Date false request.body?.[“activatedAt”]
cancelledAt Date false request.body?.[“cancelledAt”]
currency String true request.body?.[“currency”]
pricePaid Integer true request.body?.[“pricePaid”]
statusUpdatedAt Date false request.body?.[“statusUpdatedAt”]
activatedAt : Timestamp when the subscription was activated after successful payment.
cancelledAt : Timestamp when the subscription was cancelled by the user.
currency : Currency code for the payment (e.g., usd).
pricePaid : Amount paid in cents at the time of subscription activation.
statusUpdatedAt : Timestamp of the last status update, auto-managed by Stripe payment flow.

REST Request To access the api you can use the REST controller with the path POST /v1/subscriptions

  axios({
    method: 'POST',
    url: '/v1/subscriptions',
    data: {
            activatedAt:"Date",  
            cancelledAt:"Date",  
            currency:"String",  
            pricePaid:"Integer",  
            statusUpdatedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Do Test API

Rest Route

The test API REST controller can be triggered via the following route:

/v1/test

Rest Request Parameters The test api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/test

  axios({
    method: 'GET',
    url: '/v1/test',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "pricingConfigs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"pricingConfigs": [
		{
			"id": "ID",
			"currency": "String",
			"description": "Text",
			"price": "Integer",
			"type": "Enum",
			"type_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Subscriptionpayment API

This route is used to get the payment information by ID.

Rest Route

The getSubscriptionPayment API REST controller can be triggered via the following route:

/v1/subscriptionpayment/:sys_subscriptionPaymentId

Rest Request Parameters

The getSubscriptionPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_subscriptionPaymentId ID true request.params?.[“sys_subscriptionPaymentId”]
sys_subscriptionPaymentId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/subscriptionpayment/:sys_subscriptionPaymentId

  axios({
    method: 'GET',
    url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_subscriptionPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Subscriptionpayments API

This route is used to list all payments.

Rest Route

The listSubscriptionPayments API REST controller can be triggered via the following route:

/v1/subscriptionpayments

Rest Request Parameters

Filter Parameters

The listSubscriptionPayments api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source subscription object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path GET /v1/subscriptionpayments

  axios({
    method: 'GET',
    url: '/v1/subscriptionpayments',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayments",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_subscriptionPayments": [
		{
			"id": "ID",
			"ownerId": "ID",
			"orderId": "ID",
			"paymentId": "String",
			"paymentStatus": "String",
			"statusLiteral": "String",
			"redirectUrl": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Subscriptionpayment API

This route is used to create a new payment.

Rest Route

The createSubscriptionPayment API REST controller can be triggered via the following route:

/v1/subscriptionpayment

Rest Request Parameters

The createSubscriptionPayment api has got 5 regular request parameters

Parameter Type Required Population
orderId ID true request.body?.[“orderId”]
paymentId String true request.body?.[“paymentId”]
paymentStatus String true request.body?.[“paymentStatus”]
statusLiteral String true request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
orderId : an ID value to represent the orderId which is the ID parameter of the source subscription object
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path POST /v1/subscriptionpayment

  axios({
    method: 'POST',
    url: '/v1/subscriptionpayment',
    data: {
            orderId:"ID",  
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayment",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_subscriptionPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Subscriptionpayment API

This route is used to update an existing payment.

Rest Route

The updateSubscriptionPayment API REST controller can be triggered via the following route:

/v1/subscriptionpayment/:sys_subscriptionPaymentId

Rest Request Parameters

The updateSubscriptionPayment api has got 5 regular request parameters

Parameter Type Required Population
sys_subscriptionPaymentId ID true request.params?.[“sys_subscriptionPaymentId”]
paymentId String false request.body?.[“paymentId”]
paymentStatus String false request.body?.[“paymentStatus”]
statusLiteral String false request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
sys_subscriptionPaymentId : This id paremeter is used to select the required data object that will be updated
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request To access the api you can use the REST controller with the path PATCH /v1/subscriptionpayment/:sys_subscriptionPaymentId

  axios({
    method: 'PATCH',
    url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`,
    data: {
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayment",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_subscriptionPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Subscriptionpayment API

This route is used to delete a payment.

Rest Route

The deleteSubscriptionPayment API REST controller can be triggered via the following route:

/v1/subscriptionpayment/:sys_subscriptionPaymentId

Rest Request Parameters

The deleteSubscriptionPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_subscriptionPaymentId ID true request.params?.[“sys_subscriptionPaymentId”]
sys_subscriptionPaymentId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/subscriptionpayment/:sys_subscriptionPaymentId

  axios({
    method: 'DELETE',
    url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayment",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_subscriptionPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Subscriptionpaymentbyorderid API

This route is used to get the payment information by order id.

Rest Route

The getSubscriptionPaymentByOrderId API REST controller can be triggered via the following route:

/v1/subscriptionpaymentbyorderid/:orderId

Rest Request Parameters

The getSubscriptionPaymentByOrderId api has got 1 regular request parameter

Parameter Type Required Population
orderId ID true request.params?.[“orderId”]
orderId : an ID value to represent the orderId which is the ID parameter of the source subscription object. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/subscriptionpaymentbyorderid/:orderId

  axios({
    method: 'GET',
    url: `/v1/subscriptionpaymentbyorderid/${orderId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_subscriptionPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Subscriptionpaymentbypaymentid API

This route is used to get the payment information by payment id.

Rest Route

The getSubscriptionPaymentByPaymentId API REST controller can be triggered via the following route:

/v1/subscriptionpaymentbypaymentid/:paymentId

Rest Request Parameters

The getSubscriptionPaymentByPaymentId api has got 1 regular request parameter

Parameter Type Required Population
paymentId String true request.params?.[“paymentId”]
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/subscriptionpaymentbypaymentid/:paymentId

  axios({
    method: 'GET',
    url: `/v1/subscriptionpaymentbypaymentid/${paymentId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_subscriptionPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_subscriptionPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Start Subscriptionpayment API

Start payment for subscription

Rest Route

The startSubscriptionPayment API REST controller can be triggered via the following route:

/v1/startsubscriptionpayment/:subscriptionId

Rest Request Parameters

The startSubscriptionPayment api has got 2 regular request parameters

Parameter Type Required Population
subscriptionId ID true request.params?.[“subscriptionId”]
paymentUserParams Object true request.body?.[“paymentUserParams”]
subscriptionId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId.

REST Request To access the api you can use the REST controller with the path PATCH /v1/startsubscriptionpayment/:subscriptionId

  axios({
    method: 'PATCH',
    url: `/v1/startsubscriptionpayment/${subscriptionId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Refresh Subscriptionpayment API

Refresh payment info for subscription from Stripe

Rest Route

The refreshSubscriptionPayment API REST controller can be triggered via the following route:

/v1/refreshsubscriptionpayment/:subscriptionId

Rest Request Parameters

The refreshSubscriptionPayment api has got 2 regular request parameters

Parameter Type Required Population
subscriptionId ID true request.params?.[“subscriptionId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
subscriptionId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to refresh a stripe payment process

REST Request To access the api you can use the REST controller with the path PATCH /v1/refreshsubscriptionpayment/:subscriptionId

  axios({
    method: 'PATCH',
    url: `/v1/refreshsubscriptionpayment/${subscriptionId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Callback Subscriptionpayment API

Refresh payment values by gateway webhook call for subscription

Rest Route

The callbackSubscriptionPayment API REST controller can be triggered via the following route:

/v1/callbacksubscriptionpayment

Rest Request Parameters

The callbackSubscriptionPayment api has got 1 regular request parameter

Parameter Type Required Population
subscriptionId ID false request.body?.[“subscriptionId”]
subscriptionId : The order id parameter that will be read from webhook callback params

REST Request To access the api you can use the REST controller with the path POST /v1/callbacksubscriptionpayment

  axios({
    method: 'POST',
    url: '/v1/callbacksubscriptionpayment',
    data: {
            subscriptionId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymentcustomerbyuserid API

This route is used to get the payment customer information by user id.

Rest Route

The getPaymentCustomerByUserId API REST controller can be triggered via the following route:

/v1/paymentcustomers/:userId

Rest Request Parameters

The getPaymentCustomerByUserId api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers/:userId

  axios({
    method: 'GET',
    url: `/v1/paymentcustomers/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomer",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_paymentCustomer": {
		"id": "ID",
		"userId": "ID",
		"customerId": "String",
		"platform": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Paymentcustomers API

This route is used to list all payment customers.

Rest Route

The listPaymentCustomers API REST controller can be triggered via the following route:

/v1/paymentcustomers

Rest Request Parameters

Filter Parameters

The listPaymentCustomers api supports 3 optional filter parameters for filtering list results:

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers

  axios({
    method: 'GET',
    url: '/v1/paymentcustomers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // platform: '<value>' // Filter by platform
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentCustomers": [
		{
			"id": "ID",
			"userId": "ID",
			"customerId": "String",
			"platform": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Paymentcustomermethods API

This route is used to list all payment customer methods.

Rest Route

The listPaymentCustomerMethods API REST controller can be triggered via the following route:

/v1/paymentcustomermethods/:userId

Rest Request Parameters

The listPaymentCustomerMethods api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : An ID value to represent the user who owns the payment method. The parameter is used to query data.

Filter Parameters

The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomermethods/:userId

  axios({
    method: 'GET',
    url: `/v1/paymentcustomermethods/${userId}`,
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - Subscription Service Subscription Payment Flow

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

Stripe Payment Flow For Subscription

Subscription is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database.

The ID of this data object—referenced as subscriptionId in the general business logic—will be used as the orderId in the payment flow.

Accessing the service API for the payment flow API

The Aifitapp application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders. To access the related APIs, use the base URL of the subscription service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment.

For the subscription service, the base URLs are:

Creating the Subscription

While creating the subscription instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of subscription). The payment flow begins after the object is created.

Because of the data object’s Stripe order settings, the payment flow is aware of the following fields, references, and their purposes:

Before Payment Flow Starts

It is assumed that the frontend provides a “Pay” or “Checkout” button that initiates the payment flow. The following steps occur after the user clicks this button.
Note that an subscription instance must already exist to represent the order being paid, with its initial status set.

A Stripe payment flow can be implemented in several ways, but the best practice is to use a PaymentIntent and manage it jointly from the backend and frontend.
A PaymentIntent represents the intent to collect payment for a given order (or any payable entity).
In the Aifitapp application, the PaymentIntent is created in the backend, while the PaymentMethod (the user’s stored card information) is created in the frontend.
Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference.

The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to add or remove payment methods.
The user must select a Payment Method before starting the payment flow.

Listing the Payment Methods for the User

To list the payment methods of the currently logged-in user, call the following system API (unversioned):

GET /payment-methods/list

This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope.

const response = await fetch("$serviceUrl/payment-methods/list", {
  method: "GET",
  headers: { "Content-Type": "application/json" },
});

Example response:

[
  {
    "id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01",
    "paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8",
    "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
    "customerId": "cus_TNgWUw5QkmUPLa",
    "cardHolderName": "John Doe",
    "cardHolderZip": "34662",
    "platform": "stripe",
    "cardInfo": {
      "brand": "visa",
      "last4": "4242",
      "checks": {
        "cvc_check": "pass",
        "address_postal_code_check": "pass"
      },
      "funding": "credit",
      "exp_month": 11,
      "exp_year": 2033
    },
    "isActive": true,
    "createdAt": "2025-11-07T19:16:38.469Z",
    "updatedAt": "2025-11-07T19:16:38.469Z",
    "_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2"
  }
]

In each payment method object, the following fields are useful for displaying to the user:

for (const method of paymentMethods) {
  const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons
  const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow
  const cardHolderName = method.cardHolderName; // show in list
  const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number
  const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date
  const id = method.id; // internal DB record ID, used for deletion
  const customerId = method.customerId; // Stripe customer reference
}

If the list is empty, prompt the user to add a new payment method.

Creating a Payment Method

The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled entirely through Stripe.js on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse.

Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns.

To initialize Stripe on the frontend, include your public key:

<script src="https://js.stripe.com/v3/?advancedFraudSignals=false"></script>
const stripe = Stripe("pk_test_51POkqt4..................");
const elements = stripe.elements();

const cardNumberElement = elements.create("cardNumber", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardNumberElement.mount("#card-number-element");

const cardExpiryElement = elements.create("cardExpiry", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardExpiryElement.mount("#card-expiry-element");

const cardCvcElement = elements.create("cardCvc", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardCvcElement.mount("#card-cvc-element");

// Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure).

You can dynamically show the card brand while typing:

cardNumberElement.on("change", (event) => {
  const cardBrand = event.brand;
  const cardNumberDiv = document.getElementById("card-number-element");
  cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand);
});

Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code.

const { paymentMethod, error } = await stripe.createPaymentMethod({
  type: "card",
  card: cardNumberElement,
  billing_details: {
    name: cardholderName.value,
    address: { postal_code: cardholderZip.value },
  },
});

When a paymentMethod is successfully created, send its ID to your backend to attach it to the logged-in user’s account.

Use the system API (unversioned):

POST /payment-methods/add

Example:

const response = await fetch("$serviceUrl/payment-methods/add", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ paymentMethodId: paymentMethod.id }),
});

When addPaymentMethod is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use.

Example response:

{
  "isActive": true,
  "cardHolderName": "John Doe",
  "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
  "customerId": "cus_TNgWUw5QkmUPLa",
  "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
  "platform": "stripe",
  "cardHolderZip": "34662",
  "cardInfo": {
    "brand": "visa",
    "last4": "4242",
    "funding": "credit",
    "exp_month": 11,
    "exp_year": 2033
  },
  "id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf",
  "createdAt": "2025-11-07T20:16:55.451Z",
  "updatedAt": "2025-11-07T20:16:55.451Z"
}

You can append this new entry directly to the UI list or refresh the list using the listPaymentMethods API.

Deleting a Payment Method

To remove a saved payment method from the current user’s account, call the system API (unversioned):

DELETE /payment-methods/delete/:paymentMethodId

Example:

await fetch(
  `$serviceUrl/payment-methods/delete/${paymentMethodId}`,
  {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  }
);

Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object

The payment flow is initiated in the backend through the startSubscriptionPayment API.
This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend forces the user to select a payment method before initiating the payment.

The startSubscriptionPayment API is a versioned Business Logic API and follows the same structure as other business APIs.

In the Aifitapp application, the payment flow starts by creating a Stripe PaymentIntent and confirming it in a single step within the backend.
In a typical (“happy”) path, when the startSubscriptionPayment API is called, the response will include a successful or failed PaymentIntent result inside the paymentResult object, along with the subscription object.

However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately.
In such cases, control should return to a frontend page to allow the user to finish the process.
To enable this, a return_url must be provided during the PaymentIntent creation step.

Although technically optional, it is strongly recommended to include a return_url.
This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction.
The return_url must be a frontend URL.

The paymentUserParams parameter of the startSubscriptionPayment API contains the data necessary to create the Stripe PaymentIntent.

Call the API as follows:

const response = await fetch(
  `$serviceUrl/v1/startsubscriptionpayment/${orderId}`,
  {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      paymentUserParams: {
        paymentMethodId,
        return_url: `${yourFrontendReturnUrl}`,
      },
    }),
  }
);

The API response will contain a paymentResult object. If an error occurs, it will begin with { "result": "ERR" }. Otherwise, it will include the PaymentIntent information:

{
  "paymentResult": {
    "success": true,
    "paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
    "paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
      "clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg",
      "publicKey": "pk_test_51POkqWP5uU",
      "status": "succeeded"
    },
    "statusLiteral": "success",
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10",
    "metadata": {
      "order": "Purchase-Purchase-order",
      "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
      "checkoutName": "babilOrder"
    },
    "paymentUserParams": {
      "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
      "return_url": "${yourFrontendReturnUrl}"
    }
  }
}

Start Subscriptionpayment API

Start payment for subscription

Rest Route

The startSubscriptionPayment API REST controller can be triggered via the following route:

/v1/startsubscriptionpayment/:subscriptionId

Rest Request Parameters

The startSubscriptionPayment api has got 2 regular request parameters

Parameter Type Required Population
subscriptionId ID true request.params?.[“subscriptionId”]
paymentUserParams Object true request.body?.[“paymentUserParams”]
subscriptionId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId.

REST Request To access the api you can use the REST controller with the path PATCH /v1/startsubscriptionpayment/:subscriptionId

  axios({
    method: 'PATCH',
    url: `/v1/startsubscriptionpayment/${subscriptionId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "subscription",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"subscription": {
		"id": "ID",
		"activatedAt": "Date",
		"cancelledAt": "Date",
		"currency": "String",
		"pricePaid": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"statusUpdatedAt": "Date",
		"userId": "ID",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Analyzing the API Response

After calling the startSubscriptionPayment API, the most common expected outcome is a confirmed and completed payment. However, several alternate cases should be handled on the frontend.

System Error Case

The API may return a classic service-level error (unrelated to payment). Check the HTTP status code of the response. It should be 200 or 201. Any 400, 401, 403, or 404 indicates a system error.

{
  "result": "ERR",
  "status": 404,
  "message": "Record not found",
  "date": "2025-11-08T00:57:54.820Z"
}

Handle system errors on the payment page (show a retry option). Do not navigate to the result page.

Payment Error Case

The API performs both database operations and the Stripe payment operation. If the payment fails but the service logic succeeds, the API may still return a 200 OK status, with the failure recorded in the paymentResult.

In this case, show an error message and allow the user to retry.

{
  "status": "OK",
  "statusCode": "200",
  "subscription": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "failed"
  },
  "paymentResult": {
    "result": "ERR",
    "status": 500,
    "message": "Stripe error message: Your card number is incorrect.",
    "errCode": "invalid_number",
    "date": "2025-11-08T00:57:54.820Z"
  }
}

Payment errors should be handled on the payment page (retry option). Do not go to the result page.


Happy Case

When both the service and payment result succeed, this is considered the happy path. In this case, use the subscription and paymentResult objects in the response to display a success message to the user.

amount and description values are included to help you show payment details on the result page.

{
  "status": "OK",
  "statusCode": "200",
  "order": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "paid"
  },
  "paymentResult": {
    "success": true,
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "status": "succeeded"
    },
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10"
  }
}

To verify success:

if (paymentResult.paymentIntentInfo.status === "succeeded") {
  // Redirect to result page
}

Note: A successful result does not trigger fulfillment immediately. Fulfillment begins only after the Stripe webhook updates the database. It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page.

Handle the happy case in the result page by sending the subscriptionId and the payment intent secret.

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

Edge Cases

Although startSubscriptionPayment is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required.

You must handle these cases in both the payment page and the result page, because some next actions are available immediately, while others occur only after a redirect.

If the paymentIntentInfo.status equals "requires_action", handle it using Stripe.js as shown below:

if (paymentResult.paymentIntentInfo.status === "requires_action") {
  await runNextAction(
    paymentResult.paymentIntentInfo.clientSecret,
    paymentResult.paymentIntentInfo.publicKey
  );
}

Helper function:

async function runNextAction(clientSecret, publicKey) {
  const stripe = Stripe(publicKey);
  const { error } = await stripe.handleNextAction({ clientSecret });
  if (error) {
    console.log("next_action error:", error);
    showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500");
    throw new Error(error.message);
  }
}

After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page.

const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

if (paymentIntent.status === "succeeded") {
  showToast("Payment successful!", "fa-circle-check text-green-500");
} else if (paymentIntent.status === "processing") {
  showToast("Payment is processing…", "fa-circle-info text-blue-500");
} else if (paymentIntent.status === "requires_payment_method") {
  showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500");
}

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

The Result Page

The payment result page should handle the following steps:

  1. Read orderId and payment_intent_client_secret from the query parameters.
  2. Retrieve the PaymentIntent from Stripe and check its status.
  3. If required, handle any next_action and re-fetch the PaymentIntent.
  4. If the status is "succeeded", display a clear visual confirmation.
  5. Fetch the subscription instance from the backend to display any additional order or fulfillment details.

Note that paymentIntent status only gives information about the Stripe side. The subscription instance in the service should also ve updated to start the fulfillment. In most cases, the startsubscriptionPayment api updates the status of the order using the response of the paymentIntent confirmation, but as stated above in some cases this update can be done only when the webhook executes. So in teh result page always get the final payment status in the `subscription.

To ensure that service i To fetch the subscription instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the subscription instance.

if (subscription.paymentConfirmation == "canceled") {
  // the payment is canceled, user can be informed that they should try again
} if (subscription.paymentConfirmation == "paid") {
  // service knows that payment is done, user can be informed that fullfillment started
} else {
  // it may be pending, processing
  // Fetch the object again until a canceled or paid status
}

Payment Flow via MCP (AI Chat Integration)

The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The subscription service exposes an initiatePayment MCP tool that the AI can call when the user wants to pay for an order.

How initiatePayment Works in MCP

  1. User asks to pay — e.g., “I want to pay for my order”
  2. AI calls initiatePayment MCP tool with orderId (and orderType if multiple order types exist)
  3. Tool validates the order exists, is payable, and the user is authorized
  4. Tool returns __frontendAction with type: "payment" — this is NOT a direct payment execution
  5. Frontend chat UI renders a PaymentActionCard with a “Pay Now” button
  6. User clicks “Pay Now” — the frontend opens a payment modal with CheckoutForm
  7. Standard Stripe flow proceeds (payment method selection, 3DS handling, etc.)

Frontend Action Response Format

The initiatePayment MCP tool returns:

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "subscription",
    "serviceName": "subscription",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order description"
  },
  "message": "Payment is ready. Click the button below to proceed."
}

MCP Client Architecture

The frontend communicates with MCP tools through the MCP BFF (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides:

The PaymentActionCard component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface.


AIFITAPP

FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - AgentHub Service

This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of agentHub

Service Access

AgentHub service management is handled through service specific base urls.

AgentHub service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the agentHub service, the base URLs are:

Scope

AgentHub Service Description

AI Agent Hub

AgentHub service provides apis and business logic for following data objects in aifitapp application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

sys_agentOverride Data Object: Runtime overrides for design-time agents. Null fields use the design default.

sys_agentExecution Data Object: Agent execution log. Records each agent invocation with input, output, and performance metrics.

sys_toolCatalog Data Object: Cached tool catalog discovered from project services. Refreshed periodically.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Sys_agentOverride Data Object

Runtime overrides for design-time agents. Null fields use the design default.

Sys_agentOverride Data Object Properties

Sys_agentOverride data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
agentName String Yes No Design-time agent name this override applies to.
provider String No No Override AI provider (e.g., openai, anthropic).
model String No No Override model name.
systemPrompt Text No No Override system prompt.
temperature Double No No Override temperature (0-2).
maxTokens Integer No No Override max tokens.
responseFormat String No No Override response format (text/json).
selectedTools Object No No Array of tool names from the catalog that this agent can use.
guardrails Object No No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes No Enable or disable this agent.
updatedBy ID No No User who last updated this override.

Sys_agentExecution Data Object

Agent execution log. Records each agent invocation with input, output, and performance metrics.

Sys_agentExecution Data Object Properties

Sys_agentExecution data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
agentName String Yes No Agent that was executed.
agentType Enum Yes No Whether this was a design-time or dynamic agent.
source Enum Yes No How the agent was triggered.
userId ID No No User who triggered the execution.
input Object No No Request input (truncated for large payloads).
output Object No No Response output (truncated for large payloads).
toolCalls Integer No No Number of tool calls made during execution.
tokenUsage Object No No Token usage: { prompt, completion, total }.
durationMs Integer No No Execution time in milliseconds.
status Enum Yes No Execution status.
error Text No No Error message if execution failed.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Filter Properties

agentName agentType source userId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_toolCatalog Data Object

Cached tool catalog discovered from project services. Refreshed periodically.

Sys_toolCatalog Data Object Properties

Sys_toolCatalog data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
toolName String Yes No Full tool name (e.g., service:apiName).
serviceName String Yes No Source service name.
description Text No No Tool description.
parameters Object No No JSON Schema of tool parameters.
lastRefreshed Date No No When this tool was last discovered/refreshed.

Filter Properties

serviceName

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

Sys_agentOverride Default APIs

Operation API Name Route Explicitly Set
Create createAgentOverride /v1/agentoverride Yes
Update updateAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
Delete deleteAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
Get getAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
List listAgentOverrides /v1/agentoverrides Yes

Sys_agentExecution Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getAgentExecution /v1/agentexecution/:sys_agentExecutionId Yes
List listAgentExecutions /v1/agentexecutions Yes

Sys_toolCatalog Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getToolCatalogEntry /v1/toolcatalogentry/:sys_toolCatalogId Yes
List listToolCatalog /v1/toolcatalog Yes

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Get Agentoverride API

[Default get API] — This is the designated default get API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The getAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'GET',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentoverrides API

[Default list API] — This is the designated default list API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentOverrides API REST controller can be triggered via the following route:

/v1/agentoverrides

Rest Request Parameters The listAgentOverrides api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverrides

  axios({
    method: 'GET',
    url: '/v1/agentoverrides',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Agentoverride API

[Default update API] — This is the designated default update API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The updateAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The updateAgentOverride api has got 10 regular request parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be updated
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled : Enable or disable this agent.

REST Request To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Create Agentoverride API

[Default create API] — This is the designated default create API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The createAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride

Rest Request Parameters

The createAgentOverride api has got 9 regular request parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]
agentName : Design-time agent name this override applies to.
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.

REST Request To access the api you can use the REST controller with the path POST /v1/agentoverride

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Agentoverride API

[Default delete API] — This is the designated default delete API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The deleteAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The deleteAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'DELETE',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Toolcatalog API

[Default list API] — This is the designated default list API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listToolCatalog API REST controller can be triggered via the following route:

/v1/toolcatalog

Rest Request Parameters

Filter Parameters

The listToolCatalog api supports 1 optional filter parameter for filtering list results:

serviceName (String): Source service name.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalog

  axios({
    method: 'GET',
    url: '/v1/toolcatalog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // serviceName: '<value>' // Filter by serviceName
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_toolCatalogs": [
		{
			"id": "ID",
			"toolName": "String",
			"serviceName": "String",
			"description": "Text",
			"parameters": "Object",
			"lastRefreshed": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Toolcatalogentry API

[Default get API] — This is the designated default get API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getToolCatalogEntry API REST controller can be triggered via the following route:

/v1/toolcatalogentry/:sys_toolCatalogId

Rest Request Parameters

The getToolCatalogEntry api has got 1 regular request parameter

Parameter Type Required Population
sys_toolCatalogId ID true request.params?.[“sys_toolCatalogId”]
sys_toolCatalogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalogentry/:sys_toolCatalogId

  axios({
    method: 'GET',
    url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentexecutions API

[Default list API] — This is the designated default list API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentExecutions API REST controller can be triggered via the following route:

/v1/agentexecutions

Rest Request Parameters

Filter Parameters

The listAgentExecutions api supports 5 optional filter parameters for filtering list results:

agentName (String): Agent that was executed.

agentType (Enum): Whether this was a design-time or dynamic agent.

source (Enum): How the agent was triggered.

userId (ID): User who triggered the execution.

status (Enum): Execution status.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecutions

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Agentexecution API

[Default get API] — This is the designated default get API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentExecution API REST controller can be triggered via the following route:

/v1/agentexecution/:sys_agentExecutionId

Rest Request Parameters

The getAgentExecution api has got 1 regular request parameter

Parameter Type Required Population
sys_agentExecutionId ID true request.params?.[“sys_agentExecutionId”]
sys_agentExecutionId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecution/:sys_agentExecutionId

  axios({
    method: 'GET',
    url: `/v1/agentexecution/${sys_agentExecutionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.



Related Documentation

For more detailed information, refer to:


Generated by Mindbricks Genesis Engine