# Sahibinden Clone – Classifieds & Marketplace Platform - REST API Reference
> Complete REST API documentation for all services in Sahibinden Clone – Classifieds & Marketplace Platform
This document provides comprehensive REST API documentation for all services. Use this reference to understand available endpoints, request/response formats, and authentication requirements.
---
## Table of Contents
- [Introduction](#introduction)
- [AdminModeration Service REST API](#adminmoderation-service-rest-api-guide)
- [CategoryLocation Service REST API](#categorylocation-service-rest-api-guide)
- [Conversation Service REST API](#conversation-service-rest-api-guide)
- [Favorite Service REST API](#favorite-service-rest-api-guide)
- [Listing Service REST API](#listing-service-rest-api-guide)
- [ListingImage Service REST API](#listingimage-service-rest-api-guide)
- [Payment Service REST API](#payment-service-rest-api-guide)
- [Auth Service REST API](#auth-service-rest-api-guide)
- [Bff Service REST API](#bff-service-rest-api-guide)
- [Notification Service REST API](#notification-service-rest-api-guide)
---
## Introduction
# Sahibinden Clone – Classifieds & Marketplace Platform
Version : 1.0.13
clonesahibinden is a scalable classified ads platform where users can register, list items across multiple categories such as vehicles, real estate, goods, and jobs, interact via messaging, and manage their listings with support for premium ad features and role-based moderation. The platform offers advanced category management, powerful search and filtering, and a comprehensive admin and moderation dashboard.
## How to Use Project Documents
The `Clonesahibinden` 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://clonesahibinden.prw.mindbricks.com/auth-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/auth-api` |
| **Production** | `https://clonesahibinden.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
* **Preview APIs** become accessible after a project is previewed inside the Mindbricks platform. These are ideal for development and testing.
* **Staging** and **Production** APIs are only accessible after the project is deployed to cloud environments provisioned via Mindbricks.
* In some cases, the project owner may choose to deploy services on their **own infrastructure**. In such scenarios, the service base URLs will be **custom** and should be communicated manually by the project owner to developers or AI agents.
> **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 `Clonesahibinden` 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:
* Register and authenticate users (login)
* Manage users, roles, and permissions
* Handle user groups (if defined)
* Support multi-tenancy logic (if configured)
* Perform Policy-Based Access Control (PBAC), if activated by the architect
### Auth Service Documentation
Use the following resources to understand and integrate the Auth Service:
* **REST API Guide** – ideal for frontend and direct HTTP usage
[Auth REST API Guide](/document/docs/auth-service/rest-api-guide.html)
* **Event Guide** – helpful for event-driven or cross-service integrations
[Auth Event Guide](/document/docs/auth-service/event-guide.html)
* **Service Design Document** – overall structure, patterns, and logic
[Auth Service Design](/document/docs/auth-service/service-design.html)
> **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
* **Elasticsearch Replicas for Fast Queries:**
Each data object managed by a business service is automatically replicated as an **Elasticsearch index**, making it accessible for fast, frontend-oriented queries through the BFF.
* **Cross-Service Data Aggregation:**
The BFF offers an **aggregation layer** capable of combining data across multiple services, enabling complex filters, searches, and unified views of related data.
* **Read-Only by Design:**
The BFF service is **strictly read-only**. All create, update, or delete operations must be performed through the relevant business services, or via event-driven sagas if designed.
### BFF Service Documentation
* **REST API Guide** – querying aggregated and indexed data
[BFF REST API Guide](/document/docs/bff-service/rest-api-guide.html)
* **Event Guide** – syncing strategies across replicas
[BFF Event Guide](/document/docs/bff-service/event-guide.html)
* **Service Design** – aggregation patterns and index structures
[BFF Service Design](/document/docs/bff-service/service-design.html)
> **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 `Sahibinden Clone – Classifieds & Marketplace Platform` 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:
* Handle the **state and operations of domain data**
* Offer **Create, Update, Delete** operations over owned entities
* Serve **direct data queries** (`get`, `list`) for their own objects when needed
For advanced query needs across multiple services or aggregated views, prefer using the [BFF service](#using-the-bff-backend-for-frontend-service).
### Available Business Services
### adminModeration Service
**Description:** Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.
**Documentation:**
* [REST API Guide](/document/docs/adminModeration-service/rest-api-guide.html)
* [Event Guide](/document/docs/adminModeration-service/event-guide.html)
* [Service Design](/document/docs/adminModeration-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/adminmoderation-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/adminmoderation-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/adminmoderation-api` |
### categoryLocation Service
**Description:** Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.
**Documentation:**
* [REST API Guide](/document/docs/categoryLocation-service/rest-api-guide.html)
* [Event Guide](/document/docs/categoryLocation-service/event-guide.html)
* [Service Design](/document/docs/categoryLocation-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/categorylocation-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/categorylocation-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/categorylocation-api` |
### conversation Service
**Description:** Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.
**Documentation:**
* [REST API Guide](/document/docs/conversation-service/rest-api-guide.html)
* [Event Guide](/document/docs/conversation-service/event-guide.html)
* [Service Design](/document/docs/conversation-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/conversation-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/conversation-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/conversation-api` |
### favorite Service
**Description:** Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.
**Documentation:**
* [REST API Guide](/document/docs/favorite-service/rest-api-guide.html)
* [Event Guide](/document/docs/favorite-service/event-guide.html)
* [Service Design](/document/docs/favorite-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/favorite-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/favorite-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/favorite-api` |
### listing Service
**Description:** Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.
**Documentation:**
* [REST API Guide](/document/docs/listing-service/rest-api-guide.html)
* [Event Guide](/document/docs/listing-service/event-guide.html)
* [Service Design](/document/docs/listing-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/listing-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/listing-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/listing-api` |
### listingImage Service
**Description:** Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.
**Documentation:**
* [REST API Guide](/document/docs/listingImage-service/rest-api-guide.html)
* [Event Guide](/document/docs/listingImage-service/event-guide.html)
* [Service Design](/document/docs/listingImage-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/listingimage-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/listingimage-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/listingimage-api` |
### payment Service
**Description:** Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.
**Documentation:**
* [REST API Guide](/document/docs/payment-service/rest-api-guide.html)
* [Event Guide](/document/docs/payment-service/event-guide.html)
* [Service Design](/document/docs/payment-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://clonesahibinden.prw.mindbricks.com/payment-api` |
| **Staging** | `https://clonesahibinden-stage.mindbricks.co/payment-api` |
| **Production** | `https://clonesahibinden.mindbricks.co/payment-api` |
## Conclusion
This documentation set provides a comprehensive guide for understanding and consuming the `Sahibinden Clone – Classifieds & Marketplace Platform` 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:
* Start with the **Auth Service** to manage users, roles, sessions, and permissions.
* Use the **BFF Service** for optimized, read-only data queries and cross-service aggregation.
* Refer to the **Business Services** when you need to manage domain-specific data or perform direct CRUD operations.
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.
---
## Service API Documentation
# REST API GUIDE
## clonesahibinden-adminmoderation-service
**Version:** `1.0.1`
Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the AdminModeration Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AdminModeration Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the AdminModeration Service via HTTP requests for purposes such as creating, updating, deleting and querying AdminModeration objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the AdminModeration Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the AdminModeration service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the AdminModeration service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the AdminModeration service.
This service is configured to listen for HTTP requests on port `3009`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/adminmoderation-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/adminmoderation-api`
* **Production:** `https://clonesahibinden.mindbricks.co/adminmoderation-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the AdminModeration service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `AdminModeration` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `AdminModeration` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `AdminModeration` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
AdminModeration service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### AdminActionLog resource
*Resource Definition* : Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.
*AdminActionLog Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **action** | String | | | *Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)* |
| **actionAt** | Date | | | *Date and time the action was performed, UTC.* |
| **adminUserId** | ID | | | *User ID of admin/moderator who initiated the action (refers to auth:user).* |
| **metadata** | Object | | | *Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)* |
| **reason** | String | | | *Reason for action (required on denial, ban; optional for others).* |
| **targetId** | ID | | | *ID of the affected resource/entity (listing, user, message, etc.)* |
| **targetType** | String | | | *Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)* |
## Business Api
### `Create Adminactionlog` API
Appends a new immutable moderation/admin audit log entry for every critical action (listing, user, message, role, etc). Used both by internal workflows and explicit admin APIs.
**API Frontend Description By The Backend Architect**
Frontends should not invoke directly; log entries are created automatically via moderation/admin actions (approve/deny/ban/etc). Accepts adminUserId (from session), action, targetType, targetId, reason (required on denial/ban), metadata (optional), actionAt (server time, auto).
**Rest Route**
The `createAdminActionLog` API REST controller can be triggered via the following route:
`/v1/adminactionlogs`
**Rest Request Parameters**
The `createAdminActionLog` api has got 5 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| action | String | true | request.body?.["action"] |
| metadata | Object | false | request.body?.["metadata"] |
| reason | String | false | request.body?.["reason"] |
| targetId | ID | true | request.body?.["targetId"] |
| targetType | String | true | request.body?.["targetType"] |
**action** : Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
**metadata** : Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
**reason** : Reason for action (required on denial, ban; optional for others).
**targetId** : ID of the affected resource/entity (listing, user, message, etc.)
**targetType** : Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/adminactionlogs**
```js
axios({
method: 'POST',
url: '/v1/adminactionlogs',
data: {
action:"String",
metadata:"Object",
reason:"String",
targetId:"ID",
targetType:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "adminActionLog",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"adminActionLog": {
"id": "ID",
"action": "String",
"actionAt": "Date",
"adminUserId": "ID",
"metadata": "Object",
"reason": "String",
"targetId": "ID",
"targetType": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Adminactionlog` API
Retrieve a single moderation/admin action log entry by ID. Used for detailed audit review or appeals.
**API Frontend Description By The Backend Architect**
Admin/staff frontend can use to show full details of an individual moderation event for investigation, override, or dispute resolution. Only available to admin/moderator roles.
**Rest Route**
The `getAdminActionLog` API REST controller can be triggered via the following route:
`/v1/adminactionlogs/:adminActionLogId`
**Rest Request Parameters**
The `getAdminActionLog` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| adminActionLogId | ID | true | request.params?.["adminActionLogId"] |
**adminActionLogId** : 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/adminactionlogs/:adminActionLogId**
```js
axios({
method: 'GET',
url: `/v1/adminactionlogs/${adminActionLogId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "adminActionLog",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"adminActionLog": {
"adminUser": {
"email": "String",
"fullname": "String",
"roleId": "String"
},
"isActive": true
}
}
```
### `List Adminactionlogs` API
List all moderation/admin action logs with full filter/sort for dashboard or traceability/audit needs. Supports filtering by action, targetType, targetId, adminUserId, actionAt.
**API Frontend Description By The Backend Architect**
Feeds moderation dashboard. Supports filtering/searching by action (approve, deny, ban, etc), affected entity, targetId, admin/mod, time range. Pagination enabled for large result sets. Intended for admin/mod use only.
**Rest Route**
The `listAdminActionLogs` API REST controller can be triggered via the following route:
`/v1/adminactionlogs`
**Rest Request Parameters**
The `listAdminActionLogs` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/adminactionlogs**
```js
axios({
method: 'GET',
url: '/v1/adminactionlogs',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "adminActionLogs",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"adminActionLogs": [
{
"adminUser": [
{
"email": "String",
"fullname": "String",
"roleId": "String"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `_fetch Listadminactionlog` API
System API to fetch list of adminActionLog records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListAdminActionLog` API REST controller can be triggered via the following route:
`/v1/_fetchlistadminactionlog`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListAdminActionLog` api supports 5 optional filter parameters for filtering list results:
**action** (`String`): Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
- Single (partial match, case-insensitive): `?action=`
- Multiple: `?action=&action=`
- Null: `?action=null`
**actionAt** (`Date`): Date and time the action was performed, UTC.
- Single date: `?actionAt=2024-01-15`
- Multiple dates: `?actionAt=2024-01-15&actionAt=2024-01-20`
- Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-`
- Null: `?actionAt=null`
**adminUserId** (`ID`): User ID of admin/moderator who initiated the action (refers to auth:user).
- Single: `?adminUserId=`
- Multiple: `?adminUserId=&adminUserId=`
- Null: `?adminUserId=null`
**targetId** (`ID`): ID of the affected resource/entity (listing, user, message, etc.)
- Single: `?targetId=`
- Multiple: `?targetId=&targetId=`
- Null: `?targetId=null`
**targetType** (`String`): Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)
- Single (partial match, case-insensitive): `?targetType=`
- Multiple: `?targetType=&targetType=`
- Null: `?targetType=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistadminactionlog**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistadminactionlog',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// action: '' // Filter by action
// actionAt: '' // Filter by actionAt
// adminUserId: '' // Filter by adminUserId
// targetId: '' // Filter by targetId
// targetType: '' // Filter by targetType
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "adminActionLogs",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"adminActionLogs": [
{
"id": "ID",
"action": "String",
"actionAt": "Date",
"adminUserId": "ID",
"metadata": "Object",
"reason": "String",
"targetId": "ID",
"targetType": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"adminUser": [
{
"fullname": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-categorylocation-service
**Version:** `1.0.1`
Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the CategoryLocation Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our CategoryLocation Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the CategoryLocation Service via HTTP requests for purposes such as creating, updating, deleting and querying CategoryLocation objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the CategoryLocation Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the CategoryLocation service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the CategoryLocation service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the CategoryLocation service.
This service is configured to listen for HTTP requests on port `3001`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/categorylocation-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/categorylocation-api`
* **Production:** `https://clonesahibinden.mindbricks.co/categorylocation-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the CategoryLocation service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `CategoryLocation` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `CategoryLocation` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `CategoryLocation` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
CategoryLocation service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### Category resource
*Resource Definition* : Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.
*Category Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **description** | Text | | | *Optional extended description for category (for admin display or frontend info).* |
| **icon** | String | | | *Icon identifier (string or URL to a static asset) for this category.* |
| **name** | String | | | *Category name, e.g. 'Automobiles', 'Electronics'.* |
| **parentCategoryId** | ID | | | *References parent category for hierarchy. Top-level (root) categories have null.* |
| **slug** | String | | | *SEO-friendly unique slug for URL and search. Lowercase, hyphens only.* |
| **sortOrder** | Integer | | | *Order for listing within siblings. Unique per parent.* |
### Location resource
*Resource Definition* : Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.
*Location Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **city** | String | | | *City name.* |
| **country** | String | | | *Country name (typically 'Turkey').* |
| **district** | String | | | *District name, for fine-grained search.* |
| **latitude** | Double | | | *Latitude for map/search.* |
| **longitude** | Double | | | *Longitude for map/search.* |
| **postalCode** | String | | | *Postal code for location.* |
## Business Api
### `Create Category` API
Creates a new category. Slug must be globally unique. Only admin may create categories.
**API Frontend Description By The Backend Architect**
Only admins can create categories. The slug field must be unique and URL-friendly. Parent selection (for nesting) is validated. Use for admin consoles and bulk management.
**Rest Route**
The `createCategory` API REST controller can be triggered via the following route:
`/v1/categories`
**Rest Request Parameters**
The `createCategory` api has got 6 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| description | Text | false | request.body?.["description"] |
| icon | String | false | request.body?.["icon"] |
| name | String | true | request.body?.["name"] |
| parentCategoryId | ID | false | request.body?.["parentCategoryId"] |
| slug | String | true | request.body?.["slug"] |
| sortOrder | Integer | true | request.body?.["sortOrder"] |
**description** : Optional extended description for category (for admin display or frontend info).
**icon** : Icon identifier (string or URL to a static asset) for this category.
**name** : Category name, e.g. 'Automobiles', 'Electronics'.
**parentCategoryId** : References parent category for hierarchy. Top-level (root) categories have null.
**slug** : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
**sortOrder** : Order for listing within siblings. Unique per parent.
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/categories**
```js
axios({
method: 'POST',
url: '/v1/categories',
data: {
description:"Text",
icon:"String",
name:"String",
parentCategoryId:"ID",
slug:"String",
sortOrder:"Integer",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "category",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"category": {
"id": "ID",
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Create Location` API
Create a new location entry (country, city, district). Only admin allowed. Composite uniqueness enforced.
**API Frontend Description By The Backend Architect**
For admin use only. Location uniqueness validated on (country, city, district). For multi-level selectors, call this repeatedly to populate country/city/district lists.
**Rest Route**
The `createLocation` API REST controller can be triggered via the following route:
`/v1/locations`
**Rest Request Parameters**
The `createLocation` api has got 6 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| city | String | true | request.body?.["city"] |
| country | String | true | request.body?.["country"] |
| district | String | true | request.body?.["district"] |
| latitude | Double | false | request.body?.["latitude"] |
| longitude | Double | false | request.body?.["longitude"] |
| postalCode | String | false | request.body?.["postalCode"] |
**city** : City name.
**country** : Country name (typically 'Turkey').
**district** : District name, for fine-grained search.
**latitude** : Latitude for map/search.
**longitude** : Longitude for map/search.
**postalCode** : Postal code for location.
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/locations**
```js
axios({
method: 'POST',
url: '/v1/locations',
data: {
city:"String",
country:"String",
district:"String",
latitude:"Double",
longitude:"Double",
postalCode:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "location",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"location": {
"id": "ID",
"city": "String",
"country": "String",
"district": "String",
"latitude": "Double",
"longitude": "Double",
"postalCode": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete Category` API
Deletes a category by id (soft delete). Only admin allowed.
**API Frontend Description By The Backend Architect**
Admin-only. Deleting a parent category sets parentCategoryId to null on children. Category is soft-deleted for restoration if needed.
**Rest Route**
The `deleteCategory` API REST controller can be triggered via the following route:
`/v1/categories/:categoryId`
**Rest Request Parameters**
The `deleteCategory` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| categoryId | ID | true | request.params?.["categoryId"] |
**categoryId** : 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/categories/:categoryId**
```js
axios({
method: 'DELETE',
url: `/v1/categories/${categoryId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "category",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"category": {
"id": "ID",
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete Location` API
Soft-delete a location for admin-only. Used for removing obsolete/corrected locations.
**API Frontend Description By The Backend Architect**
Admin-only. Set isActive=false to remove location from public selectors. If referenced elsewhere, deletion may be blocked until listings/categories updated.
**Rest Route**
The `deleteLocation` API REST controller can be triggered via the following route:
`/v1/locations/:locationId`
**Rest Request Parameters**
The `deleteLocation` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| locationId | ID | true | request.params?.["locationId"] |
**locationId** : 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/locations/:locationId**
```js
axios({
method: 'DELETE',
url: `/v1/locations/${locationId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "location",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"location": {
"id": "ID",
"city": "String",
"country": "String",
"district": "String",
"latitude": "Double",
"longitude": "Double",
"postalCode": "String",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Category` API
Fetch a single category by id. Publicly accessible.
**API Frontend Description By The Backend Architect**
Get category details for a given id. Enrich response with child category count and parent info for navigation trees. Used for editing/viewing category details.
**Rest Route**
The `getCategory` API REST controller can be triggered via the following route:
`/v1/categories/:categoryId`
**Rest Request Parameters**
The `getCategory` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| categoryId | ID | true | request.params?.["categoryId"] |
**categoryId** : 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/categories/:categoryId**
```js
axios({
method: 'GET',
url: `/v1/categories/${categoryId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "category",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"category": {
"parentCategory": {
"name": "String",
"slug": "String"
},
"childCategories": {
"name": "String",
"slug": "String",
"isActive": true
},
"isActive": true
}
}
```
### `Get Location` API
Get details of a location by id. Publicly accessible for search/forms. Used by listing creation editors, etc.
**API Frontend Description By The Backend Architect**
Fetch all fields for display or editing/location picker. Admins use for management forms; public users for navigation/filter search.
**Rest Route**
The `getLocation` API REST controller can be triggered via the following route:
`/v1/locations/:locationId`
**Rest Request Parameters**
The `getLocation` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| locationId | ID | true | request.params?.["locationId"] |
**locationId** : 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/locations/:locationId**
```js
axios({
method: 'GET',
url: `/v1/locations/${locationId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "location",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"location": {
"isActive": true
}
}
```
### `List Categories` API
Returns all categories (optionally filtered by parentCategoryId or isActive). Used for category trees, navigation, and dropdowns. Public.
**API Frontend Description By The Backend Architect**
Use this endpoint for building category selection/search trees, sidebars, or dropdowns. Accepts parentCategoryId as a filter for fetching children. Returns all data for public display. Pagination not enabled (few hundred at most). Children included via join. Optionally returns count of active children for expandable UI.
**Rest Route**
The `listCategories` API REST controller can be triggered via the following route:
`/v1/categories`
**Rest Request Parameters**
The `listCategories` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/categories**
```js
axios({
method: 'GET',
url: '/v1/categories',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "categories",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"categories": [
{
"childCategories": [
{
"name": "String",
"slug": "String",
"isActive": true
},
{},
{}
],
"activeChildCount": [
null,
null,
null
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `List Locations` API
List all locations (optionally filter by country/city/district). Used for populating selectors and browsing. Public. No pagination (few thousand max).
**API Frontend Description By The Backend Architect**
Request all locations or optionally filter by country/city/district for cascading selectors. Public use for forms, admin for management. If needed, can expand to support location grouping/child-count in future.
**Rest Route**
The `listLocations` API REST controller can be triggered via the following route:
`/v1/locations`
**Rest Request Parameters**
The `listLocations` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/locations**
```js
axios({
method: 'GET',
url: '/v1/locations',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "locations",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"locations": [
{
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Update Category` API
Update an existing category. Only admin allowed. Slug uniqueness enforced.
**API Frontend Description By The Backend Architect**
Admins can update any field of a category including parent/child relationships. Changing parentCategoryId triggers structure update. Slug must remain unique.
**Rest Route**
The `updateCategory` API REST controller can be triggered via the following route:
`/v1/categories/:categoryId`
**Rest Request Parameters**
The `updateCategory` api has got 7 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| categoryId | ID | true | request.params?.["categoryId"] |
| description | Text | false | request.body?.["description"] |
| icon | String | false | request.body?.["icon"] |
| name | String | false | request.body?.["name"] |
| parentCategoryId | ID | false | request.body?.["parentCategoryId"] |
| slug | String | false | request.body?.["slug"] |
| sortOrder | Integer | false | request.body?.["sortOrder"] |
**categoryId** : This id paremeter is used to select the required data object that will be updated
**description** : Optional extended description for category (for admin display or frontend info).
**icon** : Icon identifier (string or URL to a static asset) for this category.
**name** : Category name, e.g. 'Automobiles', 'Electronics'.
**parentCategoryId** : References parent category for hierarchy. Top-level (root) categories have null.
**slug** : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
**sortOrder** : Order for listing within siblings. Unique per parent.
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/categories/:categoryId**
```js
axios({
method: 'PATCH',
url: `/v1/categories/${categoryId}`,
data: {
description:"Text",
icon:"String",
name:"String",
parentCategoryId:"ID",
slug:"String",
sortOrder:"Integer",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "category",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"category": {
"id": "ID",
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Update Location` API
Update existing location entry. Only admin allowed. Composite key must remain unique.
**API Frontend Description By The Backend Architect**
Admin-only. Location string fields (country, city, district) must not create a duplicate. Use for typo correction or boundary updates; minimal public usage.
**Rest Route**
The `updateLocation` API REST controller can be triggered via the following route:
`/v1/locations/:locationId`
**Rest Request Parameters**
The `updateLocation` api has got 7 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| locationId | ID | true | request.params?.["locationId"] |
| city | String | false | request.body?.["city"] |
| country | String | false | request.body?.["country"] |
| district | String | false | request.body?.["district"] |
| latitude | Double | false | request.body?.["latitude"] |
| longitude | Double | false | request.body?.["longitude"] |
| postalCode | String | false | request.body?.["postalCode"] |
**locationId** : This id paremeter is used to select the required data object that will be updated
**city** : City name.
**country** : Country name (typically 'Turkey').
**district** : District name, for fine-grained search.
**latitude** : Latitude for map/search.
**longitude** : Longitude for map/search.
**postalCode** : Postal code for location.
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/locations/:locationId**
```js
axios({
method: 'PATCH',
url: `/v1/locations/${locationId}`,
data: {
city:"String",
country:"String",
district:"String",
latitude:"Double",
longitude:"Double",
postalCode:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "location",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"location": {
"id": "ID",
"city": "String",
"country": "String",
"district": "String",
"latitude": "Double",
"longitude": "Double",
"postalCode": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `_fetch Listcategory` API
System API to fetch list of category records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListCategory` API REST controller can be triggered via the following route:
`/v1/_fetchlistcategory`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListCategory` api supports 3 optional filter parameters for filtering list results:
**name** (`String`): Category name, e.g. 'Automobiles', 'Electronics'.
- Single (partial match, case-insensitive): `?name=`
- Multiple: `?name=&name=`
- Null: `?name=null`
**parentCategoryId** (`ID`): References parent category for hierarchy. Top-level (root) categories have null.
- Single: `?parentCategoryId=`
- Multiple: `?parentCategoryId=&parentCategoryId=`
- Null: `?parentCategoryId=null`
**slug** (`String`): SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
- Single (partial match, case-insensitive): `?slug=`
- Multiple: `?slug=&slug=`
- Null: `?slug=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistcategory**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistcategory',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// name: '' // Filter by name
// parentCategoryId: '' // Filter by parentCategoryId
// slug: '' // Filter by slug
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "categories",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"categories": [
{
"id": "ID",
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"parent": [
{
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `_fetch Listlocation` API
System API to fetch list of location records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListLocation` API REST controller can be triggered via the following route:
`/v1/_fetchlistlocation`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListLocation` api supports 3 optional filter parameters for filtering list results:
**city** (`String`): City name.
- Single (partial match, case-insensitive): `?city=`
- Multiple: `?city=&city=`
- Null: `?city=null`
**country** (`String`): Country name (typically 'Turkey').
- Single (partial match, case-insensitive): `?country=`
- Multiple: `?country=&country=`
- Null: `?country=null`
**district** (`String`): District name, for fine-grained search.
- Single (partial match, case-insensitive): `?district=`
- Multiple: `?district=&district=`
- Null: `?district=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistlocation**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistlocation',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// city: '' // Filter by city
// country: '' // Filter by country
// district: '' // Filter by district
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "locations",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"locations": [
{
"id": "ID",
"city": "String",
"country": "String",
"district": "String",
"latitude": "Double",
"longitude": "Double",
"postalCode": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-conversation-service
**Version:** `1.0.1`
Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the Conversation Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Conversation Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the Conversation Service via HTTP requests for purposes such as creating, updating, deleting and querying Conversation objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the Conversation Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the Conversation service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the Conversation service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Conversation service.
This service is configured to listen for HTTP requests on port `3005`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/conversation-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/conversation-api`
* **Production:** `https://clonesahibinden.mindbricks.co/conversation-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the Conversation service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `Conversation` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Conversation` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `Conversation` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
Conversation service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### ConversationMessage resource
*Resource Definition* : A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status.
*ConversationMessage Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **content** | Text | | | *Message text body. Sanitized before saving.* |
| **conversationThreadId** | ID | | | *Parent thread for this message.* |
| **isRead** | Boolean | | | *True if the receiver has read this message.* |
| **readAt** | Date | | | *Timestamp when the receiver read the message (null if unread).* |
| **receiverId** | ID | | | *User receiving the message (must be the other participant of the thread).* |
| **senderId** | ID | | | *User sending the message (must be a participant of the thread).* |
| **sentAt** | Date | | | *Timestamp when message was sent.* |
### ConversationThread resource
*Resource Definition* : Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.
*ConversationThread Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **lastMessageAt** | Date | | | *Date/time of the latest message in the thread (for sorting inbox).* |
| **listingId** | ID | | | *ID of the listing being discussed.* |
| **receiverId** | ID | | | *User B in the conversation (order-invariant with senderId).* |
| **senderId** | ID | | | *User A in the conversation (order-invariant with receiverId).* |
## Business Api
### `Create Conversationmessage` API
Send a new message in a conversation. Only thread participants can send; updates thread's lastMessageAt.
**API Frontend Description By The Backend Architect**
Used when a user sends a message in a conversation (thread). On success, new message appears in thread; unread by receiver.
**Rest Route**
The `createConversationMessage` API REST controller can be triggered via the following route:
`/v1/conversationmessages`
**Rest Request Parameters**
The `createConversationMessage` api has got 7 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| content | Text | true | request.body?.["content"] |
| conversationThreadId | ID | true | request.body?.["conversationThreadId"] |
| isRead | Boolean | true | request.body?.["isRead"] |
| readAt | Date | false | request.body?.["readAt"] |
| receiverId | ID | true | request.body?.["receiverId"] |
| senderId | ID | true | request.body?.["senderId"] |
| sentAt | Date | true | request.body?.["sentAt"] |
**content** : Message text body. Sanitized before saving.
**conversationThreadId** : Parent thread for this message.
**isRead** : True if the receiver has read this message.
**readAt** : Timestamp when the receiver read the message (null if unread).
**receiverId** : User receiving the message (must be the other participant of the thread).
**senderId** : User sending the message (must be a participant of the thread).
**sentAt** : Timestamp when message was sent.
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/conversationmessages**
```js
axios({
method: 'POST',
url: '/v1/conversationmessages',
data: {
content:"Text",
conversationThreadId:"ID",
isRead:"Boolean",
readAt:"Date",
receiverId:"ID",
senderId:"ID",
sentAt:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationMessage",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"conversationMessage": {
"id": "ID",
"content": "Text",
"conversationThreadId": "ID",
"isRead": "Boolean",
"readAt": "Date",
"receiverId": "ID",
"senderId": "ID",
"sentAt": "Date",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Create Conversationthread` API
Starts a new conversation thread between two users for a specific listing. Prevents duplicate threads for the same user pair/listing.
**API Frontend Description By The Backend Architect**
Invoked when user contacts seller about a listing. If an existing thread exists for this user pair/listing (any order), it is reused. Only listing owner or buyers can start a thread.
**Rest Route**
The `createConversationThread` API REST controller can be triggered via the following route:
`/v1/conversationthreads`
**Rest Request Parameters**
The `createConversationThread` api has got 4 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| lastMessageAt | Date | true | request.body?.["lastMessageAt"] |
| listingId | ID | true | request.body?.["listingId"] |
| receiverId | ID | true | request.body?.["receiverId"] |
| senderId | ID | true | request.body?.["senderId"] |
**lastMessageAt** : Date/time of the latest message in the thread (for sorting inbox).
**listingId** : ID of the listing being discussed.
**receiverId** : User B in the conversation (order-invariant with senderId).
**senderId** : User A in the conversation (order-invariant with receiverId).
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/conversationthreads**
```js
axios({
method: 'POST',
url: '/v1/conversationthreads',
data: {
lastMessageAt:"Date",
listingId:"ID",
receiverId:"ID",
senderId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationThread",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"conversationThread": {
"id": "ID",
"lastMessageAt": "Date",
"listingId": "ID",
"receiverId": "ID",
"senderId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete Conversationmessage` API
Soft-deletes a message. Only moderator/admins can fully delete; users may hide/delete for self (future phase).
**API Frontend Description By The Backend Architect**
Used for moderation; message remains for audit trail/history.
**Rest Route**
The `deleteConversationMessage` API REST controller can be triggered via the following route:
`/v1/conversationmessages/:conversationMessageId`
**Rest Request Parameters**
The `deleteConversationMessage` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| conversationMessageId | ID | true | request.params?.["conversationMessageId"] |
**conversationMessageId** : 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/conversationmessages/:conversationMessageId**
```js
axios({
method: 'DELETE',
url: `/v1/conversationmessages/${conversationMessageId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationMessage",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"conversationMessage": {
"id": "ID",
"content": "Text",
"conversationThreadId": "ID",
"isRead": "Boolean",
"readAt": "Date",
"receiverId": "ID",
"senderId": "ID",
"sentAt": "Date",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Conversationmessage` API
Fetch a single message by ID. Only accessible to participants or moderators/admins.
**API Frontend Description By The Backend Architect**
Loads a message for display in UI. Fails if not participant or staff.
**Rest Route**
The `getConversationMessage` API REST controller can be triggered via the following route:
`/v1/conversationmessages/:conversationMessageId`
**Rest Request Parameters**
The `getConversationMessage` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| conversationMessageId | ID | true | request.params?.["conversationMessageId"] |
**conversationMessageId** : 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/conversationmessages/:conversationMessageId**
```js
axios({
method: 'GET',
url: `/v1/conversationmessages/${conversationMessageId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationMessage",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"conversationMessage": {
"id": "ID",
"content": "Text",
"conversationThreadId": "ID",
"isRead": "Boolean",
"readAt": "Date",
"receiverId": "ID",
"senderId": "ID",
"sentAt": "Date",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Conversationthread` API
Get a conversation thread by ID. Only visible to participants or staff.
**API Frontend Description By The Backend Architect**
Shows full thread info for inbox/detail view. Fails if user does not participate or is not moderator/admin.
**Rest Route**
The `getConversationThread` API REST controller can be triggered via the following route:
`/v1/conversationthreads/:conversationThreadId`
**Rest Request Parameters**
The `getConversationThread` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| conversationThreadId | ID | true | request.params?.["conversationThreadId"] |
**conversationThreadId** : 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/conversationthreads/:conversationThreadId**
```js
axios({
method: 'GET',
url: `/v1/conversationthreads/${conversationThreadId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationThread",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"conversationThread": {
"listing": {
"status": "Enum",
"status_idx": "Integer",
"title": "String",
"userId": "ID"
},
"isActive": true
}
}
```
### `List Conversationmessages` API
List all messages in a thread, sorted oldest to newest. Only accessible to thread participants or staff.
**API Frontend Description By The Backend Architect**
Loads the chat history in UI for reading; includes isRead, sender info, etc. Used for conversation detail view.
**Rest Route**
The `listConversationMessages` API REST controller can be triggered via the following route:
`/v1/listconversationmessages/:conversationThreadId`
**Rest Request Parameters**
The `listConversationMessages` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| conversationThreadId | ID | true | request.query?.["conversationThreadId"] |
**conversationThreadId** : Thread to load messages from.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/listconversationmessages/:conversationThreadId**
```js
axios({
method: 'GET',
url: `/v1/listconversationmessages/${conversationThreadId}`,
data: {
},
params: {
conversationThreadId:'"ID"',
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationMessages",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"conversationMessages": [
{
"id": "ID",
"content": "Text",
"conversationThreadId": "ID",
"isRead": "Boolean",
"readAt": "Date",
"receiverId": "ID",
"senderId": "ID",
"sentAt": "Date",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `List Conversationthreads` API
List all threads a user participates in, most recent first. Also used for moderator search/all-list.
**API Frontend Description By The Backend Architect**
Shows all user's conversation threads in inbox. Moderators can search all.
**Rest Route**
The `listConversationThreads` API REST controller can be triggered via the following route:
`/v1/conversationthreads`
**Rest Request Parameters**
The `listConversationThreads` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/conversationthreads**
```js
axios({
method: 'GET',
url: '/v1/conversationthreads',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationThreads",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"conversationThreads": [
{
"listing": [
{
"status": "Enum",
"status_idx": "Integer",
"title": "String",
"userId": "ID"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Mark Messageasread` API
Marks a message as read (isRead=true, readAt=now); only allowed for receiver.
**API Frontend Description By The Backend Architect**
When viewing messages, receiver marks message as read – triggers unread count decrement in UI, updates message status.
**Rest Route**
The `markMessageAsRead` API REST controller can be triggered via the following route:
`/v1/markmessageasread/:conversationMessageId`
**Rest Request Parameters**
The `markMessageAsRead` api has got 3 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| conversationMessageId | ID | true | request.params?.["conversationMessageId"] |
| isRead | Boolean | false | request.body?.["isRead"] |
| readAt | Date | false | request.body?.["readAt"] |
**conversationMessageId** : This id paremeter is used to select the required data object that will be updated
**isRead** : True if the receiver has read this message.
**readAt** : Timestamp when the receiver read the message (null if unread).
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/markmessageasread/:conversationMessageId**
```js
axios({
method: 'PATCH',
url: `/v1/markmessageasread/${conversationMessageId}`,
data: {
isRead:"Boolean",
readAt:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationMessage",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"conversationMessage": {
"id": "ID",
"content": "Text",
"conversationThreadId": "ID",
"isRead": "Boolean",
"readAt": "Date",
"receiverId": "ID",
"senderId": "ID",
"sentAt": "Date",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `_fetch Listconversationmessage` API
System API to fetch list of conversationMessage records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListConversationMessage` API REST controller can be triggered via the following route:
`/v1/_fetchlistconversationmessage`
**Rest Request Parameters**
The `_fetchListConversationMessage` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistconversationmessage**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistconversationmessage',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationMessages",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"conversationMessages": [
{
"id": "ID",
"content": "Text",
"conversationThreadId": "ID",
"isRead": "Boolean",
"readAt": "Date",
"receiverId": "ID",
"senderId": "ID",
"sentAt": "Date",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"thread": [
{
"lastMessageAt": "Date",
"listingId": "ID",
"receiverId": "ID",
"senderId": "ID"
},
{},
{}
],
"receiverUser": [
{
"fullname": "String"
},
{},
{}
],
"senderUser": [
{
"fullname": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `_fetch Listconversationthread` API
System API to fetch list of conversationThread records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListConversationThread` API REST controller can be triggered via the following route:
`/v1/_fetchlistconversationthread`
**Rest Request Parameters**
The `_fetchListConversationThread` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistconversationthread**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistconversationthread',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "conversationThreads",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"conversationThreads": [
{
"id": "ID",
"lastMessageAt": "Date",
"listingId": "ID",
"receiverId": "ID",
"senderId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"listing": [
{
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer"
},
{},
{}
],
"receiverUser": [
{
"fullname": "String"
},
{},
{}
],
"senderUser": [
{
"fullname": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-favorite-service
**Version:** `1.0.3`
Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the Favorite Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Favorite Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the Favorite Service via HTTP requests for purposes such as creating, updating, deleting and querying Favorite objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the Favorite Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the Favorite service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the Favorite service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Favorite service.
This service is configured to listen for HTTP requests on port `3006`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/favorite-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/favorite-api`
* **Production:** `https://clonesahibinden.mindbricks.co/favorite-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the Favorite service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `Favorite` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Favorite` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `Favorite` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
Favorite service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### Favorite resource
*Resource Definition* : Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.
*Favorite Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **favoritedAt** | Date | | | *Date and time when the favorite was added.* |
| **listingId** | ID | | | *Target listing being favorited.* |
| **userId** | ID | | | *User who favorited the listing.* |
## Business Api
### `Create Favorite` API
Add a favorite for a listing for the current user. Prevents duplicate (user,listing) pairs, and can't favorite own listing.
**API Frontend Description By The Backend Architect**
AI Dev: Call this API to favorite a listing; on success, update UI state and increment count. If already favorited, show appropriate feedback. Cannot favorite own listings. No double favoriting allowed.
**Rest Route**
The `createFavorite` API REST controller can be triggered via the following route:
`/v1/favorites`
**Rest Request Parameters**
The `createFavorite` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.body?.["listingId"] |
**listingId** : Target listing being favorited.
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/favorites**
```js
axios({
method: 'POST',
url: '/v1/favorites',
data: {
listingId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "favorite",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"favorite": {
"id": "ID",
"favoritedAt": "Date",
"listingId": "ID",
"userId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete Favorite` API
Unfavorite (remove favorite) the given listing for current user. Decrements favoriteCount on related listing when possible.
**API Frontend Description By The Backend Architect**
AI Dev: Use this API to unfavorite a listing. On success, update UI (remove highlight) and decrement displayed favorite count. If not found, treat as idempotent success for best UX.
**Rest Route**
The `deleteFavorite` API REST controller can be triggered via the following route:
`/v1/favorites/:favoriteId`
**Rest Request Parameters**
The `deleteFavorite` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| favoriteId | ID | true | request.params?.["favoriteId"] |
| listingId | ID | true | request.query?.["listingId"] |
**favoriteId** : This id paremeter is used to select the required data object that will be deleted
**listingId** : Target listing being favorited.. The parameter is used to query data.
**REST Request**
To access the api you can use the **REST** controller with the path **DELETE /v1/favorites/:favoriteId**
```js
axios({
method: 'DELETE',
url: `/v1/favorites/${favoriteId}`,
data: {
},
params: {
listingId:'"ID"',
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "favorite",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"favorite": {
"id": "ID",
"favoritedAt": "Date",
"listingId": "ID",
"userId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Favorite` API
Get a specific favorite by id or by userId+listingId, mainly used to check if a listing is favorited by user (for heart/check display in feeds/details). Only accessible by owner or admin.
**API Frontend Description By The Backend Architect**
AI Dev: Use to check if a given listing is in the user's favorites; supports single-record fetch via id or userId+listingId composite. If no record, treat as not favorited in UI.
**Rest Route**
The `getFavorite` API REST controller can be triggered via the following route:
`/v1/favorites/:favoriteId`
**Rest Request Parameters**
The `getFavorite` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| favoriteId | ID | true | request.params?.["favoriteId"] |
**favoriteId** : 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/favorites/:favoriteId**
```js
axios({
method: 'GET',
url: `/v1/favorites/${favoriteId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "favorite",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"favorite": {
"listing": {
"isPremium": "Boolean",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"title": "String"
},
"isActive": true
}
}
```
### `List Favorites` API
List all listings favorited by the current user, joined with listing summary and preview (title, price, cover image, etc). Private; only owner or admin can access.
**API Frontend Description By The Backend Architect**
AI Dev: Use this to render the user's entire favorites collection for the profile page. Each item must provide at least listing id, title, price, and main image for visual feed. Paginate and sort newest first by favoritedAt.
**Rest Route**
The `listFavorites` API REST controller can be triggered via the following route:
`/v1/favorites`
**Rest Request Parameters**
The `listFavorites` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/favorites**
```js
axios({
method: 'GET',
url: '/v1/favorites',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "favorites",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"favorites": [
{
"listing": [
{
"currency": "String",
"isPremium": "Boolean",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"title": "String"
},
{},
{}
],
"mainImage": {
"sortOrder": "Integer",
"thumbnailUrl": "String",
"url": "String"
},
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `_fetch Listfavorite` API
System API to fetch list of favorite records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListFavorite` API REST controller can be triggered via the following route:
`/v1/_fetchlistfavorite`
**Rest Request Parameters**
The `_fetchListFavorite` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistfavorite**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistfavorite',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "favorites",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"favorites": [
{
"id": "ID",
"favoritedAt": "Date",
"listingId": "ID",
"userId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"listing": [
{
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer"
},
{},
{}
],
"user": [
{
"fullname": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-listing-service
**Version:** `1.0.3`
Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the Listing Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Listing Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the Listing Service via HTTP requests for purposes such as creating, updating, deleting and querying Listing objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the Listing Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the Listing service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the Listing service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Listing service.
This service is configured to listen for HTTP requests on port `3001`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/listing-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/listing-api`
* **Production:** `https://clonesahibinden.mindbricks.co/listing-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the Listing service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `Listing` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Listing` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `Listing` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
Listing service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### Listing resource
*Resource Definition* : Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.
*Listing Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **attributes** | Object | | | *JSON object for custom per-category attributes (structured as required by category schema).* |
| **categoryId** | ID | | | *Main category for the listing (categoryLocation:category).* |
| **condition** | Enum | | | *Item condition: new, used, other.* |
| **contactEmail** | String | | | *Contact email (recommended to send via platform only).* |
| **contactPhone** | String | | | *Display phone/contact for listing; may be masked by front end.* |
| **currency** | String | | | *Currency (ISO-4217 code, e.g. 'TRY', 'USD').* |
| **description** | Text | | | *Full description/body of listing.* |
| **expiresAt** | Date | | | *UTC expiry for listing; after this, listing is automatically expired.* |
| **favoriteCount** | Integer | | | *Favorite count (updated asynchronously by favorite service, not directly settable by user).* |
| **isPremium** | Boolean | | | *If true, the listing is premium (highlighted/pinned, eligible for special placement).* |
| **listingType** | Enum | | | *Type of listing (sale, rent, service, etc.).* |
| **locationId** | ID | | | *Location (categoryLocation:location).* |
| **_paymentConfirmation** | String | | | *Stripe payment result details (Stripe webhook metadata, internal use only).* |
| **premiumExpiry** | Date | | | *UTC date when premium status expires. Null if not premium or not applicable.* |
| **premiumType** | Enum | | | *Which premium package (gold, silver, none, etc.).* |
| **price** | Double | | | *Listing price.* |
| **status** | Enum | | | *Lifecycle status: pending_review, active, denied, sold, expired, deleted.* |
| **subcategoryId** | ID | | | *Subcategory for the listing, can be null for top-level (categoryLocation:category).* |
| **title** | String | | | *Listing title, short and clear.* |
| **userId** | ID | | | *Owner (poster) of the listing (auth:user).* |
| **viewsCount** | Integer | | | *View count (updated asynchronously; not directly settable by user).* |
| **paymentConfirmation** | Enum | | | *An automatic property that is used to check the confirmed status of the payment set by webhooks.* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### condition Enum Property
*Property Definition* : Item condition: new, used, other.*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **brand_new** | `"brand_new""` | 0 |
| **used** | `"used""` | 1 |
| **other** | `"other""` | 2 |
##### listingType Enum Property
*Property Definition* : Type of listing (sale, rent, service, etc.).*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **sale** | `"sale""` | 0 |
| **rent** | `"rent""` | 1 |
| **service** | `"service""` | 2 |
| **job** | `"job""` | 3 |
##### premiumType Enum Property
*Property Definition* : Which premium package (gold, silver, none, etc.).*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **none** | `"none""` | 0 |
| **bronze** | `"bronze""` | 1 |
| **silver** | `"silver""` | 2 |
| **gold** | `"gold""` | 3 |
##### status Enum Property
*Property Definition* : Lifecycle status: pending_review, active, denied, sold, expired, deleted.*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **pending_review** | `"pending_review""` | 0 |
| **active** | `"active""` | 1 |
| **denied** | `"denied""` | 2 |
| **sold** | `"sold""` | 3 |
| **expired** | `"expired""` | 4 |
| **deleted** | `"deleted""` | 5 |
##### paymentConfirmation Enum Property
*Property Definition* : An automatic property that is used to check the confirmed status of the payment set by webhooks.*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **pending** | `"pending""` | 0 |
| **processing** | `"processing""` | 1 |
| **paid** | `"paid""` | 2 |
| **canceled** | `"canceled""` | 3 |
### Sys_listingPayment resource
*Resource Definition* : A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config
*Sys_listingPayment Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **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 listing 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.* |
### Sys_paymentCustomer resource
*Resource Definition* : A payment storage object to store the customer values of the payment platform
*Sys_paymentCustomer Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **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.* |
### Sys_paymentMethod resource
*Resource Definition* : A payment storage object to store the payment methods of the platform customers
*Sys_paymentMethod Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **paymentMethodId** | String | | | *A string value to represent the id of the payment method on the payment platform.* |
| **userId** | ID | | | * An ID value to represent the user who owns the payment method* |
| **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.* |
## Business Api
### `Create Listing` API
Create a new classified listing. Sets status to 'pending_review' (may be updated by moderator process). Accepts all mandatory fields, accepts premiumType for premium upgrade.
**API Frontend Description By The Backend Architect**
- After creating a listing, display the pending_review status and explain the moderation flow.
- If premiumType is chosen, trigger Stripe flow; after payment confirm, reload to show upgraded listing.
**Rest Route**
The `createListing` API REST controller can be triggered via the following route:
`/v1/listings`
**Rest Request Parameters**
The `createListing` api has got 19 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| attributes | Object | false | request.body?.["attributes"] |
| categoryId | ID | true | request.body?.["categoryId"] |
| condition | Enum | true | request.body?.["condition"] |
| contactEmail | String | false | request.body?.["contactEmail"] |
| contactPhone | String | false | request.body?.["contactPhone"] |
| currency | String | true | request.body?.["currency"] |
| description | Text | true | request.body?.["description"] |
| expiresAt | Date | false | request.body?.["expiresAt"] |
| favoriteCount | Integer | true | request.body?.["favoriteCount"] |
| listingType | Enum | true | request.body?.["listingType"] |
| locationId | ID | true | request.body?.["locationId"] |
| _paymentConfirmation | String | false | request.body?.["_paymentConfirmation"] |
| premiumExpiry | Date | false | request.body?.["premiumExpiry"] |
| premiumType | Enum | false | request.body?.["premiumType"] |
| price | Double | true | request.body?.["price"] |
| status | Enum | true | request.body?.["status"] |
| subcategoryId | ID | false | request.body?.["subcategoryId"] |
| title | String | true | request.body?.["title"] |
| viewsCount | Integer | true | request.body?.["viewsCount"] |
**attributes** : JSON object for custom per-category attributes (structured as required by category schema).
**categoryId** : Main category for the listing (categoryLocation:category).
**condition** : Item condition: new, used, other.
**contactEmail** : Contact email (recommended to send via platform only).
**contactPhone** : Display phone/contact for listing; may be masked by front end.
**currency** : Currency (ISO-4217 code, e.g. 'TRY', 'USD').
**description** : Full description/body of listing.
**expiresAt** : UTC expiry for listing; after this, listing is automatically expired.
**favoriteCount** : Favorite count (updated asynchronously by favorite service, not directly settable by user).
**listingType** : Type of listing (sale, rent, service, etc.).
**locationId** : Location (categoryLocation:location).
**_paymentConfirmation** : Stripe payment result details (Stripe webhook metadata, internal use only).
**premiumExpiry** : UTC date when premium status expires. Null if not premium or not applicable.
**premiumType** : Which premium package (gold, silver, none, etc.).
**price** : Listing price.
**status** : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
**subcategoryId** : Subcategory for the listing, can be null for top-level (categoryLocation:category).
**title** : Listing title, short and clear.
**viewsCount** : View count (updated asynchronously; not directly settable by user).
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/listings**
```js
axios({
method: 'POST',
url: '/v1/listings',
data: {
attributes:"Object",
categoryId:"ID",
condition:"Enum",
contactEmail:"String",
contactPhone:"String",
currency:"String",
description:"Text",
expiresAt:"Date",
favoriteCount:"Integer",
listingType:"Enum",
locationId:"ID",
_paymentConfirmation:"String",
premiumExpiry:"Date",
premiumType:"Enum",
price:"Double",
status:"Enum",
subcategoryId:"ID",
title:"String",
viewsCount:"Integer",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete Listing` API
Delete a listing (soft delete, sets status to 'deleted'). Only allowed by listing owner, admin, or moderator.
**API Frontend Description By The Backend Architect**
- Confirm before deleting, as this removes visibility and access for buyers.
- Owner can undo delete by restoring listing in future.
- After delete, return to listing dashboard.
**Rest Route**
The `deleteListing` API REST controller can be triggered via the following route:
`/v1/listings/:listingId`
**Rest Request Parameters**
The `deleteListing` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.params?.["listingId"] |
**listingId** : 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/listings/:listingId**
```js
axios({
method: 'DELETE',
url: `/v1/listings/${listingId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Listing` API
Retrieve one listing with all primary fields, including category, subcategory, location, user info. Optionally, frontend can request joined images/favorites from other services.
**API Frontend Description By The Backend Architect**
- Show complete listing details to the user, with status and premium.
- Display relations (user, category, subcategory, location); join images and favorite status via BFF as needed.
- For owner, show edit/delete options; for visitors, show contact/"favorite" actions if allowed.
**Rest Route**
The `getListing` API REST controller can be triggered via the following route:
`/v1/listings/:listingId`
**Rest Request Parameters**
The `getListing` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.params?.["listingId"] |
**listingId** : 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/listings/:listingId**
```js
axios({
method: 'GET',
url: `/v1/listings/${listingId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"user": {
"fullname": "String",
"avatar": "String",
"roleId": "String"
},
"category": {
"name": "String",
"parentCategoryId": "ID",
"slug": "String"
},
"subcategory": {
"name": "String",
"parentCategoryId": "ID",
"slug": "String"
},
"location": {
"city": "String",
"country": "String",
"district": "String"
},
"isActive": true
}
}
```
### `List Listings` API
Search/browse listings with advanced filtering (category, location, keyword, price range, condition, type, premium, status, etc.) and sorting. Publicly accessible. Supports pagination and all major sort orders. Full-text search on title/description.
**API Frontend Description By The Backend Architect**
- Support all applicable filters and keyword search. Use UI to trigger filter/query params.
- Allow sorting by newest (default), oldest, price asc/desc, premium-first, most viewed.
- Pagination: always return limited page, show total count.
- Returns summary info, relations (user, category, location). Images/favorites joined in BFF layer as needed.
**Rest Route**
The `listListings` API REST controller can be triggered via the following route:
`/v1/listings`
**Rest Request Parameters**
The `listListings` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/listings**
```js
axios({
method: 'GET',
url: '/v1/listings',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listings",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"listings": [
{
"user": [
{
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"category": [
{
"name": "String"
},
{},
{}
],
"subcategory": [
{
"name": "String"
},
{},
{}
],
"location": [
{
"city": "String",
"district": "String"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Update Listing` API
Update any mutable field of a listing. Only allowed by owner, admin, or moderator. If significant fields change and listing is active, status may return to pending_review until approved.
**API Frontend Description By The Backend Architect**
- If the user is not the listing owner, admin, or moderator, forbid.
- After major changes, listing status may require moderator review.
- On success, reload listing details showing updated info and status.
**Rest Route**
The `updateListing` API REST controller can be triggered via the following route:
`/v1/listings/:listingId`
**Rest Request Parameters**
The `updateListing` api has got 17 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.params?.["listingId"] |
| attributes | Object | false | request.body?.["attributes"] |
| categoryId | ID | false | request.body?.["categoryId"] |
| condition | Enum | false | request.body?.["condition"] |
| contactEmail | String | false | request.body?.["contactEmail"] |
| contactPhone | String | false | request.body?.["contactPhone"] |
| currency | String | false | request.body?.["currency"] |
| description | Text | false | request.body?.["description"] |
| expiresAt | Date | false | request.body?.["expiresAt"] |
| listingType | Enum | false | request.body?.["listingType"] |
| locationId | ID | false | request.body?.["locationId"] |
| premiumExpiry | Date | false | request.body?.["premiumExpiry"] |
| premiumType | Enum | false | request.body?.["premiumType"] |
| price | Double | false | request.body?.["price"] |
| status | Enum | false | request.body?.["status"] |
| subcategoryId | ID | false | request.body?.["subcategoryId"] |
| title | String | false | request.body?.["title"] |
**listingId** : This id paremeter is used to select the required data object that will be updated
**attributes** : JSON object for custom per-category attributes (structured as required by category schema).
**categoryId** : Main category for the listing (categoryLocation:category).
**condition** : Item condition: new, used, other.
**contactEmail** : Contact email (recommended to send via platform only).
**contactPhone** : Display phone/contact for listing; may be masked by front end.
**currency** : Currency (ISO-4217 code, e.g. 'TRY', 'USD').
**description** : Full description/body of listing.
**expiresAt** : UTC expiry for listing; after this, listing is automatically expired.
**listingType** : Type of listing (sale, rent, service, etc.).
**locationId** : Location (categoryLocation:location).
**premiumExpiry** : UTC date when premium status expires. Null if not premium or not applicable.
**premiumType** : Which premium package (gold, silver, none, etc.).
**price** : Listing price.
**status** : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
**subcategoryId** : Subcategory for the listing, can be null for top-level (categoryLocation:category).
**title** : Listing title, short and clear.
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/listings/:listingId**
```js
axios({
method: 'PATCH',
url: `/v1/listings/${listingId}`,
data: {
attributes:"Object",
categoryId:"ID",
condition:"Enum",
contactEmail:"String",
contactPhone:"String",
currency:"String",
description:"Text",
expiresAt:"Date",
listingType:"Enum",
locationId:"ID",
premiumExpiry:"Date",
premiumType:"Enum",
price:"Double",
status:"Enum",
subcategoryId:"ID",
title:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Upgrade Listingpremium` API
Upgrades a listing to premium status after successful payment. Sets isPremium=true, premiumType, premiumExpiry based on duration, and records payment confirmation. Called internally by payment service via interservice call.
**API Frontend Description By The Backend Architect**
- Internal API, called by payment service after Stripe payment confirmation.
- Updates listing premium status and expiry date.
- Not intended for direct frontend use.
**Rest Route**
The `upgradeListingPremium` API REST controller can be triggered via the following route:
`/v1/listings/upgrade-premium`
**Rest Request Parameters**
The `upgradeListingPremium` api has got 4 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.body?.["listingId"] |
| premiumType | Enum | true | request.body?.["premiumType"] |
| premiumDuration | Integer | true | request.body?.["premiumDuration"] |
| paymentTransactionId | ID | true | request.body?.["paymentTransactionId"] |
**listingId** : ID of the listing to upgrade
**premiumType** : Premium package type (bronze, silver, gold)
**premiumDuration** : Duration of premium in days
**paymentTransactionId** : Payment transaction ID for confirmation record
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/listings/upgrade-premium**
```js
axios({
method: 'POST',
url: '/v1/listings/upgrade-premium',
data: {
listingId:"ID",
premiumType:"Enum",
premiumDuration:"Integer",
paymentTransactionId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "POST",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Listingpayment` API
This route is used to get the payment information by ID.
**Rest Route**
The `getListingPayment` API REST controller can be triggered via the following route:
`/v1/listingpayment/:sys_listingPaymentId`
**Rest Request Parameters**
The `getListingPayment` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| sys_listingPaymentId | ID | true | request.params?.["sys_listingPaymentId"] |
**sys_listingPaymentId** : 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/listingpayment/:sys_listingPaymentId**
```js
axios({
method: 'GET',
url: `/v1/listingpayment/${sys_listingPaymentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_listingPayment": {
"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 Listingpayments` API
This route is used to list all payments.
**Rest Route**
The `listListingPayments` API REST controller can be triggered via the following route:
`/v1/listingpayments`
**Rest Request Parameters**
**Filter Parameters**
The `listListingPayments` api supports 6 optional filter parameters for filtering list results:
**ownerId** (`ID`): An ID value to represent owner user who created the order
- Single: `?ownerId=`
- Multiple: `?ownerId=&ownerId=`
- Null: `?ownerId=null`
**orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source listing object
- Single: `?orderId=`
- Multiple: `?orderId=&orderId=`
- Null: `?orderId=null`
**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
- Single (partial match, case-insensitive): `?paymentId=`
- Multiple: `?paymentId=&paymentId=`
- Null: `?paymentId=null`
**paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
- Single (partial match, case-insensitive): `?paymentStatus=`
- Multiple: `?paymentStatus=&paymentStatus=`
- Null: `?paymentStatus=null`
**statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself.
- Single (partial match, case-insensitive): `?statusLiteral=`
- Multiple: `?statusLiteral=&statusLiteral=`
- Null: `?statusLiteral=null`
**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.
- Single (partial match, case-insensitive): `?redirectUrl=`
- Multiple: `?redirectUrl=&redirectUrl=`
- Null: `?redirectUrl=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/listingpayments**
```js
axios({
method: 'GET',
url: '/v1/listingpayments',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// ownerId: '' // Filter by ownerId
// orderId: '' // Filter by orderId
// paymentId: '' // Filter by paymentId
// paymentStatus: '' // Filter by paymentStatus
// statusLiteral: '' // Filter by statusLiteral
// redirectUrl: '' // Filter by redirectUrl
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayments",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"sys_listingPayments": [
{
"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 Listingpayment` API
This route is used to create a new payment.
**Rest Route**
The `createListingPayment` API REST controller can be triggered via the following route:
`/v1/listingpayment`
**Rest Request Parameters**
The `createListingPayment` 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 listing 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/listingpayment**
```js
axios({
method: 'POST',
url: '/v1/listingpayment',
data: {
orderId:"ID",
paymentId:"String",
paymentStatus:"String",
statusLiteral:"String",
redirectUrl:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayment",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"sys_listingPayment": {
"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 Listingpayment` API
This route is used to update an existing payment.
**Rest Route**
The `updateListingPayment` API REST controller can be triggered via the following route:
`/v1/listingpayment/:sys_listingPaymentId`
**Rest Request Parameters**
The `updateListingPayment` api has got 5 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| sys_listingPaymentId | ID | true | request.params?.["sys_listingPaymentId"] |
| 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_listingPaymentId** : 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/listingpayment/:sys_listingPaymentId**
```js
axios({
method: 'PATCH',
url: `/v1/listingpayment/${sys_listingPaymentId}`,
data: {
paymentId:"String",
paymentStatus:"String",
statusLiteral:"String",
redirectUrl:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayment",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"sys_listingPayment": {
"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 Listingpayment` API
This route is used to delete a payment.
**Rest Route**
The `deleteListingPayment` API REST controller can be triggered via the following route:
`/v1/listingpayment/:sys_listingPaymentId`
**Rest Request Parameters**
The `deleteListingPayment` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| sys_listingPaymentId | ID | true | request.params?.["sys_listingPaymentId"] |
**sys_listingPaymentId** : 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/listingpayment/:sys_listingPaymentId**
```js
axios({
method: 'DELETE',
url: `/v1/listingpayment/${sys_listingPaymentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayment",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"sys_listingPayment": {
"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 Listingpaymentbyorderid` API
This route is used to get the payment information by order id.
**Rest Route**
The `getListingPaymentByOrderId` API REST controller can be triggered via the following route:
`/v1/listingpaymentbyorderid/:orderId`
**Rest Request Parameters**
The `getListingPaymentByOrderId` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| sys_listingPaymentId | ID | true | request.params?.["sys_listingPaymentId"] |
| orderId | ID | true | request.params?.["orderId"] |
**sys_listingPaymentId** : This id paremeter is used to query the required data object.
**orderId** : an ID value to represent the orderId which is the ID parameter of the source listing 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/listingpaymentbyorderid/:orderId**
```js
axios({
method: 'GET',
url: `/v1/listingpaymentbyorderid/${orderId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_listingPayment": {
"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 Listingpaymentbypaymentid` API
This route is used to get the payment information by payment id.
**Rest Route**
The `getListingPaymentByPaymentId` API REST controller can be triggered via the following route:
`/v1/listingpaymentbypaymentid/:paymentId`
**Rest Request Parameters**
The `getListingPaymentByPaymentId` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| sys_listingPaymentId | ID | true | request.params?.["sys_listingPaymentId"] |
| paymentId | String | true | request.params?.["paymentId"] |
**sys_listingPaymentId** : This id paremeter is used to query the required data 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. The parameter is used to query data.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/listingpaymentbypaymentid/:paymentId**
```js
axios({
method: 'GET',
url: `/v1/listingpaymentbypaymentid/${paymentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_listingPayment": {
"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 Listingpayment` API
Start payment for listing
**Rest Route**
The `startListingPayment` API REST controller can be triggered via the following route:
`/v1/startlistingpayment/:listingId`
**Rest Request Parameters**
The `startListingPayment` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.params?.["listingId"] |
| paymentUserParams | Object | false | request.body?.["paymentUserParams"] |
**listingId** : 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
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/startlistingpayment/:listingId**
```js
axios({
method: 'PATCH',
url: `/v1/startlistingpayment/${listingId}`,
data: {
paymentUserParams:"Object",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"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 Listingpayment` API
Refresh payment info for listing from Stripe
**Rest Route**
The `refreshListingPayment` API REST controller can be triggered via the following route:
`/v1/refreshlistingpayment/:listingId`
**Rest Request Parameters**
The `refreshListingPayment` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.params?.["listingId"] |
| paymentUserParams | Object | false | request.body?.["paymentUserParams"] |
**listingId** : 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/refreshlistingpayment/:listingId**
```js
axios({
method: 'PATCH',
url: `/v1/refreshlistingpayment/${listingId}`,
data: {
paymentUserParams:"Object",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"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 Listingpayment` API
Refresh payment values by gateway webhook call for listing
**Rest Route**
The `callbackListingPayment` API REST controller can be triggered via the following route:
`/v1/callbacklistingpayment`
**Rest Request Parameters**
The `callbackListingPayment` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.body?.["listingId"] |
**listingId** : 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/callbacklistingpayment**
```js
axios({
method: 'POST',
url: '/v1/callbacklistingpayment',
data: {
listingId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listing",
"method": "POST",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"listing": {
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"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 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| sys_paymentCustomerId | ID | true | request.params?.["sys_paymentCustomerId"] |
| userId | ID | true | request.params?.["userId"] |
**sys_paymentCustomerId** : This id paremeter is used to query the required data object.
**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**
```js
axios({
method: 'GET',
url: `/v1/paymentcustomers/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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
- Single: `?userId=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**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
- Single (partial match, case-insensitive): `?customerId=`
- Multiple: `?customerId=&customerId=`
- Null: `?customerId=null`
**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.
- Single (partial match, case-insensitive): `?platform=`
- Multiple: `?platform=&platform=`
- Null: `?platform=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers**
```js
axios({
method: 'GET',
url: '/v1/paymentcustomers',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// customerId: '' // Filter by customerId
// platform: '' // Filter by platform
}
});
```
**REST Response**
```json
{
"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**
**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.
- Single (partial match, case-insensitive): `?paymentMethodId=`
- Multiple: `?paymentMethodId=&paymentMethodId=`
- Null: `?paymentMethodId=null`
**customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway.
- Single (partial match, case-insensitive): `?customerId=`
- Multiple: `?customerId=&customerId=`
- Null: `?customerId=null`
**cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer.
- Single (partial match, case-insensitive): `?cardHolderName=`
- Multiple: `?cardHolderName=&cardHolderName=`
- Null: `?cardHolderName=null`
**cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
- Single (partial match, case-insensitive): `?cardHolderZip=`
- Multiple: `?cardHolderZip=&cardHolderZip=`
- Null: `?cardHolderZip=null`
**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.
- Single (partial match, case-insensitive): `?platform=`
- Multiple: `?platform=&platform=`
- Null: `?platform=null`
**cardInfo** (`Object`): A Json value to store the card details of the payment method.
- Single: `?cardInfo=`
- Multiple: `?cardInfo=&cardInfo=`
- Null: `?cardInfo=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId**
```js
axios({
method: 'GET',
url: `/v1/paymentcustomermethods/${userId}`,
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// paymentMethodId: '' // Filter by paymentMethodId
// customerId: '' // Filter by customerId
// cardHolderName: '' // Filter by cardHolderName
// cardHolderZip: '' // Filter by cardHolderZip
// platform: '' // Filter by platform
// cardInfo: '' // Filter by cardInfo
}
});
```
**REST Response**
```json
{
"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": []
}
```
### `_fetch Listlisting` API
System API to fetch list of listing records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListListing` API REST controller can be triggered via the following route:
`/v1/_fetchlistlisting`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListListing` api supports 14 optional filter parameters for filtering list results:
**categoryId** (`ID`): Main category for the listing (categoryLocation:category).
- Single: `?categoryId=`
- Multiple: `?categoryId=&categoryId=`
- Null: `?categoryId=null`
**condition** (`Enum`): Item condition: new, used, other.
- Single: `?condition=` (case-insensitive)
- Multiple: `?condition=&condition=`
- Null: `?condition=null`
**expiresAt** (`Date`): UTC expiry for listing; after this, listing is automatically expired.
- Single date: `?expiresAt=2024-01-15`
- Multiple dates: `?expiresAt=2024-01-15&expiresAt=2024-01-20`
- Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-`
- Null: `?expiresAt=null`
**isPremium** (`Boolean`): If true, the listing is premium (highlighted/pinned, eligible for special placement).
- True: `?isPremium=true`
- False: `?isPremium=false`
- Null: `?isPremium=null`
**listingType** (`Enum`): Type of listing (sale, rent, service, etc.).
- Single: `?listingType=` (case-insensitive)
- Multiple: `?listingType=&listingType=`
- Null: `?listingType=null`
**locationId** (`ID`): Location (categoryLocation:location).
- Single: `?locationId=`
- Multiple: `?locationId=&locationId=`
- Null: `?locationId=null`
**premiumExpiry** (`Date`): UTC date when premium status expires. Null if not premium or not applicable.
- Single date: `?premiumExpiry=2024-01-15`
- Multiple dates: `?premiumExpiry=2024-01-15&premiumExpiry=2024-01-20`
- Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-`
- Null: `?premiumExpiry=null`
**premiumType** (`Enum`): Which premium package (gold, silver, none, etc.).
- Single: `?premiumType=` (case-insensitive)
- Multiple: `?premiumType=&premiumType=`
- Null: `?premiumType=null`
**price** (`Double`): Listing price.
- Single: `?price=`
- Multiple: `?price=&price=`
- Range: `?price=$lt-`, `$lte-`, `$gt-`, `$gte-`, `$btw--`
- Null: `?price=null`
**status** (`Enum`): Lifecycle status: pending_review, active, denied, sold, expired, deleted.
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**subcategoryId** (`ID`): Subcategory for the listing, can be null for top-level (categoryLocation:category).
- Single: `?subcategoryId=`
- Multiple: `?subcategoryId=&subcategoryId=`
- Null: `?subcategoryId=null`
**title** (`String`): Listing title, short and clear.
- Single (partial match, case-insensitive): `?title=`
- Multiple: `?title=&title=`
- Null: `?title=null`
**userId** (`ID`): Owner (poster) of the listing (auth:user).
- Single: `?userId=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks.
- Single: `?paymentConfirmation=` (case-insensitive)
- Multiple: `?paymentConfirmation=&paymentConfirmation=`
- Null: `?paymentConfirmation=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistlisting**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistlisting',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// categoryId: '' // Filter by categoryId
// condition: '' // Filter by condition
// expiresAt: '' // Filter by expiresAt
// isPremium: '' // Filter by isPremium
// listingType: '' // Filter by listingType
// locationId: '' // Filter by locationId
// premiumExpiry: '' // Filter by premiumExpiry
// premiumType: '' // Filter by premiumType
// price: '' // Filter by price
// status: '' // Filter by status
// subcategoryId: '' // Filter by subcategoryId
// title: '' // Filter by title
// userId: '' // Filter by userId
// paymentConfirmation: '' // Filter by paymentConfirmation
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listings",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"listings": [
{
"id": "ID",
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"mainCategory": [
{
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer"
},
{},
{}
],
"location": [
{
"city": "String",
"country": "String",
"district": "String",
"latitude": "Double",
"longitude": "Double",
"postalCode": "String"
},
{},
{}
],
"subCategory": [
{
"description": "Text",
"icon": "String",
"name": "String",
"parentCategoryId": "ID",
"slug": "String",
"sortOrder": "Integer"
},
{},
{}
],
"user": [
{
"fullname": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `_fetch Listsys_listingpayment` API
System API to fetch list of sys_listingPayment records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListSys_listingPayment` API REST controller can be triggered via the following route:
`/v1/_fetchlistsys_listingpayment`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListSys_listingPayment` api supports 6 optional filter parameters for filtering list results:
**ownerId** (`ID`): An ID value to represent owner user who created the order
- Single: `?ownerId=`
- Multiple: `?ownerId=&ownerId=`
- Null: `?ownerId=null`
**orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source listing object
- Single: `?orderId=`
- Multiple: `?orderId=&orderId=`
- Null: `?orderId=null`
**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
- Single (partial match, case-insensitive): `?paymentId=`
- Multiple: `?paymentId=&paymentId=`
- Null: `?paymentId=null`
**paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
- Single (partial match, case-insensitive): `?paymentStatus=`
- Multiple: `?paymentStatus=&paymentStatus=`
- Null: `?paymentStatus=null`
**statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself.
- Single (partial match, case-insensitive): `?statusLiteral=`
- Multiple: `?statusLiteral=&statusLiteral=`
- Null: `?statusLiteral=null`
**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.
- Single (partial match, case-insensitive): `?redirectUrl=`
- Multiple: `?redirectUrl=&redirectUrl=`
- Null: `?redirectUrl=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistsys_listingpayment**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistsys_listingpayment',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// ownerId: '' // Filter by ownerId
// orderId: '' // Filter by orderId
// paymentId: '' // Filter by paymentId
// paymentStatus: '' // Filter by paymentStatus
// statusLiteral: '' // Filter by statusLiteral
// redirectUrl: '' // Filter by redirectUrl
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_listingPayments",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"sys_listingPayments": [
{
"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": []
}
```
### `_fetch Listsys_paymentcustomer` API
System API to fetch list of sys_paymentCustomer records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListSys_paymentCustomer` API REST controller can be triggered via the following route:
`/v1/_fetchlistsys_paymentcustomer`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListSys_paymentCustomer` 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
- Single: `?userId=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**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
- Single (partial match, case-insensitive): `?customerId=`
- Multiple: `?customerId=&customerId=`
- Null: `?customerId=null`
**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.
- Single (partial match, case-insensitive): `?platform=`
- Multiple: `?platform=&platform=`
- Null: `?platform=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistsys_paymentcustomer**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistsys_paymentcustomer',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// customerId: '' // Filter by customerId
// platform: '' // Filter by platform
}
});
```
**REST Response**
```json
{
"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": []
}
```
### `_fetch Listsys_paymentmethod` API
System API to fetch list of sys_paymentMethod records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListSys_paymentMethod` API REST controller can be triggered via the following route:
`/v1/_fetchlistsys_paymentmethod`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListSys_paymentMethod` api supports 7 optional filter parameters for filtering list results:
**paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform.
- Single (partial match, case-insensitive): `?paymentMethodId=`
- Multiple: `?paymentMethodId=&paymentMethodId=`
- Null: `?paymentMethodId=null`
**userId** (`ID`): An ID value to represent the user who owns the payment method
- Single: `?userId=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway.
- Single (partial match, case-insensitive): `?customerId=`
- Multiple: `?customerId=&customerId=`
- Null: `?customerId=null`
**cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer.
- Single (partial match, case-insensitive): `?cardHolderName=`
- Multiple: `?cardHolderName=&cardHolderName=`
- Null: `?cardHolderName=null`
**cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
- Single (partial match, case-insensitive): `?cardHolderZip=`
- Multiple: `?cardHolderZip=&cardHolderZip=`
- Null: `?cardHolderZip=null`
**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.
- Single (partial match, case-insensitive): `?platform=`
- Multiple: `?platform=&platform=`
- Null: `?platform=null`
**cardInfo** (`Object`): A Json value to store the card details of the payment method.
- Single: `?cardInfo=`
- Multiple: `?cardInfo=&cardInfo=`
- Null: `?cardInfo=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistsys_paymentmethod**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistsys_paymentmethod',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// paymentMethodId: '' // Filter by paymentMethodId
// userId: '' // Filter by userId
// customerId: '' // Filter by customerId
// cardHolderName: '' // Filter by cardHolderName
// cardHolderZip: '' // Filter by cardHolderZip
// platform: '' // Filter by platform
// cardInfo: '' // Filter by cardInfo
}
});
```
**REST Response**
```json
{
"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": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-listingimage-service
**Version:** `1.0.1`
Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the ListingImage Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our ListingImage Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the ListingImage Service via HTTP requests for purposes such as creating, updating, deleting and querying ListingImage objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the ListingImage Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the ListingImage service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the ListingImage service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the ListingImage service.
This service is configured to listen for HTTP requests on port `3002`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/listingimage-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/listingimage-api`
* **Production:** `https://clonesahibinden.mindbricks.co/listingimage-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the ListingImage service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `ListingImage` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `ListingImage` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `ListingImage` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
ListingImage service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### ListingImage resource
*Resource Definition* : Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.
*ListingImage Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **fileSize** | Integer | | | *Size of the image file in bytes.* |
| **fullUrl** | String | | | *URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).* |
| **height** | Float | | | *Height of the original image, in pixels.* |
| **listingId** | ID | | | *The related listing that this image belongs to.* |
| **mediumUrl** | String | | | *URL to the medium-sized processed image version (e.g. 400x300px or similar).* |
| **mimeType** | String | | | *MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).* |
| **sortOrder** | Integer | | | *Order value for display in UI; the lowest value image is the cover/main image.* |
| **thumbnailUrl** | String | | | *URL to the thumbnail image (small size, e.g. 120x90px).* |
| **uploadedAt** | Date | | | *UTC timestamp when image was uploaded to platform.* |
| **url** | String | | | *URL to the original uploaded image file (full resolution/original).* |
| **width** | Float | | | *Width of the original image, in pixels.* |
## Business Api
### `Create Listingimage` API
Create an image record attached to a listing. Enforces max 10 images per listing, allowed file types (image/jpeg, png, webp, gif), max file size (10MB), and minimum dimensions (400x300px). Only owner of related listing, admin, or moderator can add.
**API Frontend Description By The Backend Architect**
Show file/image upload UI, allow per-image progress and preview, error on more than 10 images, reject unsupported types/sizes/resolutions. On success, show image in gallery. Only listing owner/moderator/admin may add images.
**Rest Route**
The `createListingImage` API REST controller can be triggered via the following route:
`/v1/listingimages`
**Rest Request Parameters**
The `createListingImage` api has got 11 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| fileSize | Integer | true | request.body?.["fileSize"] |
| fullUrl | String | true | request.body?.["fullUrl"] |
| height | Float | true | request.body?.["height"] |
| listingId | ID | true | request.body?.["listingId"] |
| mediumUrl | String | true | request.body?.["mediumUrl"] |
| mimeType | String | true | request.body?.["mimeType"] |
| sortOrder | Integer | true | request.body?.["sortOrder"] |
| thumbnailUrl | String | true | request.body?.["thumbnailUrl"] |
| uploadedAt | Date | true | request.body?.["uploadedAt"] |
| url | String | true | request.body?.["url"] |
| width | Float | true | request.body?.["width"] |
**fileSize** : Size of the image file in bytes.
**fullUrl** : URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
**height** : Height of the original image, in pixels.
**listingId** : The related listing that this image belongs to.
**mediumUrl** : URL to the medium-sized processed image version (e.g. 400x300px or similar).
**mimeType** : MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
**sortOrder** : Order value for display in UI; the lowest value image is the cover/main image.
**thumbnailUrl** : URL to the thumbnail image (small size, e.g. 120x90px).
**uploadedAt** : UTC timestamp when image was uploaded to platform.
**url** : URL to the original uploaded image file (full resolution/original).
**width** : Width of the original image, in pixels.
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/listingimages**
```js
axios({
method: 'POST',
url: '/v1/listingimages',
data: {
fileSize:"Integer",
fullUrl:"String",
height:"Float",
listingId:"ID",
mediumUrl:"String",
mimeType:"String",
sortOrder:"Integer",
thumbnailUrl:"String",
uploadedAt:"Date",
url:"String",
width:"Float",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listingImage",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"listingImage": {
"id": "ID",
"fileSize": "Integer",
"fullUrl": "String",
"height": "Float",
"listingId": "ID",
"mediumUrl": "String",
"mimeType": "String",
"sortOrder": "Integer",
"thumbnailUrl": "String",
"uploadedAt": "Date",
"url": "String",
"width": "Float",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete Listingimage` API
Remove (soft delete) this image record. Only admin, moderator, or owner of related listing may take action. Image stays in database; actual asset removal is scheduled or handled in listing/bucket image service.
**API Frontend Description By The Backend Architect**
Provide a delete/trash icon per image. Show immediate feedback on delete (soft delete). Remove from gallery and reflow grid/order. Deletion disables but does not erase image from DB or storage bucket (handled asynchronously).
**Rest Route**
The `deleteListingImage` API REST controller can be triggered via the following route:
`/v1/listingimages/:listingImageId`
**Rest Request Parameters**
The `deleteListingImage` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingImageId | ID | true | request.params?.["listingImageId"] |
**listingImageId** : 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/listingimages/:listingImageId**
```js
axios({
method: 'DELETE',
url: `/v1/listingimages/${listingImageId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listingImage",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"listingImage": {
"id": "ID",
"fileSize": "Integer",
"fullUrl": "String",
"height": "Float",
"listingId": "ID",
"mediumUrl": "String",
"mimeType": "String",
"sortOrder": "Integer",
"thumbnailUrl": "String",
"uploadedAt": "Date",
"url": "String",
"width": "Float",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Listingimage` API
Retrieve details/metadata of one image for a listing. Publicly accessible for gallery/carousel; has no sensitive info.
**API Frontend Description By The Backend Architect**
Used to fetch image details (URLs for all resolutions and display order) for single-image views. All users can access listing image detail for active listings.
**Rest Route**
The `getListingImage` API REST controller can be triggered via the following route:
`/v1/listingimages/:listingImageId`
**Rest Request Parameters**
The `getListingImage` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingImageId | ID | true | request.params?.["listingImageId"] |
**listingImageId** : 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/listingimages/:listingImageId**
```js
axios({
method: 'GET',
url: `/v1/listingimages/${listingImageId}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listingImage",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"listingImage": {
"isActive": true
}
}
```
### `List Listingimages` API
List all images belonging to a specific listing, sorted by sortOrder ascending. Returns up to 10 images per listing. Publicly accessible for populating image galleries.
**API Frontend Description By The Backend Architect**
Display all images in a listing as a gallery or carousel, sorted by sortOrder (lowest/1 is main image/cover). Maximum images per listing is 10. Used on public listing detail pages and for listing management.
**Rest Route**
The `listListingImages` API REST controller can be triggered via the following route:
`/v1/listlistingimages/:listingId`
**Rest Request Parameters**
The `listListingImages` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.query?.["listingId"] |
**listingId** : The related listing that this image belongs to.. The parameter is used to query data.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/listlistingimages/:listingId**
```js
axios({
method: 'GET',
url: `/v1/listlistingimages/${listingId}`,
data: {
},
params: {
listingId:'"ID"',
}
});
```
**REST Response**
This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listingImages",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"listingImages": [
{
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Update Listingimage` API
Update sort order or image metadata; user is limited to manipulating images of their own listings (or admins/mods). Cannot move image to another listing. Can revalidate constraints on request.
**API Frontend Description By The Backend Architect**
Allow user to reorder images of a listing (changing sortOrder), set another main image (sortOrder=1), or update image metadata. Show error if trying to move image between listings or violate constraints.
**Rest Route**
The `updateListingImage` API REST controller can be triggered via the following route:
`/v1/listingimages/:listingImageId`
**Rest Request Parameters**
The `updateListingImage` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingImageId | ID | true | request.params?.["listingImageId"] |
| sortOrder | Integer | false | request.body?.["sortOrder"] |
**listingImageId** : This id paremeter is used to select the required data object that will be updated
**sortOrder** : Order value for display in UI; the lowest value image is the cover/main image.
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/listingimages/:listingImageId**
```js
axios({
method: 'PATCH',
url: `/v1/listingimages/${listingImageId}`,
data: {
sortOrder:"Integer",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listingImage",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"listingImage": {
"id": "ID",
"fileSize": "Integer",
"fullUrl": "String",
"height": "Float",
"listingId": "ID",
"mediumUrl": "String",
"mimeType": "String",
"sortOrder": "Integer",
"thumbnailUrl": "String",
"uploadedAt": "Date",
"url": "String",
"width": "Float",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `_fetch Listlistingimage` API
System API to fetch list of listingImage records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListListingImage` API REST controller can be triggered via the following route:
`/v1/_fetchlistlistingimage`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListListingImage` api supports 1 optional filter parameter for filtering list results:
**listingId** (`ID`): The related listing that this image belongs to.
- Single: `?listingId=`
- Multiple: `?listingId=&listingId=`
- Null: `?listingId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistlistingimage**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistlistingimage',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// listingId: '' // Filter by listingId
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "listingImages",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"listingImages": [
{
"id": "ID",
"fileSize": "Integer",
"fullUrl": "String",
"height": "Float",
"listingId": "ID",
"mediumUrl": "String",
"mimeType": "String",
"sortOrder": "Integer",
"thumbnailUrl": "String",
"uploadedAt": "Date",
"url": "String",
"width": "Float",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"listing": [
{
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-payment-service
**Version:** `1.0.2`
Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the Payment Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Payment Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the Payment Service via HTTP requests for purposes such as creating, updating, deleting and querying Payment objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the Payment Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the Payment service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the Payment service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Payment service.
This service is configured to listen for HTTP requests on port `3002`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/payment-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/payment-api`
* **Production:** `https://clonesahibinden.mindbricks.co/payment-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the Payment service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `Payment` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Payment` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `Payment` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
Payment service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### PaymentTransaction resource
*Resource Definition* : Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.
*PaymentTransaction Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **amount** | Double | | | *Payment amount for selected premiumType, in target currency.* |
| **currency** | String | | | *Currency in ISO-4217 format (e.g., 'TRY','USD') used for Stripe checkout.* |
| **listingId** | ID | | | *Target classified listing being upgraded to premium.* |
| **paymentConfirmedAt** | Date | | | *Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.* |
| **premiumType** | Enum | | | *Premium upgrade package: bronze, silver, gold (matches frontend/listing options).* |
| **status** | Enum | | | *Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).* |
| **stripeEventId** | String | | | *Last Stripe event webhook ID processed for this payment (used for double-spend/deduplication of webhook).* |
| **stripeSessionId** | String | | | *Stripe Checkout Session ID associated with this payment (used for reconciling gateway callbacks).* |
| **userId** | ID | | | *User (buyer) who made the payment (auth:user)* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### premiumType Enum Property
*Property Definition* : Premium upgrade package: bronze, silver, gold (matches frontend/listing options).*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **bronze** | `"bronze""` | 0 |
| **silver** | `"silver""` | 1 |
| **gold** | `"gold""` | 2 |
##### status Enum Property
*Property Definition* : Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **pending** | `"pending""` | 0 |
| **awaiting_confirmation** | `"awaiting_confirmation""` | 1 |
| **success** | `"success""` | 2 |
| **failed** | `"failed""` | 3 |
| **canceled** | `"canceled""` | 4 |
## Business Api
### `Create Paymenttransaction` API
Create a paymentTransaction to initiate a Stripe Checkout for premium upgrade on a listing. Checks listing and user, prevents duplicate active payments, creates transaction with status='pending', triggers Stripe checkout, and returns checkout session URL/info.
**API Frontend Description By The Backend Architect**
# Initiate Premium Payment
- Use to start payment for a premium listing upgrade. Must supply: listingId, premiumType.
- Only one pending/awaiting/successful payment per listing/user/premiumType allowed.
- Returns Stripe checkout URL/session info in response for frontend redirect.
**Rest Route**
The `createPaymentTransaction` API REST controller can be triggered via the following route:
`/v1/payments/create`
**Rest Request Parameters**
The `createPaymentTransaction` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| listingId | ID | true | request.body?.["listingId"] |
| premiumType | String | true | request.body?.["premiumType"] |
**listingId** : ID of the listing to upgrade to premium
**premiumType** : PremiumType to purchase ('bronze', 'silver', 'gold')
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/payments/create**
```js
axios({
method: 'POST',
url: '/v1/payments/create',
data: {
listingId:"ID",
premiumType:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "paymentTransaction",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"paymentTransaction": {
"id": "ID",
"amount": "Double",
"currency": "String",
"listingId": "ID",
"paymentConfirmedAt": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"status": "Enum",
"status_idx": "Integer",
"stripeEventId": "String",
"stripeSessionId": "String",
"userId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": true
},
"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 Paymenttransaction` API
Retrieve a paymentTransaction by ID. Only owner or admin may access. Used for order confirmation display, receipt, etc.
**API Frontend Description By The Backend Architect**
- Retrieves a single payment history entry (premium upgrade). Only accessible by creator or admin.
**Rest Route**
The `getPaymentTransaction` API REST controller can be triggered via the following route:
`/v1/payments/:id`
**Rest Request Parameters**
The `getPaymentTransaction` api has got 2 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| paymentTransactionId | ID | true | request.params?.["paymentTransactionId"] |
| id | String | true | request.params?.["id"] |
**paymentTransactionId** : This id paremeter is used to query the required data object.
**id** : This parameter will be used to select the data object that is queried
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/payments/:id**
```js
axios({
method: 'GET',
url: `/v1/payments/${id}`,
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "paymentTransaction",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"paymentTransaction": {
"listingInfo": {
"categoryId": "ID",
"isPremium": "Boolean",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"subcategoryId": "ID",
"title": "String"
},
"isActive": true
}
}
```
### `List Paymenttransactions` API
List all paymentTransactions for current user, paginated. Admin can query all users. Used for user payment history and admin reconciliation.
**API Frontend Description By The Backend Architect**
- Shows payment history rows for logged-in user. Admin can access all or filter by user/listing.
- For normal users, always filtered to session.userId.
**Rest Route**
The `listPaymentTransactions` API REST controller can be triggered via the following route:
`/v1/payments`
**Rest Request Parameters**
The `listPaymentTransactions` api has got no request parameters.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/payments**
```js
axios({
method: 'GET',
url: '/v1/payments',
data: {
},
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.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "paymentTransactions",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"paymentTransactions": [
{
"listingInfo": [
{
"categoryId": "ID",
"isPremium": "Boolean",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"subcategoryId": "ID",
"title": "String"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Stripe Webhookcallback` API
Receives Stripe webhook events, updates corresponding paymentTransaction (status, confirmation), triggers listing premium upgrade via interservice call. Only accepts trusted Stripe event payloads. No login required.
**API Frontend Description By The Backend Architect**
- INTERNAL USE ONLY. Called by Stripe, not by user. Receives POSTed webhook from Stripe.
- Verifies event with Stripe secret. Updates paymentTransaction record matched via sessionId. If payment is successful, confirms premium upgrade in listing service.
**Rest Route**
The `stripeWebhookCallback` API REST controller can be triggered via the following route:
`/v1/payments/webhook`
**Rest Request Parameters**
The `stripeWebhookCallback` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| paymentTransactionId | ID | true | request.params?.["paymentTransactionId"] |
**paymentTransactionId** : 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/payments/webhook**
```js
axios({
method: 'POST',
url: '/v1/payments/webhook',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "paymentTransaction",
"method": "POST",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"paymentTransaction": {
"id": "ID",
"amount": "Double",
"currency": "String",
"listingId": "ID",
"paymentConfirmedAt": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"status": "Enum",
"status_idx": "Integer",
"stripeEventId": "String",
"stripeSessionId": "String",
"userId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": true
}
}
```
### `_fetch Listpaymenttransaction` API
System API to fetch list of paymentTransaction records for frontend application. Auto-generated, not visible in design.
**Rest Route**
The `_fetchListPaymentTransaction` API REST controller can be triggered via the following route:
`/v1/_fetchlistpaymenttransaction`
**Rest Request Parameters**
**Filter Parameters**
The `_fetchListPaymentTransaction` api supports 5 optional filter parameters for filtering list results:
**listingId** (`ID`): Target classified listing being upgraded to premium.
- Single: `?listingId=`
- Multiple: `?listingId=&listingId=`
- Null: `?listingId=null`
**paymentConfirmedAt** (`Date`): Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
- Single date: `?paymentConfirmedAt=2024-01-15`
- Multiple dates: `?paymentConfirmedAt=2024-01-15&paymentConfirmedAt=2024-01-20`
- Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-`
- Null: `?paymentConfirmedAt=null`
**premiumType** (`Enum`): Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
- Single: `?premiumType=` (case-insensitive)
- Multiple: `?premiumType=&premiumType=`
- Null: `?premiumType=null`
**status** (`Enum`): Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**userId** (`ID`): User (buyer) who made the payment (auth:user)
- Single: `?userId=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/_fetchlistpaymenttransaction**
```js
axios({
method: 'GET',
url: '/v1/_fetchlistpaymenttransaction',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// listingId: '' // Filter by listingId
// paymentConfirmedAt: '' // Filter by paymentConfirmedAt
// premiumType: '' // Filter by premiumType
// status: '' // Filter by status
// userId: '' // Filter by userId
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "paymentTransactions",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"paymentTransactions": [
{
"id": "ID",
"amount": "Double",
"currency": "String",
"listingId": "ID",
"paymentConfirmedAt": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"status": "Enum",
"status_idx": "Integer",
"stripeEventId": "String",
"stripeSessionId": "String",
"userId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"listing": [
{
"attributes": "Object",
"categoryId": "ID",
"condition": "Enum",
"condition_idx": "Integer",
"contactEmail": "String",
"contactPhone": "String",
"currency": "String",
"description": "Text",
"expiresAt": "Date",
"favoriteCount": "Integer",
"isPremium": "Boolean",
"listingType": "Enum",
"listingType_idx": "Integer",
"locationId": "ID",
"_paymentConfirmation": "String",
"premiumExpiry": "Date",
"premiumType": "Enum",
"premiumType_idx": "Integer",
"price": "Double",
"status": "Enum",
"status_idx": "Integer",
"subcategoryId": "ID",
"title": "String",
"userId": "ID",
"viewsCount": "Integer",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer"
},
{},
{}
],
"buyer": [
{
"fullname": "String"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"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",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## clonesahibinden-auth-service
**Version:** `1.0.5`
Authentication service for the project
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the Auth Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Auth Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the Auth Service via HTTP requests for purposes such as creating, updating, deleting and querying Auth objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the Auth Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the Auth service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | clonesahibinden-access-token|
| Cookie | clonesahibinden-access-token|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the Auth service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Auth service.
This service is configured to listen for HTTP requests on port `3011`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://clonesahibinden.prw.mindbricks.com/auth-api`
* **Staging:** `https://clonesahibinden-stage.mindbricks.co/auth-api`
* **Production:** `https://clonesahibinden.mindbricks.co/auth-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the Auth service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `Auth` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Auth` service.
### 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 within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `Auth` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"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": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
Auth service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### User resource
*Resource Definition* : A data object that stores the user information and handles login settings.
*User Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **email** | String | | | * A string value to represent the user's email.* |
| **password** | String | | | * A string value to represent the user's password. It will be stored as hashed.* |
| **fullname** | String | | | *A string value to represent the fullname of the user* |
| **avatar** | String | | | *The avatar url of the user. A random avatar will be generated if not provided* |
| **roleId** | String | | | *A string value to represent the roleId of the user.* |
| **mobile** | String | | | *A string value to represent the user's mobile number.* |
| **mobileVerified** | Boolean | | | *A boolean value to represent the mobile verification status of the user.* |
| **emailVerified** | Boolean | | | *A boolean value to represent the email verification status of the user.* |
| **userType** | Enum | | | *Indicates whether the user is an individual or a corporate account.* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### userType Enum Property
*Property Definition* : Indicates whether the user is an individual or a corporate account.*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **individual** | `"individual""` | 0 |
| **corporate** | `"corporate""` | 1 |
## Business 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**
```js
axios({
method: 'GET',
url: `/v1/users/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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",
"mobile": "String",
"mobileVerified": "Boolean",
"emailVerified": "Boolean",
"userType": "Enum",
"userType_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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 5 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"] |
| mobile | String | false | request.body?.["mobile"] |
| userType | Enum | false | request.body?.["userType"] |
**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
**mobile** : A string value to represent the user's mobile number.
**userType** : Indicates whether the user is an individual or a corporate account.
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/users/:userId**
```js
axios({
method: 'PATCH',
url: `/v1/users/${userId}`,
data: {
fullname:"String",
avatar:"String",
mobile:"String",
userType:"Enum",
},
params: {
}
});
```
**REST Response**
```json
{
"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",
"mobile": "String",
"mobileVerified": "Boolean",
"emailVerified": "Boolean",
"userType": "Enum",
"userType_idx": "Integer",
"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 5 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"] |
| mobile | String | false | request.body?.["mobile"] |
| userType | Enum | false | request.body?.["userType"] |
**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
**mobile** : A string value to represent the user's mobile number.
**userType** : Indicates whether the user is an individual or a corporate account.
**REST Request**
To access the api you can use the **REST** controller with the path **PATCH /v1/profile/:userId**
```js
axios({
method: 'PATCH',
url: `/v1/profile/${userId}`,
data: {
fullname:"String",
avatar:"String",
mobile:"String",
userType:"Enum",
},
params: {
}
});
```
**REST Response**
```json
{
"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",
"mobile": "String",
"mobileVerified": "Boolean",
"emailVerified": "Boolean",
"userType": "Enum",
"userType_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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 6 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"] |
| mobile | String | false | request.body?.["mobile"] |
| userType | Enum | false | request.body?.["userType"] |
**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
**mobile** : A string value to represent the user's mobile number.
**userType** : Indicates whether the user is an individual or a corporate account.
**REST Request**
To access the api you can use the **REST** controller with the path **POST /v1/users**
```js
axios({
method: 'POST',
url: '/v1/users',
data: {
avatar:"String",
email:"String",
password:"String",
fullname:"String",
mobile:"String",
userType:"Enum",
},
params: {
}
});
```
**REST Response**
```json
{
"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",
"mobile": "String",
"mobileVerified": "Boolean",
"emailVerified": "Boolean",
"userType": "Enum",
"userType_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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**
```js
axios({
method: 'DELETE',
url: `/v1/users/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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",
"mobile": "String",
"mobileVerified": "Boolean",
"emailVerified": "Boolean",
"userType": "Enum",
"userType_idx": "Integer",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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**
```js
axios({
method: 'DELETE',
url: `/v1/archiveprofile/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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",
"mobile": "String",
"mobileVerified": "Boolean",
"emailVerified": "Boolean",
"userType": "Enum",
"userType_idx": "Integer",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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 4 optional filter parameters for filtering list results:
**email** (`String`): A string value to represent the user's email.
- Single (partial match, case-insensitive): `?email=`
- Multiple: `?email=&email=`
- Null: `?email=null`
**fullname** (`String`): A string value to represent the fullname of the user
- Single (partial match, case-insensitive): `?fullname=`
- Multiple: `?fullname=&fullname=`
- Null: `?fullname=null`
**roleId** (`String`): A string value to represent the roleId of the user.
- Single (partial match, case-insensitive): `?roleId=`
- Multiple: `?roleId=&roleId=`
- Null: `?roleId=null`
**mobile** (`String`): A string value to represent the user's mobile number.
- Single (partial match, case-insensitive): `?mobile=`
- Multiple: `?mobile=