# LinkedIn Clone - REST API Reference > Complete REST API documentation for all services in LinkedIn Clone 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) - [Auth Service REST API](#auth-service-rest-api-guide) - [JobApplication Service REST API](#jobapplication-service-rest-api-guide) - [Networking Service REST API](#networking-service-rest-api-guide) - [Company Service REST API](#company-service-rest-api-guide) - [Content Service REST API](#content-service-rest-api-guide) - [Messaging Service REST API](#messaging-service-rest-api-guide) - [Profile Service REST API](#profile-service-rest-api-guide) - [AgentHub Service REST API](#agenthub-service-rest-api-guide) - [Bff Service REST API](#bff-service-rest-api-guide) - [Notification Service REST API](#notification-service-rest-api-guide) --- ## Introduction # LinkedIn Clone Version : 1.0.2 This project's structure and ideas are the same as he real linkedIn webiste ## How to Use Project Documents The `Linkedin` 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://linkedin.prw.mindbricks.com/auth-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/auth-api` | | **Production** | `https://linkedin.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 `Linkedin` 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 `LinkedIn Clone` 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 ### jobApplication Service **Description:** Microservice handling job postings (created by recruiters/company admins), job applications (created by users), allowing job search, application submission, and status update workflows. Enforces business rules around application status, admin controls, and lets professionals apply and track job applications .within the network. **Documentation:** * [REST API Guide](/document/docs/jobApplication-service/rest-api-guide.html) * [Event Guide](/document/docs/jobApplication-service/event-guide.html) * [Service Design](/document/docs/jobApplication-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/jobapplication-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/jobapplication-api` | | **Production** | `https://linkedin.mindbricks.co/jobapplication-api` | ### networking Service **Description:** Handles professional networking logic for user-to-user connections: manages connection requests, accepted relationships, listing/removal, permissions, and state transitions. Publishes connection lifecycle events for notification... **Documentation:** * [REST API Guide](/document/docs/networking-service/rest-api-guide.html) * [Event Guide](/document/docs/networking-service/event-guide.html) * [Service Design](/document/docs/networking-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/networking-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/networking-api` | | **Production** | `https://linkedin.mindbricks.co/networking-api` | ### company Service **Description:** Handles company profiles, company admin assignments, company following, and posting company updates/news. Enables professionals to follow companies, get updates, and enables admins to manage company presence.. **Documentation:** * [REST API Guide](/document/docs/company-service/rest-api-guide.html) * [Event Guide](/document/docs/company-service/event-guide.html) * [Service Design](/document/docs/company-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/company-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/company-api` | | **Production** | `https://linkedin.mindbricks.co/company-api` | ### content Service **Description:** Handles creation, editing, and deletion of user posts (with attachments and visibility), user post feed aggregation, and post engagement (likes, comments). All with post-level visibility control (public/private).. **Documentation:** * [REST API Guide](/document/docs/content-service/rest-api-guide.html) * [Event Guide](/document/docs/content-service/event-guide.html) * [Service Design](/document/docs/content-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/content-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/content-api` | | **Production** | `https://linkedin.mindbricks.co/content-api` | ### messaging Service **Description:** Handles direct, private 1:1 and group messaging between users, conversation management, and message history/storage.. **Documentation:** * [REST API Guide](/document/docs/messaging-service/rest-api-guide.html) * [Event Guide](/document/docs/messaging-service/event-guide.html) * [Service Design](/document/docs/messaging-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/messaging-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/messaging-api` | | **Production** | `https://linkedin.mindbricks.co/messaging-api` | ### profile Service **Description:** Handles user professional profiles, including experience, education, skills, languages, certifications, profile photo, and visibility controls. Enables recruiter search, elastic-style indexing, and profile editing, with all data linked to authenticated users.. **Documentation:** * [REST API Guide](/document/docs/profile-service/rest-api-guide.html) * [Event Guide](/document/docs/profile-service/event-guide.html) * [Service Design](/document/docs/profile-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/profile-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/profile-api` | | **Production** | `https://linkedin.mindbricks.co/profile-api` | ### agentHub Service **Description:** AI Agent Hub **Documentation:** * [REST API Guide](/document/docs/agentHub-service/rest-api-guide.html) * [Event Guide](/document/docs/agentHub-service/event-guide.html) * [Service Design](/document/docs/agentHub-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/agenthub-api` | | **Staging** | `https://linkedin-stage.mindbricks.co/agenthub-api` | | **Production** | `https://linkedin.mindbricks.co/agenthub-api` | ## Connect via MCP (Model Context Protocol) All backend services in the `Linkedin` project expose their Business APIs as **MCP tools**. These tools are aggregated by the **MCP-BFF** service into a single unified endpoint that external AI tools can connect to. ### Unified MCP Endpoint | Environment | StreamableHTTP (recommended) | SSE (legacy fallback) | |-------------|------------------------------|------------------------| | **Preview** | `https://linkedin.prw.mindbricks.com/mcpbff-api/mcp` | `https://linkedin.prw.mindbricks.com/mcpbff-api/mcp/sse` | | **Staging** | `https://linkedin-stage.mindbricks.co/mcpbff-api/mcp` | `https://linkedin-stage.mindbricks.co/mcpbff-api/mcp/sse` | | **Production** | `https://linkedin.mindbricks.co/mcpbff-api/mcp` | `https://linkedin.mindbricks.co/mcpbff-api/mcp/sse` | ### Authentication MCP connections require authentication via the `Authorization` header: - **API Key (recommended for AI agents):** `Authorization: Bearer sk_mbx_your_api_key_here` API keys are long-lived and don't expire like JWT tokens. Create one from the profile page. - **JWT Token:** `Authorization: Bearer {accessToken}` Use a valid access token obtained from the login API. > **OAuth is not supported** for MCP connections at this time. ### Connecting from Cursor Add the following to your project's `.cursor/mcp.json`: ```json { "mcpServers": { "linkedin": { "url": "https://linkedin.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer sk_mbx_your_api_key_here" } } } } ``` ### Connecting from Claude Desktop Add to your Claude Desktop configuration (`claude_desktop_config.json`): ```json { "mcpServers": { "linkedin": { "url": "https://linkedin.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer sk_mbx_your_api_key_here" } } } } ``` ### What's Available Once connected, the AI tool can discover and call all Business API tools from all services — CRUD operations, custom queries, file operations, and more. The MCP-BFF handles routing each tool call to the correct backend service and propagates your authentication context. --- ## Conclusion This documentation set provides a comprehensive guide for understanding and consuming the `LinkedIn Clone` 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 ## linkedin-auth-service **Version:** `1.0.1` 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 | linkedin-access-token| | Cookie | linkedin-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://linkedin.prw.mindbricks.com/auth-api` * **Staging:** `https://linkedin-stage.mindbricks.co/auth-api` * **Production:** `https://linkedin.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.* | | **emailVerified** | Boolean | | | *A boolean value to represent the email verification status of the user.* | ### UserAvatarsFile resource *Resource Definition* : Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. *UserAvatarsFile Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **fileName** | String | | | *Original file name as uploaded by the client.* | | **mimeType** | String | | | *MIME type of the uploaded file (e.g., image/png, application/pdf).* | | **fileSize** | Integer | | | *File size in bytes.* | | **accessKey** | String | | | *12-character random key for shareable access. Auto-generated on upload.* | | **ownerId** | ID | | | *ID of the user who uploaded the file (from session).* | | **fileData** | Blob | | | *Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.* | | **metadata** | Object | | | *Optional JSON metadata for the file (tags, alt text, etc.).* | | **userId** | ID | | | *Reference to the owner user record.* | ## 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", "emailVerified": "Boolean", "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 3 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"] | **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 **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", }, 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", "emailVerified": "Boolean", "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 3 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"] | **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 **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", }, 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", "emailVerified": "Boolean", "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 4 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"] | **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 **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", }, 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", "emailVerified": "Boolean", "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", "emailVerified": "Boolean", "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", "emailVerified": "Boolean", "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 3 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` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users** ```js axios({ method: 'GET', url: '/v1/users', data: { }, params: { // Filter parameters (see Filter Parameters section above) // email: '' // Filter by email // fullname: '' // Filter by fullname // roleId: '' // Filter by roleId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Search Users` API The list of users is filtered by the tenantId. **Rest Route** The `searchUsers` API REST controller can be triggered via the following route: `/v1/searchusers` **Rest Request Parameters** The `searchUsers` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | keyword | String | true | request.query?.["keyword"] | **keyword** : **Filter Parameters** The `searchUsers` api supports 1 optional filter parameter for filtering list results: **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/searchusers** ```js axios({ method: 'GET', url: '/v1/searchusers', data: { }, params: { keyword:'"String"', // Filter parameters (see Filter Parameters section above) // roleId: '' // Filter by roleId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Userrole` API This route is used by admin roles to update the user role.The default role is user when a user is registered. A user's role can be updated by superAdmin or admin **Rest Route** The `updateUserRole` API REST controller can be triggered via the following route: `/v1/userrole/:userId` **Rest Request Parameters** The `updateUserRole` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | roleId | String | true | request.body?.["roleId"] | **userId** : This id paremeter is used to select the required data object that will be updated **roleId** : The new roleId of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userrole/:userId** ```js axios({ method: 'PATCH', url: `/v1/userrole/${userId}`, data: { roleId:"String", }, 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", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpassword` API This route is used to update the password of users in the profile page by users themselves **Rest Route** The `updateUserPassword` API REST controller can be triggered via the following route: `/v1/userpassword/:userId` **Rest Request Parameters** The `updateUserPassword` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | oldPassword | String | true | request.body?.["oldPassword"] | | newPassword | String | true | request.body?.["newPassword"] | **userId** : This id paremeter is used to select the required data object that will be updated **oldPassword** : The old password of the user that will be overridden bu the new one. Send for double check. **newPassword** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpassword/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpassword/${userId}`, data: { oldPassword:"String", newPassword:"String", }, 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", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpasswordbyadmin` API This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords **Rest Route** The `updateUserPasswordByAdmin` API REST controller can be triggered via the following route: `/v1/userpasswordbyadmin/:userId` **Rest Request Parameters** The `updateUserPasswordByAdmin` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | password | String | true | request.body?.["password"] | **userId** : This id paremeter is used to select the required data object that will be updated **password** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpasswordbyadmin/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpasswordbyadmin/${userId}`, data: { password:"String", }, 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", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Briefuser` API This route is used by public to get simple user profile information. **Rest Route** The `getBriefUser` API REST controller can be triggered via the following route: `/v1/briefuser/:userId` **Rest Request Parameters** The `getBriefUser` 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/briefuser/:userId** ```js axios({ method: 'GET', url: `/v1/briefuser/${userId}`, 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": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "isActive": true } } ``` ### `Stream Test` API Test API for iterator action streaming via SSE. **Rest Route** The `streamTest` API REST controller can be triggered via the following route: `/v1/streamtest/:userId` **Rest Request Parameters** The `streamTest` 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/streamtest/:userId** ```js axios({ method: 'GET', url: `/v1/streamtest/${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", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Register User` API This api is used by public users to register themselves **Rest Route** The `registerUser` API REST controller can be triggered via the following route: `/v1/registeruser` **Rest Request Parameters** The `registerUser` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | email | String | true | request.body?.["email"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **password** : The password defined by the the user that is being registered. **fullname** : The fullname defined by the the user that is being registered. **email** : The email defined by the the user that is being registered. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/registeruser** ```js axios({ method: 'POST', url: '/v1/registeruser', data: { avatar:"String", password:"String", fullname:"String", email:"String", }, 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", "emailVerified": "Boolean", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Useravatarsfile` API **[Default get API]** — This is the designated default `get` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getUserAvatarsFile` API REST controller can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` **Rest Request Parameters** The `getUserAvatarsFile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | **userAvatarsFileId** : 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/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'GET', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Useravatarsfiles` API **[Default list API]** — This is the designated default `list` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listUserAvatarsFiles` API REST controller can be triggered via the following route: `/v1/useravatarsfiles` **Rest Request Parameters** **Filter Parameters** The `listUserAvatarsFiles` api supports 3 optional filter parameters for filtering list results: **mimeType** (`String`): MIME type of the uploaded file (e.g., image/png, application/pdf). - Single (partial match, case-insensitive): `?mimeType=` - Multiple: `?mimeType=&mimeType=` - Null: `?mimeType=null` **ownerId** (`ID`): ID of the user who uploaded the file (from session). - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **userId** (`ID`): Reference to the owner user record. - 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/useravatarsfiles** ```js axios({ method: 'GET', url: '/v1/useravatarsfiles', data: { }, params: { // Filter parameters (see Filter Parameters section above) // mimeType: '' // Filter by mimeType // ownerId: '' // Filter by ownerId // 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": "userAvatarsFiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userAvatarsFiles": [ { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Delete Useravatarsfile` API **[Default delete API]** — This is the designated default `delete` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteUserAvatarsFile` API REST controller can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` **Rest Request Parameters** The `deleteUserAvatarsFile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | **userAvatarsFileId** : 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/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'DELETE', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### Authentication Specific Routes ### Route: login *Route Definition*: Handles the login process by verifying user credentials and generating an authenticated session. *Route Type*: login *Access Routes*: - `GET /login`: Returns the HTML login page (not a frontend module, typically used in browser-based contexts for test purpose to make sending POST /login easier). - `POST /login`: Accepts credentials, verifies the user, creates a session, and returns a JWT access token. #### Parameters | Parameter | Type | Required | Population | |-------------|----------|----------|-----------------------------| | username | String | Yes | `request.body.username` | | password | String | Yes | `request.body.password` | #### Notes - This route accepts login credentials and creates an authenticated session if credentials are valid. - On success, the response will: - Set a cookie named `projectname-access-token[-tenantCodename]` with the JWT token. - Include the token in the response headers under the same name. - Return the full `session` object in the JSON body. - Note that `username` parameter should have the email of the user as value. You can also send an `email` parameter instead of `username` parameter. If both sent only `username` parameter will be read. ```js // Sample POST /login call axios.post("/login", { username: "user@example.com", password: "securePassword" }); ```` **Success Response** Returns the authenticated session object with a status code `200 OK`. A secure HTTP-only cookie and an access token header are included in the response. ```json { "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", ... } ```` **Error Responses** * **401 Unauthorized:** Invalid username or password. * **403 Forbidden:** Login attempt rejected due to pending email/mobile verification or 2FA requirements. * **400 Bad Request:** Missing credentials in the request. ### Route: logout *Route Definition*: Logs the user out by terminating the current session and clearing the access token. *Route Type*: logout *Access Route*: `POST /logout` #### Parameters This route does not require any parameters in the body or query. #### Behavior - Invalidates the current session on the server (if stored). - Clears the access token cookie (`projectname-access-token[-tenantCodename]`) from the client. - Responds with a 200 status and a simple confirmation object. ```js // Sample POST /logout call axios.post("/logout", {}, { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Notes** * This route is public, meaning it can be called without a session or token. * If the session is active, the server will clear associated session state and cookies. * The logout behavior may vary slightly depending on whether you're using cookie-based or header-based token management. **Error Responses** 00200 OK:** Always returned, regardless of whether a session existed. Logout is treated as idempotent. ### Route: publickey *Route Definition*: Returns the public RSA key used to verify JWT access tokens issued by the auth service. *Route Type*: publicKeyFetch *Access Route*: `GET /publickey` #### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|--------------------| | keyId | String | No | `request.query.keyId` | - `keyId` is optional. If provided, retrieves the public key corresponding to the specific `keyId`. If omitted, retrieves the current active public key (`global.currentKeyId`). #### Behavior - Reads the requested RSA public key file from the server filesystem. - If the key exists, returns it along with its `keyId`. - If the key does not exist, returns a 404 error. ```js // Sample GET /publickey call axios.get("/publickey", { params: { keyId: "currentKeyIdOptional" } }); ```` **Success Response** Returns the active public key and its associated keyId. ```json { "keyId": "a1b2c3d4", "keyData": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhki...\n-----END PUBLIC KEY-----" } ```` **Error Responses** **404 Not Found:** Public key file could not be found on the server. ### Token Key Management Mindbricks uses RSA key pairs to sign and verify JWT access tokens securely. While the auth service signs each token with a private key, other services within the system — or external clients — need the corresponding **public key** to verify the authenticity and integrity of received tokens. The `/publickey` endpoint allows services and clients to dynamically fetch the currently active public key, ensuring that token verification remains secure even if key rotation is performed. > **Note**: > The `/publickey` route is not intended for direct frontend (browser) consumption. > Instead, it is primarily used by trusted backend services, APIs, or middleware systems that need to independently verify access tokens issued by the auth service — without making verification-dependent API calls to the auth service itself. Accessing the public key is crucial for validating user sessions efficiently and maintaining a decentralized trust model across your platform. ### Route: relogin *Route Definition*: Performs a silent login by verifying the current access token, refreshing the session, and returning a new access token along with updated user information. *Route Type*: sessionRefresh *Access Route*: `GET /relogin` #### Parameters This route does **not** require any request parameters. #### Behavior - Validates the access token associated with the request. - If the token is valid: - Re-authenticates the user using the session's user ID. - Fetches the most up-to-date user information from the database. - Generates a new session object with a **new session ID** and **new access token**. - If the token is invalid or missing, returns a 401 Unauthorized error. ```js // Example call to refresh session axios.get("/relogin", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns a new session object, refreshed from database data. ```json { "sessionId": "new-session-uuid", "userId": "user-uuid", "email": "user@example.com", "roleId": "admin", "accessToken": "new-jwt-token", ... } ```` **Error Responses** * **401 Unauthorized**: Token is missing, invalid, or session cannot be re-established. ```json { "status": "ERR", "message": "Cannot relogin" } ```` **Notes** - The `/relogin` route is commonly used for **silent login flows**, especially after page reloads or token-based auto-login mechanisms. - It triggers internal logic (`req.userAuthUpdate = true`) to signal that the session should be re-initialized and repopulated. - It is not a simple session lookup — it performs a fresh authentication pass using the session's user context. - The refreshed session ensures any updates to user profile, roles, or permissions are immediately reflected. > **Tip:** > This route is ideal when you want to **rebuild a user's session** in the frontend without requiring them to manually log in again. ## Verification Services — Email Verification Email verification is a two-step flow that ensures a user's email address is verified and trusted by the system. All verification services, including email verification, are located under the `/verification-services` base path. ### When is Email Verification Triggered? - After user registration, if `emailVerificationRequiredForLogin` is active. - During a separate user action to verify or update email addresses. - When login fails with `EmailVerificationNeeded` and frontend initiates verification. ### Email Verification Flow 1. **Frontend calls `/verification-services/email-verification/start`** with the user's email address. - Mindbricks checks if the email is already verified. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's email or returned in the response (only in development environments for easier testing). 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/email-verification/complete`** with the `email` and the received `secretCode`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s `emailVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/email-verification/start` **Purpose** Starts the email verification process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------| | email | String | Yes | The email address to verify | ```json { "email": "user@example.com" } ```` #### Success Response Secret code details (in development environment). Confirms that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` > ⚠️ In production, the secret code is only sent via email, not exposed in the API response. #### Error Responses - `400 Bad Request`: Email already verified. - `403 Forbidden`: Sending a code too frequently (anti-spam). --- ### POST `/verification-services/email-verification/complete` **Purpose** Completes the email verification by validating the secret code. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------| | email | String | Yes | The user email being verified | | secretCode | String | Yes | The secret code received via email | ```json { "email": "user@example.com", "secretCode": "123456" } ```` #### Success Response Returns confirmation that the email has been verified. ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ```` #### Error Responses - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes ### Resend Throttling You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds). ### Expiration Handling Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day). ### One Code Per Session Only one active verification session per user is allowed at a time. > 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps. ## Verification Services — Mobile Verification Mobile verification is a two-step flow that ensures a user's mobile number is verified and trusted by the system. All verification services, including mobile verification, are located under the `/verification-services` base path. ### When is Mobile Verification Triggered? - After user registration, if `mobileVerificationRequiredForLogin` is active. - During a separate user action to verify or update mobile numbers. - When login fails with `MobileVerificationNeeded` and frontend initiates verification. ### Mobile Verification Flow 1. **Frontend calls `/verification-services/mobile-verification/start`** with the user's email address (used to locate the user). - Mindbricks checks if the mobile number is already verified. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's mobile via SMS or returned in the response (only in development environments for easier testing). 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/mobile-verification/complete`** with the `email` and the received `secretCode`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s `mobileVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/mobile-verification/start` **Purpose**: Starts the mobile verification process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address associated with the mobile number to verify | ```json { "email": "user@example.com" } ```` **Success Response** Secret code details (in development environment). Confirms that the verification step has been started. ```json { "userId": "user-uuid", "mobile": "+15551234567", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the secret code is only sent via SMS, not exposed in the API response. **Error Responses** - 400 Bad Request: Mobile already verified. - 403 Forbidden: Sending a code too frequently (anti-spam). --- ### POST `/verification-services/mobile-verification/complete` **Purpose**: Completes the mobile verification by validating the secret code. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|------------------------------------| | email | String | Yes | The user's email being verified | | secretCode | String | Yes | The secret code received via SMS | ```json { "email": "user@example.com", "secretCode": "123456" } ```` **Success Response** Returns confirmation that the mobile number has been verified. ```json { "userId": "user-uuid", "mobile": "+15551234567", "isVerified": true } ```` **Error Responses** 403 Forbidden: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes **Resend Throttling**: You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds). **Expiration Handling**: Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day). **One Code Per Session**: Only one active verification session per user is allowed at a time. 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps. ## Verification Services — Email 2FA Verification Email 2FA (Two-Factor Authentication) provides an additional layer of security by requiring users to confirm their identity using a secret code sent to their email address. This process is used in login flows or sensitive actions that need extra verification. All verification services, including 2FA, are located under the `/verification-services` base path. ### When is Email 2FA Triggered? - During login flows where `sessionNeedsEmail2FA` is `true` - When the backend enforces two-factor authentication for a sensitive operation ### Email 2FA Flow 1. **Frontend calls `/verification-services/email-2factor-verification/start`** with the user's id, session id, client info, and reason. - Mindbricks identifies the user and checks if a cooldown period applies. - A new secret code is generated and stored, linked to the current session ID. - The code is sent via email or returned in development environments. 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/email-2factor-verification/complete`** with the `userId`, `sessionId`, and the `secretCode`. - Mindbricks verifies the code, validates the session, and updates the session to remove the 2FA requirement. --- ## API Endpoints ### POST `/verification-services/email-2factor-verification/start` **Purpose**: Starts the email-based 2FA process by generating and sending a verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The current session ID | | client | String | No | Optional client tag or context | | reason | String | No | Optional reason for triggering 2FA | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "client": "login-page", "reason": "Login requires email 2FA" } ```` #### Success Response ```json { "sessionId": "session-uuid", "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 300, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the `secretCode` is only sent via email, not exposed in the API response. #### Error Responses - **403 Forbidden**: Sending a code too frequently (anti-spam) - **401 Unauthorized**: User session not found --- ### POST `/verification-services/email-2factor-verification/complete` **Purpose**: Completes the email 2FA process by validating the secret code and session. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|--------------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The session ID the code is tied to | | secretCode | String | Yes | The secret code received via email | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "secretCode": "123456" } ```` #### Success Response Returns an updated session with 2FA disabled: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "sessionNeedsEmail2FA": false, ... } ```` #### Error Responses - **403 Forbidden**: - Secret code mismatch - Secret code expired - Verification step not found --- ### Important Behavioral Notes - **One Code Per Session**: Only one active code can be issued per session. - **Resend Throttling**: Code requests are throttled based on `resendTimeWindow` (e.g., 60 seconds). - **Expiration**: Codes expire after `expireTimeWindow` (e.g., 5 minutes). - 💡 Mindbricks manages session cache, spam control, expiration tracking, and event notifications for all 2FA steps. ## Verification Services — Mobile 2FA Verification Mobile 2FA (Two-Factor Authentication) is a security mechanism that adds an extra layer of authentication using a user's verified mobile number. All verification services, including mobile 2FA, are accessible under the `/verification-services` base path. ### When is Mobile 2FA Triggered? - During login or critical actions requiring step-up authentication. - When the session has a flag `sessionNeedsMobile2FA = true`. - When login or session verification fails with `MobileVerificationNeeded`, indicating 2FA is required. ### Mobile 2FA Verification Flow 1. **Frontend calls `/verification-services/mobile-2factor-verification/start`** with the user's id, session id, client info, and reason. - Mindbricks finds the user by id. - Verifies that the user has a verified mobile number. - A secret code is generated and cached against the session. - The code is sent to the user's verified mobile number or returned in the response (only in development environments). 2. **User receives the code and enters it in the frontend app.** 3. **Frontend calls `/verification-services/mobile-2factor-verification/complete`** with the `userId`, `sessionId`, and `secretCode`. - Mindbricks validates the code for expiration and correctness. - If valid, the session flag `sessionNeedsMobile2FA` is cleared. - A refreshed session object is returned. --- ## API Endpoints ### POST `/verification-services/mobile-2factor-verification/start` **Purpose**: Initiates mobile-based 2FA by generating and sending a secret code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The current session ID | | client | String | No | Optional client tag or context | | reason | String | No | Optional reason for triggering 2FA | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "client": "login-page", "reason": "Login requires mobile 2FA" } ```` **Success Response** Returns the generated code (only in development), expiration info, and metadata. ```json { "userId": "user-uuid", "sessionId": "session-uuid", "mobile": "+15551234567", "secretCode": "654321", "expireTime": 300, "date": "2024-04-29T11:00:00.000Z" } ```` ⚠️ In production environments, the secret code is not included in the response and is instead delivered via SMS. **Error Responses** - 403 Forbidden: Mobile number not verified. - 403 Forbidden: Code resend attempted before cooldown period (`resendTimeWindow`). - 401 Unauthorized: Email not recognized or session invalid. --- ### POST `/verification-services/mobile-2factor-verification/complete` **Purpose**: Completes mobile 2FA verification by validating the secret code and updating the session. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------| | userId | String | Yes | ID of the user | | sessionId | String | Yes | ID of the session | | secretCode | String | Yes | The 6-digit code received via SMS | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "secretCode": "654321" } ```` **Success Response** Returns the updated session with `sessionNeedsMobile2FA: false`. ```json { "sessionId": "session-uuid", "userId": "user-uuid", "sessionNeedsMobile2FA": false, "accessToken": "jwt-token", "expiresIn": 86400 } ```` **Error Responses** - 403 Forbidden: Code mismatch or expired. - 403 Forbidden: No ongoing verification found. - 401 Unauthorized: Session does not exist or is invalid. --- ### Behavioral Notes - **Rate Limiting**: A user can only request a new mobile 2FA code after the cooldown period (`resendTimeWindow`, e.g., 60 seconds). - **Expiration**: Mobile 2FA codes expire after the configured time (`expireTimeWindow`, e.g., 5 minutes). - **Session Integrity**: Verification status is tied to the session; incorrect sessionId will invalidate the attempt. 💡 Mindbricks handles session integrity, rate limiting, and secure code delivery to ensure a robust mobile 2FA process. ## Verification Services — Password Reset by Email Password Reset by Email enables a user to securely reset their password using a secret code sent to their registered email address. All verification services, including password reset by email, are located under the `/verification-services` base path. ### When is Password Reset by Email Triggered? - When a user requests to reset their password by providing their email address. - This service is typically exposed on a “Forgot Password?” flow in the frontend. ### Password Reset Flow 1. **Frontend calls `/verification-services/password-reset-by-email/start`** with the user's email. - Mindbricks checks if the user exists and if the email is registered. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's email, or returned in the response (in development environments only for testing). 2. **User receives the code and enters it into the frontend along with the new password.** 3. **Frontend calls `/verification-services/password-reset-by-email/complete`** with the `email`, the `secretCode`, and the new `password`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s password is reset, their `emailVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/password-reset-by-email/start` **Purpose**: Starts the password reset process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address of the user | ```json { "email": "user@example.com" } ```` **Success Response** Returns secret code details (only in development environment) and confirmation that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the secret code is only sent via email and not exposed in the API response. **Error Responses** - `401 NotAuthenticated`: Email address not found or not associated with a user. - `403 Forbidden`: Sending a code too frequently (spam prevention). --- ### POST `/verification-services/password-reset-by-email/complete` **Purpose**: Completes the password reset process by validating the secret code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|----------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via email | | password | String | Yes | The new password the user wants to set | ```json { "email": "user@example.com", "secretCode": "123456", "password": "newSecurePassword123" } ```` **Success Response** ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ```` **Error Responses** - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes ### Resend Throttling: A new verification code can only be requested after a cooldown period (configured via `resendTimeWindow`, e.g., 60 seconds). ### Expiration Handling: Verification codes automatically expire after a predefined period (`expireTimeWindow`, e.g., 1 day). ### Session & Event Handling: Mindbricks manages: - Spam prevention - Code caching per user - Expiration logic - Verification start/complete events ## Verification Services — Password Reset by Mobile Password reset by mobile provides users with a secure mechanism to reset their password using a verification code sent via SMS to their registered mobile number. All verification services, including password reset by mobile, are located under the `/verification-services` base path. ### When is Password Reset by Mobile Triggered? - When a user forgets their password and selects the mobile reset option. - When a user explicitly initiates password recovery via mobile on the login or help screen. ### Password Reset by Mobile Flow 1. **Frontend calls `/verification-services/password-reset-by-mobile/start`** with the user's mobile number or associated identifier. - Mindbricks checks if a user with the given mobile exists. - A secret code is generated and stored in the cache for that user. - The code is sent to the user's mobile (or returned in development environments for testing). 2. **User receives the code via SMS and enters it into the frontend app.** 3. **Frontend calls `/verification-services/password-reset-by-mobile/complete`** with the user's `email`, the `secretCode`, and the new `password`. - Mindbricks validates the secret code and its expiration. - If valid, it updates the user's password and returns a success response. --- ## API Endpoints ### POST `/verification-services/password-reset-by-mobile/start` **Purpose**: Initiates the mobile-based password reset by sending a verification code to the user's mobile. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|------------------------------| | mobile | String | Yes | The mobile number to verify | ```json { "mobile": "+905551234567" } ```` ### Success Response Returns the verification context (code returned only in development): ```json { "userId": "user-uuid", "mobile": "+905551234567", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the `secretCode` is not included in the response and is only sent via SMS. ### Error Responses - **400 Bad Request**: Mobile already verified - **403 Forbidden**: Rate-limited (code already sent recently) - **404 Not Found**: User with provided mobile not found --- ### POST `/verification-services/password-reset-by-mobile/complete` **Purpose**: Finalizes the password reset process by validating the received verification code and updating the user’s password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via SMS | | password | String | Yes | The new password to assign | ```json { "email": "user@example.com", "secretCode": "123456", "password": "NewSecurePassword123!" } ```` ### Success Response ```json { "userId": "user-uuid", "mobile": "+905551234567", "isVerified": true } ```` --- ### Important Behavioral Notes - **Throttling**: Codes can only be resent after a delay defined by `resendTimeWindow` (e.g., 60 seconds). - **Expiration**: Codes expire after the `expireTimeWindow` (e.g., 1 day). - **One Active Session**: Only one active password reset session is allowed per user at a time. - **Session-less**: This flow does not require an active session — it works for unauthenticated users. 💡 Mindbricks handles spam protection, session caching, and event-based logging (for both start and complete operations) as part of the verification service base class. ## Verification Method Types ### 🧾 For byCode Verifications This verification type requires the user to manually enter a 6-digit code. **Frontend Action**: Display a secure input page where the user can enter the code they received via email or SMS. After collecting the code and any required metadata (such as `userId` or `sessionId`), make a `POST` request to the corresponding `/complete` endpoint. --- ### 🔗 For byLink Verifications This verification type uses a clickable link embedded in an email (or SMS message). **Frontend Action**: The link points to a `GET` page in your frontend that parses `userId` and `code` from the query string and sends them to the backend via a `POST` request to the corresponding `/complete` endpoint. This enables one-click verification without requiring the user to type in a code. ### 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 ## linkedin-jobapplication-service **Version:** `1.0.0` Microservice handling job postings (created by recruiters/company admins), job applications (created by users), allowing job search, application submission, and status update workflows. Enforces business rules around application status, admin controls, and lets professionals apply and track job applications .within the network. ## 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 JobApplication Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our JobApplication Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the JobApplication Service via HTTP requests for purposes such as creating, updating, deleting and querying JobApplication 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 JobApplication 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 JobApplication 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 | linkedin-access-token| | Cookie | linkedin-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 JobApplication 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 JobApplication service. This service is configured to listen for HTTP requests on port `3003`, 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://linkedin.prw.mindbricks.com/jobapplication-api` * **Staging:** `https://linkedin-stage.mindbricks.co/jobapplication-api` * **Production:** `https://linkedin.mindbricks.co/jobapplication-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 JobApplication 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 `JobApplication` 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 `JobApplication` 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 `JobApplication` 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 JobApplication 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. ### JobPosting resource *Resource Definition* : Job posting entity representing an open position with a company. Created/managed by company admins or recruiters. Fields include companyId, postedByUserId, title, details, requirements, employment type, salary, deadline, etc. *JobPosting Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **description** | Text | | | ** | | **title** | String | | | ** | | **applicationDeadline** | Date | | | ** | | **companyId** | ID | | | ** | | **employmentType** | Enum | | | ** | | **postedByUserId** | ID | | | ** | | **salaryRange** | String | | | ** | | **location** | String | | | ** | | **visibility** | Enum | | | ** | | **workplaceType** | Enum | | | ** | | **status** | Enum | | | ** | | **companyName** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### employmentType Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **full_time** | `"full_time""` | 0 | | **part_time** | `"part_time""` | 1 | | **contract** | `"contract""` | 2 | | **internship** | `"internship""` | 3 | | **volunteer** | `"volunteer""` | 4 | | **other** | `"other""` | 5 | | **temporary** | `"temporary""` | 6 | ##### visibility Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **public** | `"public""` | 0 | | **private** | `"private""` | 1 | ##### workplaceType Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **on_site** | `"on_site""` | 0 | | **remote** | `"remote""` | 1 | | **hybrid** | `"hybrid""` | 2 | ##### status Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **closed** | `"closed""` | 1 | ### JobApplication resource *Resource Definition* : Record of a user applying for a specific jobPosting (tracks application/resume/status/audit). Each application is unique per user x jobPosting. *JobApplication Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **jobPostingId** | ID | | | ** | | **applicantUserId** | ID | | | ** | | **coverLetter** | Text | | | ** | | **resumeUrl** | String | | | ** | | **lastStatusUpdateAt** | Date | | | ** | | **status** | Enum | | | ** | | **appliedAt** | Date | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **submitted** | `"submitted""` | 0 | | **in_review** | `"in_review""` | 1 | | **accepted** | `"accepted""` | 2 | | **rejected** | `"rejected""` | 3 | ## Business Api ### `Delete Jobapplication` API Delete (soft) job application. Only applicant or admin for the job's company may delete. **Rest Route** The `deleteJobApplication` API REST controller can be triggered via the following route: `/v1/jobapplications/:jobApplicationId` **Rest Request Parameters** The `deleteJobApplication` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobApplicationId | ID | true | request.params?.["jobApplicationId"] | **jobApplicationId** : 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/jobapplications/:jobApplicationId** ```js axios({ method: 'DELETE', url: `/v1/jobapplications/${jobApplicationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobApplication", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "jobApplication": { "id": "ID", "jobPostingId": "ID", "applicantUserId": "ID", "coverLetter": "Text", "resumeUrl": "String", "lastStatusUpdateAt": "Date", "status": "Enum", "status_idx": "Integer", "appliedAt": "Date", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Jobapplication` API Get job application record. Only applicant or admin of company may view. **Rest Route** The `getJobApplication` API REST controller can be triggered via the following route: `/v1/jobapplications/:jobApplicationId` **Rest Request Parameters** The `getJobApplication` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobApplicationId | ID | true | request.params?.["jobApplicationId"] | **jobApplicationId** : 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/jobapplications/:jobApplicationId** ```js axios({ method: 'GET', url: `/v1/jobapplications/${jobApplicationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobApplication", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "jobApplication": { "id": "ID", "jobPostingId": "ID", "applicantUserId": "ID", "coverLetter": "Text", "resumeUrl": "String", "lastStatusUpdateAt": "Date", "status": "Enum", "status_idx": "Integer", "appliedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Jobposting` API Update job posting fields. Only company admins for companyId may update. Ownership enforced. Edits forbidden after deadline if desired. **Rest Route** The `updateJobPosting` API REST controller can be triggered via the following route: `/v1/jobpostings/:jobPostingId` **Rest Request Parameters** The `updateJobPosting` api has got 12 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobPostingId | ID | true | request.params?.["jobPostingId"] | | description | Text | true | request.body?.["description"] | | title | String | true | request.body?.["title"] | | applicationDeadline | Date | false | request.body?.["applicationDeadline"] | | companyId | ID | true | request.body?.["companyId"] | | employmentType | Enum | true | request.body?.["employmentType"] | | salaryRange | String | false | request.body?.["salaryRange"] | | location | String | false | request.body?.["location"] | | visibility | Enum | true | request.body?.["visibility"] | | workplaceType | Enum | true | request.body?.["workplaceType"] | | status | Enum | true | request.body?.["status"] | | companyName | String | true | request.body?.["companyName"] | **jobPostingId** : This id paremeter is used to select the required data object that will be updated **description** : **title** : **applicationDeadline** : **companyId** : **employmentType** : **salaryRange** : **location** : **visibility** : **workplaceType** : **status** : **companyName** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/jobpostings/:jobPostingId** ```js axios({ method: 'PATCH', url: `/v1/jobpostings/${jobPostingId}`, data: { description:"Text", title:"String", applicationDeadline:"Date", companyId:"ID", employmentType:"Enum", salaryRange:"String", location:"String", visibility:"Enum", workplaceType:"Enum", status:"Enum", companyName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobPosting", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "jobPosting": { "id": "ID", "description": "Text", "title": "String", "applicationDeadline": "Date", "companyId": "ID", "employmentType": "Enum", "employmentType_idx": "Integer", "postedByUserId": "ID", "salaryRange": "String", "location": "String", "visibility": "Enum", "visibility_idx": "Integer", "workplaceType": "Enum", "workplaceType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "companyName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Jobposting` API Delete (soft) a job posting. Only admin for companyId may delete. **Rest Route** The `deleteJobPosting` API REST controller can be triggered via the following route: `/v1/jobpostings/:jobPostingId` **Rest Request Parameters** The `deleteJobPosting` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobPostingId | ID | true | request.params?.["jobPostingId"] | **jobPostingId** : 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/jobpostings/:jobPostingId** ```js axios({ method: 'DELETE', url: `/v1/jobpostings/${jobPostingId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobPosting", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "jobPosting": { "id": "ID", "description": "Text", "title": "String", "applicationDeadline": "Date", "companyId": "ID", "employmentType": "Enum", "employmentType_idx": "Integer", "postedByUserId": "ID", "salaryRange": "String", "location": "String", "visibility": "Enum", "visibility_idx": "Integer", "workplaceType": "Enum", "workplaceType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "companyName": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Jobposting` API Fetch a job posting by ID. Publicly visible if visibility=public, else only viewable by admins of company. **Rest Route** The `getJobPosting` API REST controller can be triggered via the following route: `/v1/jobpostings/:jobPostingId` **Rest Request Parameters** The `getJobPosting` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobPostingId | ID | true | request.params?.["jobPostingId"] | **jobPostingId** : 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/jobpostings/:jobPostingId** ```js axios({ method: 'GET', url: `/v1/jobpostings/${jobPostingId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobPosting", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "jobPosting": { "id": "ID", "description": "Text", "title": "String", "applicationDeadline": "Date", "companyId": "ID", "employmentType": "Enum", "employmentType_idx": "Integer", "postedByUserId": "ID", "salaryRange": "String", "location": "String", "visibility": "Enum", "visibility_idx": "Integer", "workplaceType": "Enum", "workplaceType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "companyName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Jobapplication` API Update job application (status/by admin, or resume/cover by applicant, limited). Only admins/recruiters for job's company, or applicant, may update. Status can only move forward, not revert to submitted. **Rest Route** The `updateJobApplication` API REST controller can be triggered via the following route: `/v1/jobapplications/:jobApplicationId` **Rest Request Parameters** The `updateJobApplication` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobApplicationId | ID | true | request.params?.["jobApplicationId"] | | coverLetter | Text | false | request.body?.["coverLetter"] | | resumeUrl | String | false | request.body?.["resumeUrl"] | | status | Enum | true | request.body?.["status"] | **jobApplicationId** : This id paremeter is used to select the required data object that will be updated **coverLetter** : **resumeUrl** : **status** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/jobapplications/:jobApplicationId** ```js axios({ method: 'PATCH', url: `/v1/jobapplications/${jobApplicationId}`, data: { coverLetter:"Text", resumeUrl:"String", status:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobApplication", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "jobApplication": { "id": "ID", "jobPostingId": "ID", "applicantUserId": "ID", "coverLetter": "Text", "resumeUrl": "String", "lastStatusUpdateAt": "Date", "status": "Enum", "status_idx": "Integer", "appliedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Jobapplication` API Submit a job application for a jobPosting (by logged-in user). Only if not already applied, and before deadline. Sets status=submitted. **Rest Route** The `createJobApplication` API REST controller can be triggered via the following route: `/v1/jobapplications` **Rest Request Parameters** The `createJobApplication` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | jobPostingId | ID | true | request.body?.["jobPostingId"] | | coverLetter | Text | false | request.body?.["coverLetter"] | | resumeUrl | String | false | request.body?.["resumeUrl"] | | status | Enum | true | request.body?.["status"] | **jobPostingId** : **coverLetter** : **resumeUrl** : **status** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/jobapplications** ```js axios({ method: 'POST', url: '/v1/jobapplications', data: { jobPostingId:"ID", coverLetter:"Text", resumeUrl:"String", status:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobApplication", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "jobApplication": { "id": "ID", "jobPostingId": "ID", "applicantUserId": "ID", "coverLetter": "Text", "resumeUrl": "String", "lastStatusUpdateAt": "Date", "status": "Enum", "status_idx": "Integer", "appliedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Jobpostings` API List job postings. Public jobs visible to all; private jobs visible only to company admins or recruiters. **Rest Route** The `listJobPostings` API REST controller can be triggered via the following route: `/v1/jobpostings` **Rest Request Parameters** **Filter Parameters** The `listJobPostings` api supports 10 optional filter parameters for filtering list results: **title** (`String`): Filter by title - Single (partial match, case-insensitive): `?title=` - Multiple: `?title=&title=` - Null: `?title=null` **applicationDeadline** (`Date`): Filter by applicationDeadline - Single date: `?applicationDeadline=2024-01-15` - Multiple dates: `?applicationDeadline=2024-01-15&applicationDeadline=2024-01-20` - Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-` - Null: `?applicationDeadline=null` **companyId** (`ID`): Filter by companyId - Single: `?companyId=` - Multiple: `?companyId=&companyId=` - Null: `?companyId=null` **employmentType** (`Enum`): Filter by employmentType - Single: `?employmentType=` (case-insensitive) - Multiple: `?employmentType=&employmentType=` - Null: `?employmentType=null` **postedByUserId** (`ID`): Filter by postedByUserId - Single: `?postedByUserId=` - Multiple: `?postedByUserId=&postedByUserId=` - Null: `?postedByUserId=null` **location** (`String`): Filter by location - Single (partial match, case-insensitive): `?location=` - Multiple: `?location=&location=` - Null: `?location=null` **visibility** (`Enum`): Filter by visibility - Single: `?visibility=` (case-insensitive) - Multiple: `?visibility=&visibility=` - Null: `?visibility=null` **workplaceType** (`Enum`): Filter by workplaceType - Single: `?workplaceType=` (case-insensitive) - Multiple: `?workplaceType=&workplaceType=` - Null: `?workplaceType=null` **status** (`Enum`): Filter by status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **companyName** (`String`): Filter by companyName - Single (partial match, case-insensitive): `?companyName=` - Multiple: `?companyName=&companyName=` - Null: `?companyName=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/jobpostings** ```js axios({ method: 'GET', url: '/v1/jobpostings', data: { }, params: { // Filter parameters (see Filter Parameters section above) // title: '' // Filter by title // applicationDeadline: '' // Filter by applicationDeadline // companyId: '' // Filter by companyId // employmentType: '' // Filter by employmentType // postedByUserId: '' // Filter by postedByUserId // location: '' // Filter by location // visibility: '' // Filter by visibility // workplaceType: '' // Filter by workplaceType // status: '' // Filter by status // companyName: '' // Filter by companyName } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobPostings", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "jobPostings": [ { "id": "ID", "description": "Text", "title": "String", "applicationDeadline": "Date", "companyId": "ID", "employmentType": "Enum", "employmentType_idx": "Integer", "postedByUserId": "ID", "salaryRange": "String", "location": "String", "visibility": "Enum", "visibility_idx": "Integer", "workplaceType": "Enum", "workplaceType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "companyName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Jobapplications` API List job applications. Applicants see their own; admins of job's company can view all for their jobs; supports filter by status, job and applicant. **Rest Route** The `listJobApplications` API REST controller can be triggered via the following route: `/v1/jobapplications` **Rest Request Parameters** **Filter Parameters** The `listJobApplications` api supports 5 optional filter parameters for filtering list results: **jobPostingId** (`ID`): Filter by jobPostingId - Single: `?jobPostingId=` - Multiple: `?jobPostingId=&jobPostingId=` - Null: `?jobPostingId=null` **applicantUserId** (`ID`): Filter by applicantUserId - Single: `?applicantUserId=` - Multiple: `?applicantUserId=&applicantUserId=` - Null: `?applicantUserId=null` **lastStatusUpdateAt** (`Date`): Filter by lastStatusUpdateAt - Single date: `?lastStatusUpdateAt=2024-01-15` - Multiple dates: `?lastStatusUpdateAt=2024-01-15&lastStatusUpdateAt=2024-01-20` - Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-` - Null: `?lastStatusUpdateAt=null` **status** (`Enum`): Filter by status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **appliedAt** (`Date`): Filter by appliedAt - Single date: `?appliedAt=2024-01-15` - Multiple dates: `?appliedAt=2024-01-15&appliedAt=2024-01-20` - Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-` - Null: `?appliedAt=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/jobapplications** ```js axios({ method: 'GET', url: '/v1/jobapplications', data: { }, params: { // Filter parameters (see Filter Parameters section above) // jobPostingId: '' // Filter by jobPostingId // applicantUserId: '' // Filter by applicantUserId // lastStatusUpdateAt: '' // Filter by lastStatusUpdateAt // status: '' // Filter by status // appliedAt: '' // Filter by appliedAt } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobApplications", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "jobApplications": [ { "id": "ID", "jobPostingId": "ID", "applicantUserId": "ID", "coverLetter": "Text", "resumeUrl": "String", "lastStatusUpdateAt": "Date", "status": "Enum", "status_idx": "Integer", "appliedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Jobposting` API Create a new job posting. Only company admins/recruiters for companyId can create. postedByUserId set from session. **Rest Route** The `createJobPosting` API REST controller can be triggered via the following route: `/v1/jobpostings` **Rest Request Parameters** The `createJobPosting` api has got 11 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | description | Text | true | request.body?.["description"] | | title | String | true | request.body?.["title"] | | applicationDeadline | Date | false | request.body?.["applicationDeadline"] | | companyId | ID | false | request.body?.["companyId"] | | employmentType | Enum | true | request.body?.["employmentType"] | | salaryRange | String | false | request.body?.["salaryRange"] | | location | String | false | request.body?.["location"] | | visibility | Enum | true | request.body?.["visibility"] | | workplaceType | Enum | true | request.body?.["workplaceType"] | | status | Enum | true | request.body?.["status"] | | companyName | String | true | request.body?.["companyName"] | **description** : **title** : **applicationDeadline** : **companyId** : **employmentType** : **salaryRange** : **location** : **visibility** : **workplaceType** : **status** : **companyName** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/jobpostings** ```js axios({ method: 'POST', url: '/v1/jobpostings', data: { description:"Text", title:"String", applicationDeadline:"Date", companyId:"ID", employmentType:"Enum", salaryRange:"String", location:"String", visibility:"Enum", workplaceType:"Enum", status:"Enum", companyName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "jobPosting", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "jobPosting": { "id": "ID", "description": "Text", "title": "String", "applicationDeadline": "Date", "companyId": "ID", "employmentType": "Enum", "employmentType_idx": "Integer", "postedByUserId": "ID", "salaryRange": "String", "location": "String", "visibility": "Enum", "visibility_idx": "Integer", "workplaceType": "Enum", "workplaceType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "companyName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### 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 ## linkedin-networking-service **Version:** `1.0.0` Handles professional networking logic for user-to-user connections: manages connection requests, accepted relationships, listing/removal, permissions, and state transitions. Publishes connection lifecycle events for notification... ## 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 Networking Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Networking Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Networking Service via HTTP requests for purposes such as creating, updating, deleting and querying Networking 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 Networking 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 Networking 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 | linkedin-access-token| | Cookie | linkedin-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 Networking 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 Networking 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://linkedin.prw.mindbricks.com/networking-api` * **Staging:** `https://linkedin-stage.mindbricks.co/networking-api` * **Production:** `https://linkedin.mindbricks.co/networking-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 Networking 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 `Networking` 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 `Networking` 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 `Networking` 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 Networking 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. ### Connection resource *Resource Definition* : Represents a single established user-to-user professional relationship (mutual connection). One record per unordered user pair, deleted on disconnect.. *Connection Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **connectedSince** | Date | | | ** | | **userId1** | ID | | | ** | | **userId2** | ID | | | ** | ### ConnectionRequest resource *Resource Definition* : Tracks a user's request to connect with another user, supporting request/accept/reject/cancel, with audit timestamps. *ConnectionRequest Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **receiverUserId** | ID | | | ** | | **senderUserId** | ID | | | ** | | **sentAt** | Date | | | ** | | **status** | Enum | | | ** | | **respondedAt** | Date | | | ** | | **message** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **accepted** | `"accepted""` | 1 | | **rejected** | `"rejected""` | 2 | ## Business Api ### `Create Connection` API Create Connection **Rest Route** The `createConnection` API REST controller can be triggered via the following route: `/v1/connections` **Rest Request Parameters** The `createConnection` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId1 | ID | true | request.body?.["userId1"] | | userId2 | ID | true | request.body?.["userId2"] | **userId1** : **userId2** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/connections** ```js axios({ method: 'POST', url: '/v1/connections', data: { userId1:"ID", userId2:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connection", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "connection": { "id": "ID", "connectedSince": "Date", "userId1": "ID", "userId2": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Connectionrequest` API Sender or receiver may cancel/delete a connection request (soft-delete). **Rest Route** The `deleteConnectionRequest` API REST controller can be triggered via the following route: `/v1/connectionrequests/:connectionRequestId` **Rest Request Parameters** The `deleteConnectionRequest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | connectionRequestId | ID | true | request.params?.["connectionRequestId"] | **connectionRequestId** : 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/connectionrequests/:connectionRequestId** ```js axios({ method: 'DELETE', url: `/v1/connectionrequests/${connectionRequestId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connectionRequest", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "connectionRequest": { "id": "ID", "receiverUserId": "ID", "senderUserId": "ID", "sentAt": "Date", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "message": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Connectionrequest` API Allows receiver of a pending connection request to accept or reject request. **Rest Route** The `updateConnectionRequest` API REST controller can be triggered via the following route: `/v1/connectionrequests/:connectionRequestId` **Rest Request Parameters** The `updateConnectionRequest` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | connectionRequestId | ID | true | request.params?.["connectionRequestId"] | | status | Enum | true | request.body?.["status"] | | respondedAt | Date | false | request.body?.["respondedAt"] | **connectionRequestId** : This id paremeter is used to select the required data object that will be updated **status** : **respondedAt** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/connectionrequests/:connectionRequestId** ```js axios({ method: 'PATCH', url: `/v1/connectionrequests/${connectionRequestId}`, data: { status:"Enum", respondedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connectionRequest", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "connectionRequest": { "id": "ID", "receiverUserId": "ID", "senderUserId": "ID", "sentAt": "Date", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "message": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Connections` API List all active connections where session user is a participant. **Rest Route** The `listConnections` API REST controller can be triggered via the following route: `/v1/connections` **Rest Request Parameters** The `listConnections` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/connections** ```js axios({ method: 'GET', url: '/v1/connections', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connections", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "connections": [ { "id": "ID", "connectedSince": "Date", "userId1": "ID", "userId2": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Connectionrequests` API List connection requests involving current user, filterable by status (pending, accepted, rejected). **Rest Route** The `listConnectionRequests` API REST controller can be triggered via the following route: `/v1/connectionrequests` **Rest Request Parameters** **Filter Parameters** The `listConnectionRequests` api supports 1 optional filter parameter for filtering list results: **status** (`Enum`): Filter by status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/connectionrequests** ```js axios({ method: 'GET', url: '/v1/connectionrequests', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connectionRequests", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "connectionRequests": [ { "id": "ID", "receiverUserId": "ID", "senderUserId": "ID", "sentAt": "Date", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "message": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Connectionrequest` API Send a new connection request from logged-in user to another user. **Rest Route** The `createConnectionRequest` API REST controller can be triggered via the following route: `/v1/connectionrequests` **Rest Request Parameters** The `createConnectionRequest` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | receiverUserId | ID | true | request.body?.["receiverUserId"] | | status | Enum | true | request.body?.["status"] | | respondedAt | Date | false | request.body?.["respondedAt"] | | message | String | false | request.body?.["message"] | **receiverUserId** : **status** : **respondedAt** : **message** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/connectionrequests** ```js axios({ method: 'POST', url: '/v1/connectionrequests', data: { receiverUserId:"ID", status:"Enum", respondedAt:"Date", message:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connectionRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "connectionRequest": { "id": "ID", "receiverUserId": "ID", "senderUserId": "ID", "sentAt": "Date", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "message": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Connection` API Break (delete) the connection between two users. Either user may disconnect. **Rest Route** The `deleteConnection` API REST controller can be triggered via the following route: `/v1/connections/:connectionId` **Rest Request Parameters** The `deleteConnection` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | connectionId | ID | true | request.params?.["connectionId"] | **connectionId** : 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/connections/:connectionId** ```js axios({ method: 'DELETE', url: `/v1/connections/${connectionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connection", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "connection": { "id": "ID", "connectedSince": "Date", "userId1": "ID", "userId2": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Connectionrequest` API Get a specific connection request by ID if sender/receiver. **Rest Route** The `getConnectionRequest` API REST controller can be triggered via the following route: `/v1/connectionrequests/:connectionRequestId` **Rest Request Parameters** The `getConnectionRequest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | connectionRequestId | ID | true | request.params?.["connectionRequestId"] | **connectionRequestId** : 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/connectionrequests/:connectionRequestId** ```js axios({ method: 'GET', url: `/v1/connectionrequests/${connectionRequestId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connectionRequest", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "connectionRequest": { "id": "ID", "receiverUserId": "ID", "senderUserId": "ID", "sentAt": "Date", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "message": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Connection` API Get connection between session user and another user (if exists, not soft-deleted). **Rest Route** The `getConnection` API REST controller can be triggered via the following route: `/v1/connections/:connectionId` **Rest Request Parameters** The `getConnection` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | connectionId | ID | true | request.params?.["connectionId"] | **connectionId** : 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/connections/:connectionId** ```js axios({ method: 'GET', url: `/v1/connections/${connectionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "connection", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "connection": { "id": "ID", "connectedSince": "Date", "userId1": "ID", "userId2": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### 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 ## linkedin-company-service **Version:** `1.0.0` Handles company profiles, company admin assignments, company following, and posting company updates/news. Enables professionals to follow companies, get updates, and enables admins to manage company presence.. ## 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 Company Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Company Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Company Service via HTTP requests for purposes such as creating, updating, deleting and querying Company 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 Company 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 Company 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 | linkedin-access-token| | Cookie | linkedin-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 Company 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 Company 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://linkedin.prw.mindbricks.com/company-api` * **Staging:** `https://linkedin-stage.mindbricks.co/company-api` * **Production:** `https://linkedin.mindbricks.co/company-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 Company 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 `Company` 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 `Company` 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 `Company` 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 Company 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. ### CompanyFollower resource *Resource Definition* : Tracks when a user follows a company to receive updates. Append-only, deletes for unfollow. *CompanyFollower Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **userId** | ID | | | ** | | **companyId** | ID | | | ** | | **followedAt** | Date | | | ** | ### CompanyUpdate resource *Resource Definition* : A post/news update created by company admin and visible to followers depending on visibility. *CompanyUpdate Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **companyId** | ID | | | ** | | **content** | Text | | | ** | | **authorUserId** | ID | | | ** | | **attachmentUrls** | String | | | ** | | **visibility** | Enum | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### visibility Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **public** | `"public""` | 0 | | **private** | `"private""` | 1 | ### Company resource *Resource Definition* : Represents a company profile and brand presence/pages on the network. *Company Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **name** | String | | | ** | | **website** | String | | | ** | | **location** | String | | | ** | | **logoUrl** | String | | | ** | | **pageVisibility** | Enum | | | ** | | **createdByUserId** | ID | | | ** | | **description** | Text | | | ** | | **industry** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### pageVisibility Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **public** | `"public""` | 0 | | **private** | `"private""` | 1 | ### CompanyAdmin resource *Resource Definition* : Tracks which users are assigned as admins for a company, allowing them to manage the company page and edits. *CompanyAdmin Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **assignedAt** | Date | | | ** | | **userId** | ID | | | ** | | **companyId** | ID | | | ** | | **assignedBy** | ID | | | ** | ## Business Api ### `Get Companyadmin` API Get company admin record by ID. Only admins can query of their company. **Rest Route** The `getCompanyAdmin` API REST controller can be triggered via the following route: `/v1/companyadmins/:companyAdminId` **Rest Request Parameters** The `getCompanyAdmin` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyAdminId | ID | true | request.params?.["companyAdminId"] | **companyAdminId** : 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/companyadmins/:companyAdminId** ```js axios({ method: 'GET', url: `/v1/companyadmins/${companyAdminId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyAdmin", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "companyAdmin": { "id": "ID", "assignedAt": "Date", "userId": "ID", "companyId": "ID", "assignedBy": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Follow Company` API Follow a company. Adds entry to companyFollower. Any logged-in user may follow. Cannot follow twice. **Rest Route** The `followCompany` API REST controller can be triggered via the following route: `/v1/followcompany` **Rest Request Parameters** The `followCompany` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.body?.["userId"] | | companyId | ID | true | request.body?.["companyId"] | | followedAt | Date | true | request.body?.["followedAt"] | **userId** : **companyId** : **followedAt** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/followcompany** ```js axios({ method: 'POST', url: '/v1/followcompany', data: { userId:"ID", companyId:"ID", followedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyFollower", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "companyFollower": { "id": "ID", "userId": "ID", "companyId": "ID", "followedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Remove Companyadmin` API Removes admin rights from a user for a company. Can only be performed by current admin, not self-removal unless last admin? **Rest Route** The `removeCompanyAdmin` API REST controller can be triggered via the following route: `/v1/removecompanyadmin/:companyAdminId` **Rest Request Parameters** The `removeCompanyAdmin` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyAdminId | ID | true | request.params?.["companyAdminId"] | **companyAdminId** : 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/removecompanyadmin/:companyAdminId** ```js axios({ method: 'DELETE', url: `/v1/removecompanyadmin/${companyAdminId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyAdmin", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "companyAdmin": { "id": "ID", "assignedAt": "Date", "userId": "ID", "companyId": "ID", "assignedBy": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Company` API Creates a new company profile (page). User initiating the company becomes initial admin (enforced in workflow). **Rest Route** The `createCompany` API REST controller can be triggered via the following route: `/v1/companies` **Rest Request Parameters** The `createCompany` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | | website | String | false | request.body?.["website"] | | location | String | false | request.body?.["location"] | | logoUrl | String | false | request.body?.["logoUrl"] | | pageVisibility | Enum | true | request.body?.["pageVisibility"] | | createdByUserId | ID | true | request.body?.["createdByUserId"] | | description | Text | false | request.body?.["description"] | | industry | String | false | request.body?.["industry"] | **name** : **website** : **location** : **logoUrl** : **pageVisibility** : **createdByUserId** : **description** : **industry** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/companies** ```js axios({ method: 'POST', url: '/v1/companies', data: { name:"String", website:"String", location:"String", logoUrl:"String", pageVisibility:"Enum", createdByUserId:"ID", description:"Text", industry:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "company", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "company": { "id": "ID", "name": "String", "website": "String", "location": "String", "logoUrl": "String", "pageVisibility": "Enum", "pageVisibility_idx": "Integer", "createdByUserId": "ID", "description": "Text", "industry": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Company` API Get a company page by ID. If public, anyone can view. If private, only admin/followers. **Rest Route** The `getCompany` API REST controller can be triggered via the following route: `/v1/companies/:companyId` **Rest Request Parameters** The `getCompany` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyId | ID | true | request.params?.["companyId"] | **companyId** : 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/companies/:companyId** ```js axios({ method: 'GET', url: `/v1/companies/${companyId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "company", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "company": { "id": "ID", "name": "String", "website": "String", "location": "String", "logoUrl": "String", "pageVisibility": "Enum", "pageVisibility_idx": "Integer", "createdByUserId": "ID", "description": "Text", "industry": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Companies` API List all (optionally filtered) companies, e.g. for directory/search, subject to visibility. **Rest Route** The `listCompanies` API REST controller can be triggered via the following route: `/v1/companies` **Rest Request Parameters** **Filter Parameters** The `listCompanies` api supports 4 optional filter parameters for filtering list results: **name** (`String`): Filter by name - Single (partial match, case-insensitive): `?name=` - Multiple: `?name=&name=` - Null: `?name=null` **location** (`String`): Filter by location - Single (partial match, case-insensitive): `?location=` - Multiple: `?location=&location=` - Null: `?location=null` **pageVisibility** (`Enum`): Filter by pageVisibility - Single: `?pageVisibility=` (case-insensitive) - Multiple: `?pageVisibility=&pageVisibility=` - Null: `?pageVisibility=null` **industry** (`String`): Filter by industry - Single (partial match, case-insensitive): `?industry=` - Multiple: `?industry=&industry=` - Null: `?industry=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/companies** ```js axios({ method: 'GET', url: '/v1/companies', data: { }, params: { // Filter parameters (see Filter Parameters section above) // name: '' // Filter by name // location: '' // Filter by location // pageVisibility: '' // Filter by pageVisibility // industry: '' // Filter by industry } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companies", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "companies": [ { "id": "ID", "name": "String", "website": "String", "location": "String", "logoUrl": "String", "pageVisibility": "Enum", "pageVisibility_idx": "Integer", "createdByUserId": "ID", "description": "Text", "industry": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Company` API Updates fields of a company page/profile. Only current company admin can update. **Rest Route** The `updateCompany` API REST controller can be triggered via the following route: `/v1/companies/:companyId` **Rest Request Parameters** The `updateCompany` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyId | ID | true | request.params?.["companyId"] | | name | String | false | request.body?.["name"] | | website | String | false | request.body?.["website"] | | location | String | false | request.body?.["location"] | | logoUrl | String | false | request.body?.["logoUrl"] | | pageVisibility | Enum | false | request.body?.["pageVisibility"] | | createdByUserId | ID | true | request.body?.["createdByUserId"] | | description | Text | false | request.body?.["description"] | | industry | String | false | request.body?.["industry"] | **companyId** : This id paremeter is used to select the required data object that will be updated **name** : **website** : **location** : **logoUrl** : **pageVisibility** : **createdByUserId** : **description** : **industry** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/companies/:companyId** ```js axios({ method: 'PATCH', url: `/v1/companies/${companyId}`, data: { name:"String", website:"String", location:"String", logoUrl:"String", pageVisibility:"Enum", createdByUserId:"ID", description:"Text", industry:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "company", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "company": { "id": "ID", "name": "String", "website": "String", "location": "String", "logoUrl": "String", "pageVisibility": "Enum", "pageVisibility_idx": "Integer", "createdByUserId": "ID", "description": "Text", "industry": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Company` API Deletes (soft-delete) a company page. Only current admin may delete. **Rest Route** The `deleteCompany` API REST controller can be triggered via the following route: `/v1/companies/:companyId` **Rest Request Parameters** The `deleteCompany` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyId | ID | true | request.params?.["companyId"] | **companyId** : 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/companies/:companyId** ```js axios({ method: 'DELETE', url: `/v1/companies/${companyId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "company", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "company": { "id": "ID", "name": "String", "website": "String", "location": "String", "logoUrl": "String", "pageVisibility": "Enum", "pageVisibility_idx": "Integer", "createdByUserId": "ID", "description": "Text", "industry": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Assign Companyadmin` API Assigns a user as company admin. Must be called by an existing admin. Records assigning user and timestamp for audit. **Rest Route** The `assignCompanyAdmin` API REST controller can be triggered via the following route: `/v1/assigncompanyadmin` **Rest Request Parameters** The `assignCompanyAdmin` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | assignedAt | Date | true | request.body?.["assignedAt"] | | userId | ID | true | request.body?.["userId"] | | companyId | ID | true | request.body?.["companyId"] | | assignedBy | ID | true | request.body?.["assignedBy"] | **assignedAt** : **userId** : **companyId** : **assignedBy** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/assigncompanyadmin** ```js axios({ method: 'POST', url: '/v1/assigncompanyadmin', data: { assignedAt:"Date", userId:"ID", companyId:"ID", assignedBy:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyAdmin", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "companyAdmin": { "id": "ID", "assignedAt": "Date", "userId": "ID", "companyId": "ID", "assignedBy": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Companyadmins` API List all current admins for a given company. Only admins can query their company admin list. **Rest Route** The `listCompanyAdmins` API REST controller can be triggered via the following route: `/v1/companyadmins` **Rest Request Parameters** **Filter Parameters** The `listCompanyAdmins` api supports 1 optional filter parameter for filtering list results: **userId** (`ID`): Filter by userId - 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/companyadmins** ```js axios({ method: 'GET', url: '/v1/companyadmins', data: { }, params: { // Filter parameters (see Filter Parameters section above) // 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": "companyAdmins", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "companyAdmins": [ { "id": "ID", "assignedAt": "Date", "userId": "ID", "companyId": "ID", "assignedBy": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Companyupdate` API Get a company update/news post. Only public posts are visible to all, private are visible to company followers and company admins. **Rest Route** The `getCompanyUpdate` API REST controller can be triggered via the following route: `/v1/companyupdates/:companyUpdateId` **Rest Request Parameters** The `getCompanyUpdate` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyUpdateId | ID | true | request.params?.["companyUpdateId"] | **companyUpdateId** : 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/companyupdates/:companyUpdateId** ```js axios({ method: 'GET', url: `/v1/companyupdates/${companyUpdateId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyUpdate", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "companyUpdate": { "id": "ID", "companyId": "ID", "content": "Text", "authorUserId": "ID", "attachmentUrls": "String", "visibility": "Enum", "visibility_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Unfollow Company` API Unfollow a company. Deletes companyFollower entry. Only current follower may unfollow. **Rest Route** The `unfollowCompany` API REST controller can be triggered via the following route: `/v1/unfollowcompany/:companyFollowerId` **Rest Request Parameters** The `unfollowCompany` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyFollowerId | ID | true | request.params?.["companyFollowerId"] | **companyFollowerId** : 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/unfollowcompany/:companyFollowerId** ```js axios({ method: 'DELETE', url: `/v1/unfollowcompany/${companyFollowerId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyFollower", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "companyFollower": { "id": "ID", "userId": "ID", "companyId": "ID", "followedAt": "Date", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Companyfollowers` API List all followers of a company. Only company admin can see list of all followers. **Rest Route** The `listCompanyFollowers` API REST controller can be triggered via the following route: `/v1/companyfollowers` **Rest Request Parameters** **Filter Parameters** The `listCompanyFollowers` api supports 1 optional filter parameter for filtering list results: **userId** (`ID`): Filter by userId - 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/companyfollowers** ```js axios({ method: 'GET', url: '/v1/companyfollowers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // 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": "companyFollowers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "companyFollowers": [ { "id": "ID", "userId": "ID", "companyId": "ID", "followedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Companyupdate` API Posts a company update/news. Only active admin of company may post on that company's behalf. **Rest Route** The `createCompanyUpdate` API REST controller can be triggered via the following route: `/v1/companyupdates` **Rest Request Parameters** The `createCompanyUpdate` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyId | ID | true | request.body?.["companyId"] | | content | Text | true | request.body?.["content"] | | authorUserId | ID | true | request.body?.["authorUserId"] | | attachmentUrls | String | false | request.body?.["attachmentUrls"] | | visibility | Enum | true | request.body?.["visibility"] | **companyId** : **content** : **authorUserId** : **attachmentUrls** : **visibility** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/companyupdates** ```js axios({ method: 'POST', url: '/v1/companyupdates', data: { companyId:"ID", content:"Text", authorUserId:"ID", attachmentUrls:"String", visibility:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyUpdate", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "companyUpdate": { "id": "ID", "companyId": "ID", "content": "Text", "authorUserId": "ID", "attachmentUrls": "String", "visibility": "Enum", "visibility_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Companyupdate` API Update company update post/news. Only author or company admins may update. **Rest Route** The `updateCompanyUpdate` API REST controller can be triggered via the following route: `/v1/companyupdates/:companyUpdateId` **Rest Request Parameters** The `updateCompanyUpdate` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyUpdateId | ID | true | request.params?.["companyUpdateId"] | | content | Text | false | request.body?.["content"] | | attachmentUrls | String | false | request.body?.["attachmentUrls"] | | visibility | Enum | false | request.body?.["visibility"] | **companyUpdateId** : This id paremeter is used to select the required data object that will be updated **content** : **attachmentUrls** : **visibility** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/companyupdates/:companyUpdateId** ```js axios({ method: 'PATCH', url: `/v1/companyupdates/${companyUpdateId}`, data: { content:"Text", attachmentUrls:"String", visibility:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyUpdate", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "companyUpdate": { "id": "ID", "companyId": "ID", "content": "Text", "authorUserId": "ID", "attachmentUrls": "String", "visibility": "Enum", "visibility_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Companyfollower` API Get a companyFollower record (for audit/profile/follower listing). Only follower/userId or company admin can get record. **Rest Route** The `getCompanyFollower` API REST controller can be triggered via the following route: `/v1/companyfollowers/:companyFollowerId` **Rest Request Parameters** The `getCompanyFollower` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyFollowerId | ID | true | request.params?.["companyFollowerId"] | **companyFollowerId** : 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/companyfollowers/:companyFollowerId** ```js axios({ method: 'GET', url: `/v1/companyfollowers/${companyFollowerId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyFollower", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "companyFollower": { "id": "ID", "userId": "ID", "companyId": "ID", "followedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Companyupdate` API Delete (soft delete) a company update/news. Only author or current admin may delete. **Rest Route** The `deleteCompanyUpdate` API REST controller can be triggered via the following route: `/v1/companyupdates/:companyUpdateId` **Rest Request Parameters** The `deleteCompanyUpdate` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | companyUpdateId | ID | true | request.params?.["companyUpdateId"] | **companyUpdateId** : 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/companyupdates/:companyUpdateId** ```js axios({ method: 'DELETE', url: `/v1/companyupdates/${companyUpdateId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyUpdate", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "companyUpdate": { "id": "ID", "companyId": "ID", "content": "Text", "authorUserId": "ID", "attachmentUrls": "String", "visibility": "Enum", "visibility_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Companyupdates` API List company updates/news for a company. Public updates are visible to all, private to followers/admins. **Rest Route** The `listCompanyUpdates` API REST controller can be triggered via the following route: `/v1/companyupdates` **Rest Request Parameters** **Filter Parameters** The `listCompanyUpdates` api supports 1 optional filter parameter for filtering list results: **visibility** (`Enum`): Filter by visibility - Single: `?visibility=` (case-insensitive) - Multiple: `?visibility=&visibility=` - Null: `?visibility=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/companyupdates** ```js axios({ method: 'GET', url: '/v1/companyupdates', data: { }, params: { // Filter parameters (see Filter Parameters section above) // visibility: '' // Filter by visibility } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "companyUpdates", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "companyUpdates": [ { "id": "ID", "companyId": "ID", "content": "Text", "authorUserId": "ID", "attachmentUrls": "String", "visibility": "Enum", "visibility_idx": "Integer", "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 ## linkedin-content-service **Version:** `1.0.0` Handles creation, editing, and deletion of user posts (with attachments and visibility), user post feed aggregation, and post engagement (likes, comments). All with post-level visibility control (public/private).. ## 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 Content Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Content Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Content Service via HTTP requests for purposes such as creating, updating, deleting and querying Content 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 Content 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 Content 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 | linkedin-access-token| | Cookie | linkedin-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 Content 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 Content 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://linkedin.prw.mindbricks.com/content-api` * **Staging:** `https://linkedin-stage.mindbricks.co/content-api` * **Production:** `https://linkedin.mindbricks.co/content-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 Content 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 `Content` 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 `Content` 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 `Content` 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 Content 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. ### Post resource *Resource Definition* : A user or company-authored post in the feed, with content, optional attachments, and public/private visibility. Belongs to a user (author) and optionally a company. *Post Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **content** | Text | | | ** | | **companyId** | ID | | | ** | | **authorUserId** | ID | | | ** | | **visibility** | Enum | | | ** | | **attachmentUrls** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### visibility Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **public** | `"public""` | 0 | | **private** | `"private""` | 1 | ### Like resource *Resource Definition* : A record of a user liking a specific post. Each user can like a post only once. Used for engagement counts and activity feeds. *Like Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **likedAt** | Date | | | ** | | **postId** | ID | | | ** | | **userId** | ID | | | ** | ### Comment resource *Resource Definition* : A comment on a post. Can be a top-level or a reply to another comment (via parentCommentId). *Comment Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **authorUserId** | ID | | | ** | | **postId** | ID | | | ** | | **content** | Text | | | ** | | **parentCommentId** | ID | | | ** | ## Business Api ### `Create Post` API Create a new post for the authenticated user. Visibility defaults to public. Posts can optionally belong to a company if author is a company admin. Attachments optional. **Rest Route** The `createPost` API REST controller can be triggered via the following route: `/v1/posts` **Rest Request Parameters** The `createPost` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | content | Text | true | request.body?.["content"] | | companyId | ID | false | request.body?.["companyId"] | | authorUserId | ID | true | request.body?.["authorUserId"] | | visibility | Enum | true | request.body?.["visibility"] | | attachmentUrls | String | false | request.body?.["attachmentUrls"] | **content** : **companyId** : **authorUserId** : **visibility** : **attachmentUrls** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/posts** ```js axios({ method: 'POST', url: '/v1/posts', data: { content:"Text", companyId:"ID", authorUserId:"ID", visibility:"Enum", attachmentUrls:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "post", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "post": { "id": "ID", "content": "Text", "companyId": "ID", "authorUserId": "ID", "visibility": "Enum", "visibility_idx": "Integer", "attachmentUrls": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Comment` API Update an existing comment. Only the author can update. **Rest Route** The `updateComment` API REST controller can be triggered via the following route: `/v1/comments/:commentId` **Rest Request Parameters** The `updateComment` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | commentId | ID | true | request.params?.["commentId"] | | content | Text | false | request.body?.["content"] | | parentCommentId | ID | false | request.body?.["parentCommentId"] | **commentId** : This id paremeter is used to select the required data object that will be updated **content** : **parentCommentId** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/comments/:commentId** ```js axios({ method: 'PATCH', url: `/v1/comments/${commentId}`, data: { content:"Text", parentCommentId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "comment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "comment": { "id": "ID", "authorUserId": "ID", "postId": "ID", "content": "Text", "parentCommentId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Posts` API List posts matching filters, honoring post visibility. Public posts shown to all; private posts only to owners. Supports filtering by author, company, and visibility. Feed aggregation is handled at higher BFF layer. **Rest Route** The `listPosts` API REST controller can be triggered via the following route: `/v1/posts` **Rest Request Parameters** **Filter Parameters** The `listPosts` api supports 3 optional filter parameters for filtering list results: **companyId** (`ID`): Filter by companyId - Single: `?companyId=` - Multiple: `?companyId=&companyId=` - Null: `?companyId=null` **authorUserId** (`ID`): Filter by authorUserId - Single: `?authorUserId=` - Multiple: `?authorUserId=&authorUserId=` - Null: `?authorUserId=null` **visibility** (`Enum`): Filter by visibility - Single: `?visibility=` (case-insensitive) - Multiple: `?visibility=&visibility=` - Null: `?visibility=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/posts** ```js axios({ method: 'GET', url: '/v1/posts', data: { }, params: { // Filter parameters (see Filter Parameters section above) // companyId: '' // Filter by companyId // authorUserId: '' // Filter by authorUserId // visibility: '' // Filter by visibility } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "posts", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "posts": [ { "id": "ID", "content": "Text", "companyId": "ID", "authorUserId": "ID", "visibility": "Enum", "visibility_idx": "Integer", "attachmentUrls": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Like Post` API Like a post. User can like a post only once; duplicate likes prevented. **Rest Route** The `likePost` API REST controller can be triggered via the following route: `/v1/likepost` **Rest Request Parameters** The `likePost` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | postId | ID | true | request.body?.["postId"] | **postId** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/likepost** ```js axios({ method: 'POST', url: '/v1/likepost', data: { postId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "like", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "like": { "id": "ID", "likedAt": "Date", "postId": "ID", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Post` API Get a post by ID. Public posts visible to all. Private only visible to author or company admin (if company post). **Rest Route** The `getPost` API REST controller can be triggered via the following route: `/v1/posts/:postId` **Rest Request Parameters** The `getPost` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | postId | ID | true | request.params?.["postId"] | **postId** : 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/posts/:postId** ```js axios({ method: 'GET', url: `/v1/posts/${postId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "post", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "post": { "id": "ID", "content": "Text", "companyId": "ID", "authorUserId": "ID", "visibility": "Enum", "visibility_idx": "Integer", "attachmentUrls": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Comment` API Add a new comment to a post. Can be top-level (parentCommentId null) or a reply. Only authenticated users can comment. **Rest Route** The `createComment` API REST controller can be triggered via the following route: `/v1/comments` **Rest Request Parameters** The `createComment` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | postId | ID | true | request.body?.["postId"] | | content | Text | true | request.body?.["content"] | | parentCommentId | ID | false | request.body?.["parentCommentId"] | **postId** : **content** : **parentCommentId** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/comments** ```js axios({ method: 'POST', url: '/v1/comments', data: { postId:"ID", content:"Text", parentCommentId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "comment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "comment": { "id": "ID", "authorUserId": "ID", "postId": "ID", "content": "Text", "parentCommentId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Post` API Delete (soft-delete) a post. Only the author (or company admin for company posts) may delete. **Rest Route** The `deletePost` API REST controller can be triggered via the following route: `/v1/posts/:postId` **Rest Request Parameters** The `deletePost` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | postId | ID | true | request.params?.["postId"] | **postId** : 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/posts/:postId** ```js axios({ method: 'DELETE', url: `/v1/posts/${postId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "post", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "post": { "id": "ID", "content": "Text", "companyId": "ID", "authorUserId": "ID", "visibility": "Enum", "visibility_idx": "Integer", "attachmentUrls": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Post` API Update content, visibility, or attachments of an existing post by its owner or company admin (if company post). **Rest Route** The `updatePost` API REST controller can be triggered via the following route: `/v1/posts/:postId` **Rest Request Parameters** The `updatePost` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | postId | ID | true | request.params?.["postId"] | | content | Text | false | request.body?.["content"] | | companyId | ID | false | request.body?.["companyId"] | | visibility | Enum | false | request.body?.["visibility"] | | attachmentUrls | String | false | request.body?.["attachmentUrls"] | **postId** : This id paremeter is used to select the required data object that will be updated **content** : **companyId** : **visibility** : **attachmentUrls** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/posts/:postId** ```js axios({ method: 'PATCH', url: `/v1/posts/${postId}`, data: { content:"Text", companyId:"ID", visibility:"Enum", attachmentUrls:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "post", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "post": { "id": "ID", "content": "Text", "companyId": "ID", "authorUserId": "ID", "visibility": "Enum", "visibility_idx": "Integer", "attachmentUrls": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Likes` API List likes on a given post (or by user). Supports filtering by postId and userId. **Rest Route** The `listLikes` API REST controller can be triggered via the following route: `/v1/likes` **Rest Request Parameters** **Filter Parameters** The `listLikes` api supports 2 optional filter parameters for filtering list results: **postId** (`ID`): Filter by postId - Single: `?postId=` - Multiple: `?postId=&postId=` - Null: `?postId=null` **userId** (`ID`): Filter by userId - 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/likes** ```js axios({ method: 'GET', url: '/v1/likes', data: { }, params: { // Filter parameters (see Filter Parameters section above) // postId: '' // Filter by postId // 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": "likes", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "likes": [ { "id": "ID", "likedAt": "Date", "postId": "ID", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Unlike Post` API Undo a like by user for a given post. Soft-deletes the like record. **Rest Route** The `unlikePost` API REST controller can be triggered via the following route: `/v1/unlikepost/:likeId` **Rest Request Parameters** The `unlikePost` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | likeId | ID | true | request.params?.["likeId"] | **likeId** : 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/unlikepost/:likeId** ```js axios({ method: 'DELETE', url: `/v1/unlikepost/${likeId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "like", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "like": { "id": "ID", "likedAt": "Date", "postId": "ID", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Comments` API List comments for a post (or by parentComment). Supports filtering by postId and parentCommentId. Sorted by creation date ascending. **Rest Route** The `listComments` API REST controller can be triggered via the following route: `/v1/comments` **Rest Request Parameters** **Filter Parameters** The `listComments` api supports 1 optional filter parameter for filtering list results: **postId** (`ID`): Filter by postId - Single: `?postId=` - Multiple: `?postId=&postId=` - Null: `?postId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/comments** ```js axios({ method: 'GET', url: '/v1/comments', data: { }, params: { // Filter parameters (see Filter Parameters section above) // postId: '' // Filter by postId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "comments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "comments": [ { "id": "ID", "authorUserId": "ID", "postId": "ID", "content": "Text", "parentCommentId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Comment` API Get a comment by ID. Any user can read comments. Soft-deleted comments not listed unless owner. **Rest Route** The `getComment` API REST controller can be triggered via the following route: `/v1/comments/:commentId` **Rest Request Parameters** The `getComment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | commentId | ID | true | request.params?.["commentId"] | **commentId** : 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/comments/:commentId** ```js axios({ method: 'GET', url: `/v1/comments/${commentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "comment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "comment": { "id": "ID", "authorUserId": "ID", "postId": "ID", "content": "Text", "parentCommentId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Userposts` API list all posts of a user **Rest Route** The `listUserPosts` API REST controller can be triggered via the following route: `/v1/userposts` **Rest Request Parameters** **Filter Parameters** The `listUserPosts` api supports 3 optional filter parameters for filtering list results: **companyId** (`ID`): Filter by companyId - Single: `?companyId=` - Multiple: `?companyId=&companyId=` - Null: `?companyId=null` **authorUserId** (`ID`): Filter by authorUserId - Single: `?authorUserId=` - Multiple: `?authorUserId=&authorUserId=` - Null: `?authorUserId=null` **visibility** (`Enum`): Filter by visibility - Single: `?visibility=` (case-insensitive) - Multiple: `?visibility=&visibility=` - Null: `?visibility=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/userposts** ```js axios({ method: 'GET', url: '/v1/userposts', data: { }, params: { // Filter parameters (see Filter Parameters section above) // companyId: '' // Filter by companyId // authorUserId: '' // Filter by authorUserId // visibility: '' // Filter by visibility } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "posts", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "posts": [ { "id": "ID", "content": "Text", "companyId": "ID", "authorUserId": "ID", "visibility": "Enum", "visibility_idx": "Integer", "attachmentUrls": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Delete Comment` API Delete (soft-delete) a comment. Only the author may delete. **Rest Route** The `deleteComment` API REST controller can be triggered via the following route: `/v1/comments/:commentId` **Rest Request Parameters** The `deleteComment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | commentId | ID | true | request.params?.["commentId"] | **commentId** : 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/comments/:commentId** ```js axios({ method: 'DELETE', url: `/v1/comments/${commentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "comment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "comment": { "id": "ID", "authorUserId": "ID", "postId": "ID", "content": "Text", "parentCommentId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### 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 ## linkedin-messaging-service **Version:** `1.0.0` Handles direct, private 1:1 and group messaging between users, conversation management, and message history/storage.. ## 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 Messaging Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Messaging Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Messaging Service via HTTP requests for purposes such as creating, updating, deleting and querying Messaging 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 Messaging 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 Messaging 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 | linkedin-access-token| | Cookie | linkedin-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 Messaging 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 Messaging 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://linkedin.prw.mindbricks.com/messaging-api` * **Staging:** `https://linkedin-stage.mindbricks.co/messaging-api` * **Production:** `https://linkedin.mindbricks.co/messaging-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 Messaging 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 `Messaging` 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 `Messaging` 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 `Messaging` 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 Messaging 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. ### Message resource *Resource Definition* : Message posted within a conversation. Tracks content, sender, readBy, and deletedFor status per user. *Message Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **content** | Text | | | ** | | **senderUserId** | ID | | | ** | | **deletedFor** | ID | | | ** | | **readBy** | ID | | | ** | | **conversationId** | ID | | | ** | | **sentAt** | Date | | | ** | ### Conversation resource *Resource Definition* : Messaging thread among users supporting 1:1 and group. Tracks participants, group status, and last message time. *Conversation Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **isGroup** | Boolean | | | ** | | **participantIds** | ID | | | ** | | **lastMessageAt** | Date | | | ** | ## Business Api ### `List Messages` API List messages in a conversation, ordered by sentAt ascending. Only participants can view. Support filters such as min/max sentAt, unreadBy, etc. **Rest Route** The `listMessages` API REST controller can be triggered via the following route: `/v1/messages` **Rest Request Parameters** **Filter Parameters** The `listMessages` api supports 3 optional filter parameters for filtering list results: **senderUserId** (`ID`): Filter by senderUserId - Single: `?senderUserId=` - Multiple: `?senderUserId=&senderUserId=` - Null: `?senderUserId=null` **conversationId** (`ID`): Filter by conversationId - Single: `?conversationId=` - Multiple: `?conversationId=&conversationId=` - Null: `?conversationId=null` **sentAt** (`Date`): Filter by sentAt - Single date: `?sentAt=2024-01-15` - Multiple dates: `?sentAt=2024-01-15&sentAt=2024-01-20` - Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-` - Null: `?sentAt=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/messages** ```js axios({ method: 'GET', url: '/v1/messages', data: { }, params: { // Filter parameters (see Filter Parameters section above) // senderUserId: '' // Filter by senderUserId // conversationId: '' // Filter by conversationId // sentAt: '' // Filter by sentAt } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "messages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "messages": [ { "id": "ID", "content": "Text", "senderUserId": "ID", "deletedFor": "ID", "readBy": "ID", "conversationId": "ID", "sentAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Conversation` API Update conversation (e.g., participants, group flag). Only group conversations can be updated. Only current participants can update. For group: can add/remove participants; 1:1 conversations can't change participantIds or isGroup. **Rest Route** The `updateConversation` API REST controller can be triggered via the following route: `/v1/conversations/:conversationId` **Rest Request Parameters** The `updateConversation` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | | isGroup | Boolean | false | request.body?.["isGroup"] | | participantIds | ID | false | request.body?.["participantIds"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | **conversationId** : This id paremeter is used to select the required data object that will be updated **isGroup** : **participantIds** : **lastMessageAt** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/conversations/:conversationId** ```js axios({ method: 'PATCH', url: `/v1/conversations/${conversationId}`, data: { isGroup:"Boolean", participantIds:"ID", lastMessageAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "isGroup": "Boolean", "participantIds": "ID", "lastMessageAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Message` API Fetch a specific message if the requesting user is a participant in the conversation. **Rest Route** The `getMessage` API REST controller can be triggered via the following route: `/v1/messages/:messageId` **Rest Request Parameters** The `getMessage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageId | ID | true | request.params?.["messageId"] | **messageId** : 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/messages/:messageId** ```js axios({ method: 'GET', url: `/v1/messages/${messageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "content": "Text", "senderUserId": "ID", "deletedFor": "ID", "readBy": "ID", "conversationId": "ID", "sentAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Conversation` API Fetch details for a conversation thread. Only participants may view. **Rest Route** The `getConversation` API REST controller can be triggered via the following route: `/v1/conversations/:conversationId` **Rest Request Parameters** The `getConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | **conversationId** : 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/conversations/:conversationId** ```js axios({ method: 'GET', url: `/v1/conversations/${conversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "isGroup": "Boolean", "participantIds": "ID", "lastMessageAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Message` API Update content of a message or update readBy/deletedFor. Only sender may update content. Any participant can update their readBy/deletedFor entries. Content updates forbidden except for sender. **Rest Route** The `updateMessage` API REST controller can be triggered via the following route: `/v1/messages/:messageId` **Rest Request Parameters** The `updateMessage` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageId | ID | true | request.params?.["messageId"] | | content | Text | false | request.body?.["content"] | | deletedFor | ID | false | request.body?.["deletedFor"] | | readBy | ID | false | request.body?.["readBy"] | **messageId** : This id paremeter is used to select the required data object that will be updated **content** : **deletedFor** : **readBy** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/messages/:messageId** ```js axios({ method: 'PATCH', url: `/v1/messages/${messageId}`, data: { content:"Text", deletedFor:"ID", readBy:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "content": "Text", "senderUserId": "ID", "deletedFor": "ID", "readBy": "ID", "conversationId": "ID", "sentAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Conversation` API Soft-delete a conversation thread. Only participants can delete. This is 'hide for all' (e.g., group exit or complete deletion). **Rest Route** The `deleteConversation` API REST controller can be triggered via the following route: `/v1/conversations/:conversationId` **Rest Request Parameters** The `deleteConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | **conversationId** : 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/conversations/:conversationId** ```js axios({ method: 'DELETE', url: `/v1/conversations/${conversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "isGroup": "Boolean", "participantIds": "ID", "lastMessageAt": "Date", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Conversations` API List all conversations for the session user (where session userId in participantIds). Shows recent first (lastMessageAt desc). **Rest Route** The `listConversations` API REST controller can be triggered via the following route: `/v1/conversations` **Rest Request Parameters** **Filter Parameters** The `listConversations` api supports 4 optional filter parameters for filtering list results: **isGroup** (`Boolean`): Filter by isGroup - True: `?isGroup=true` - False: `?isGroup=false` - Null: `?isGroup=null` **participantIds** (`ID` array): Filter by participantIds - Single: `?participantIds=` - Multiple: `?participantIds=&participantIds=` - Null: `?participantIds=null` - Array contains: `?participantIds=&participantIds_op=contains` (default) - Array overlap: `?participantIds=&participantIds=&participantIds_op=overlap` **participantIds_op** (`String`): Operator for filtering array property "participantIds". Use "contains" to check if array contains the value, or "overlap" to check if arrays have common elements. - Single (partial match, case-insensitive): `?participantIds_op=` - Multiple: `?participantIds_op=&participantIds_op=` - Null: `?participantIds_op=null` **lastMessageAt** (`Date`): Filter by lastMessageAt - Single date: `?lastMessageAt=2024-01-15` - Multiple dates: `?lastMessageAt=2024-01-15&lastMessageAt=2024-01-20` - Special: `$today`, `$ltoday`, `$week`, `$lweek`, `$month`, `$leq-`, `$lin-` - Null: `?lastMessageAt=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/conversations** ```js axios({ method: 'GET', url: '/v1/conversations', data: { }, params: { // Filter parameters (see Filter Parameters section above) // isGroup: '' // Filter by isGroup // participantIds: '' // Filter by participantIds // participantIds_op: '' // Filter by participantIds_op // lastMessageAt: '' // Filter by lastMessageAt } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "conversations": [ { "id": "ID", "isGroup": "Boolean", "participantIds": "ID", "lastMessageAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Delete Message` API Soft-delete a message. Sender can hard-delete for all (set isActive=false). Any participant can soft-delete (add own userId to deletedFor array). **Rest Route** The `deleteMessage` API REST controller can be triggered via the following route: `/v1/messages/:messageId` **Rest Request Parameters** The `deleteMessage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageId | ID | true | request.params?.["messageId"] | **messageId** : 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/messages/:messageId** ```js axios({ method: 'DELETE', url: `/v1/messages/${messageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "content": "Text", "senderUserId": "ID", "deletedFor": "ID", "readBy": "ID", "conversationId": "ID", "sentAt": "Date", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Message` API Send a new message in a conversation. Only participants can send. On send, update conversation.lastMessageAt and set sentAt=now, senderUserId=session user. Add sender to readBy by default. Publish event for notification subsystem. **Rest Route** The `createMessage` API REST controller can be triggered via the following route: `/v1/messages` **Rest Request Parameters** The `createMessage` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | content | Text | true | request.body?.["content"] | | senderUserId | ID | true | request.body?.["senderUserId"] | | deletedFor | ID | false | request.body?.["deletedFor"] | | readBy | ID | false | request.body?.["readBy"] | | conversationId | ID | true | request.body?.["conversationId"] | | sentAt | Date | false | request.body?.["sentAt"] | **content** : **senderUserId** : **deletedFor** : **readBy** : **conversationId** : **sentAt** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/messages** ```js axios({ method: 'POST', url: '/v1/messages', data: { content:"Text", senderUserId:"ID", deletedFor:"ID", readBy:"ID", conversationId:"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": "message", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "content": "Text", "senderUserId": "ID", "deletedFor": "ID", "readBy": "ID", "conversationId": "ID", "sentAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Conversation` API Create a new conversation (thread) for messaging; can be group (isGroup) or 1:1. Participants must include the session user. For 1:1, only two users allowed; for group, at least three. If 1:1 exists, prevent duplicate. **Rest Route** The `createConversation` API REST controller can be triggered via the following route: `/v1/conversations` **Rest Request Parameters** The `createConversation` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | isGroup | Boolean | true | request.body?.["isGroup"] | | participantIds | ID | true | request.body?.["participantIds"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | **isGroup** : **participantIds** : **lastMessageAt** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/conversations** ```js axios({ method: 'POST', url: '/v1/conversations', data: { isGroup:"Boolean", participantIds:"ID", lastMessageAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "isGroup": "Boolean", "participantIds": "ID", "lastMessageAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### 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 ## linkedin-profile-service **Version:** `1.0.1` Handles user professional profiles, including experience, education, skills, languages, certifications, profile photo, and visibility controls. Enables recruiter search, elastic-style indexing, and profile editing, with all data linked to authenticated users.. ## 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 Profile Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Profile Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Profile Service via HTTP requests for purposes such as creating, updating, deleting and querying Profile 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 Profile 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 Profile 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 | linkedin-access-token| | Cookie | linkedin-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 Profile 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 Profile 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://linkedin.prw.mindbricks.com/profile-api` * **Staging:** `https://linkedin-stage.mindbricks.co/profile-api` * **Production:** `https://linkedin.mindbricks.co/profile-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 Profile 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 `Profile` 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 `Profile` 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 `Profile` 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 Profile 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. ### Profile resource *Resource Definition* : Professional profile for a user, includes core info and arrays of experience/education/skills. One profile per user... *Profile Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **summary** | Text | | | ** | | **headline** | String | | | ** | | **profilePhotoUrl** | String | | | ** | | **userId** | ID | | | ** | | **fullName** | String | | | ** | | **currentCompany** | String | | | ** | | **industry** | String | | | ** | | **languages** | String | | | ** | | **skills** | String | | | ** | | **location** | String | | | ** | | **experience** | Object | | | ** | | **profileVisibility** | Enum | | | ** | | **education** | Object | | | ** | | **certifications** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### profileVisibility Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **public** | `"public""` | 0 | | **private** | `"private""` | 1 | ### Premiumsubscription resource *Resource Definition* : premium subscription for a user *Premiumsubscription Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **profileId** | ID | | | ** | | **currency** | String | | | ** | | **status** | String | | | ** | | **price** | Double | | | ** | | **userId** | ID | | | ** | | **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. ##### 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 | ### Certification resource *Resource Definition* : Official certification available for selection in user profile (dictionary only, not user relation). *Certification Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **name** | String | | | ** | ### Language resource *Resource Definition* : Official language available for selection in user profile (dictionary only, not user relation). *Language Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **name** | String | | | ** | ### Sys_premiumsubscriptionPayment resource *Resource Definition* : A payment storage object to store the payment life cyle of orders based on premiumsubscription object. It is autocreated based on the source object's checkout config *Sys_premiumsubscriptionPayment 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 premiumsubscription 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 ### `Update Profile` API Updates the profile of the authenticated user. Includes visibility settings, skills, experience, etc. **Rest Route** The `updateProfile` API REST controller can be triggered via the following route: `/v1/profiles/:profileId` **Rest Request Parameters** The `updateProfile` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | profileId | ID | true | request.params?.["profileId"] | | summary | Text | false | request.body?.["summary"] | | headline | String | false | request.body?.["headline"] | | profilePhotoUrl | String | false | request.body?.["profilePhotoUrl"] | | fullName | String | false | request.body?.["fullName"] | | currentCompany | String | false | request.body?.["currentCompany"] | | industry | String | false | request.body?.["industry"] | | languages | String | false | request.body?.["languages"] | | skills | String | false | request.body?.["skills"] | | location | String | false | request.body?.["location"] | | experience | Object | false | request.body?.["experience"] | | profileVisibility | Enum | true | request.body?.["profileVisibility"] | | education | Object | false | request.body?.["education"] | | certifications | String | false | request.body?.["certifications"] | **profileId** : This id paremeter is used to select the required data object that will be updated **summary** : **headline** : **profilePhotoUrl** : **fullName** : **currentCompany** : **industry** : **languages** : **skills** : **location** : **experience** : **profileVisibility** : **education** : **certifications** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/profiles/:profileId** ```js axios({ method: 'PATCH', url: `/v1/profiles/${profileId}`, data: { summary:"Text", headline:"String", profilePhotoUrl:"String", fullName:"String", currentCompany:"String", industry:"String", languages:"String", skills:"String", location:"String", experience:"Object", profileVisibility:"Enum", education:"Object", certifications:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "profile", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "profile": { "id": "ID", "summary": "Text", "headline": "String", "profilePhotoUrl": "String", "userId": "ID", "fullName": "String", "currentCompany": "String", "industry": "String", "languages": "String", "skills": "String", "location": "String", "experience": "Object", "profileVisibility": "Enum", "profileVisibility_idx": "Integer", "education": "Object", "certifications": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Profile` API Deletes the profile of the authenticated user (soft delete). **Rest Route** The `deleteProfile` API REST controller can be triggered via the following route: `/v1/profiles/:profileId` **Rest Request Parameters** The `deleteProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | profileId | ID | true | request.params?.["profileId"] | **profileId** : 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/profiles/:profileId** ```js axios({ method: 'DELETE', url: `/v1/profiles/${profileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "profile", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "profile": { "id": "ID", "summary": "Text", "headline": "String", "profilePhotoUrl": "String", "userId": "ID", "fullName": "String", "currentCompany": "String", "industry": "String", "languages": "String", "skills": "String", "location": "String", "experience": "Object", "profileVisibility": "Enum", "profileVisibility_idx": "Integer", "education": "Object", "certifications": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Language` API Deletes a language entry from the dictionary. **Rest Route** The `deleteLanguage` API REST controller can be triggered via the following route: `/v1/languages/:languageId` **Rest Request Parameters** The `deleteLanguage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | languageId | ID | true | request.params?.["languageId"] | **languageId** : 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/languages/:languageId** ```js axios({ method: 'DELETE', url: `/v1/languages/${languageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "language", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "language": { "id": "ID", "name": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Language` API Edit an existing language entry. **Rest Route** The `updateLanguage` API REST controller can be triggered via the following route: `/v1/languages/:languageId` **Rest Request Parameters** The `updateLanguage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | languageId | ID | true | request.params?.["languageId"] | **languageId** : 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 **PATCH /v1/languages/:languageId** ```js axios({ method: 'PATCH', url: `/v1/languages/${languageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "language", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "language": { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Profiles` API Lists profiles by search/filter. Only public profiles are listed, unless the current user is the owner. **Rest Route** The `listProfiles` API REST controller can be triggered via the following route: `/v1/profiles` **Rest Request Parameters** **Filter Parameters** The `listProfiles` api supports 5 optional filter parameters for filtering list results: **headline** (`String`): Filter by headline - Single (partial match, case-insensitive): `?headline=` - Multiple: `?headline=&headline=` - Null: `?headline=null` **fullName** (`String`): Filter by fullName - Single (partial match, case-insensitive): `?fullName=` - Multiple: `?fullName=&fullName=` - Null: `?fullName=null` **currentCompany** (`String`): Filter by currentCompany - Single (partial match, case-insensitive): `?currentCompany=` - Multiple: `?currentCompany=¤tCompany=` - Null: `?currentCompany=null` **industry** (`String`): Filter by industry - Single (partial match, case-insensitive): `?industry=` - Multiple: `?industry=&industry=` - Null: `?industry=null` **location** (`String`): Filter by location - Single (partial match, case-insensitive): `?location=` - Multiple: `?location=&location=` - Null: `?location=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/profiles** ```js axios({ method: 'GET', url: '/v1/profiles', data: { }, params: { // Filter parameters (see Filter Parameters section above) // headline: '' // Filter by headline // fullName: '' // Filter by fullName // currentCompany: '' // Filter by currentCompany // industry: '' // Filter by industry // location: '' // Filter by location } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "profiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "profiles": [ { "id": "ID", "summary": "Text", "headline": "String", "profilePhotoUrl": "String", "userId": "ID", "fullName": "String", "currentCompany": "String", "industry": "String", "languages": "String", "skills": "String", "location": "String", "experience": "Object", "profileVisibility": "Enum", "profileVisibility_idx": "Integer", "education": "Object", "certifications": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Languages` API Lists all available languages for profile selection. **Rest Route** The `listLanguages` API REST controller can be triggered via the following route: `/v1/languages` **Rest Request Parameters** **Filter Parameters** The `listLanguages` api supports 1 optional filter parameter for filtering list results: **name** (`String`): Filter by name - Single (partial match, case-insensitive): `?name=` - Multiple: `?name=&name=` - Null: `?name=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/languages** ```js axios({ method: 'GET', url: '/v1/languages', data: { }, params: { // Filter parameters (see Filter Parameters section above) // name: '' // Filter by name } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "languages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "languages": [ { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Language` API Retrieves a language entry by ID. **Rest Route** The `getLanguage` API REST controller can be triggered via the following route: `/v1/languages/:languageId` **Rest Request Parameters** The `getLanguage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | languageId | ID | true | request.params?.["languageId"] | **languageId** : 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/languages/:languageId** ```js axios({ method: 'GET', url: `/v1/languages/${languageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "language", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "language": { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Language` API Add a new language to the dictionary for user profiles. Must be unique by name. **Rest Route** The `createLanguage` API REST controller can be triggered via the following route: `/v1/languages` **Rest Request Parameters** The `createLanguage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | **name** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/languages** ```js axios({ method: 'POST', url: '/v1/languages', data: { name:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "language", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "language": { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Profile` API Creates a new professional profile for the authenticated user. Each user can create only one profile. **Rest Route** The `createProfile` API REST controller can be triggered via the following route: `/v1/profiles` **Rest Request Parameters** The `createProfile` api has got 13 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | summary | Text | false | request.body?.["summary"] | | headline | String | false | request.body?.["headline"] | | profilePhotoUrl | String | false | request.body?.["profilePhotoUrl"] | | fullName | String | true | request.body?.["fullName"] | | currentCompany | String | false | request.body?.["currentCompany"] | | industry | String | false | request.body?.["industry"] | | languages | String | false | request.body?.["languages"] | | skills | String | false | request.body?.["skills"] | | location | String | false | request.body?.["location"] | | experience | Object | false | request.body?.["experience"] | | profileVisibility | Enum | true | request.body?.["profileVisibility"] | | education | Object | false | request.body?.["education"] | | certifications | String | false | request.body?.["certifications"] | **summary** : **headline** : **profilePhotoUrl** : **fullName** : **currentCompany** : **industry** : **languages** : **skills** : **location** : **experience** : **profileVisibility** : **education** : **certifications** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/profiles** ```js axios({ method: 'POST', url: '/v1/profiles', data: { summary:"Text", headline:"String", profilePhotoUrl:"String", fullName:"String", currentCompany:"String", industry:"String", languages:"String", skills:"String", location:"String", experience:"Object", profileVisibility:"Enum", education:"Object", certifications:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "profile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "profile": { "id": "ID", "summary": "Text", "headline": "String", "profilePhotoUrl": "String", "userId": "ID", "fullName": "String", "currentCompany": "String", "industry": "String", "languages": "String", "skills": "String", "location": "String", "experience": "Object", "profileVisibility": "Enum", "profileVisibility_idx": "Integer", "education": "Object", "certifications": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Profile` API Retrieves a user profile by ID. If private, only the owner can get; if public, anyone can view. **Rest Route** The `getProfile` API REST controller can be triggered via the following route: `/v1/profiles/:profileId` **Rest Request Parameters** The `getProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | profileId | ID | true | request.params?.["profileId"] | **profileId** : 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/profiles/:profileId** ```js axios({ method: 'GET', url: `/v1/profiles/${profileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "profile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "profile": { "id": "ID", "summary": "Text", "headline": "String", "profilePhotoUrl": "String", "userId": "ID", "fullName": "String", "currentCompany": "String", "industry": "String", "languages": "String", "skills": "String", "location": "String", "experience": "Object", "profileVisibility": "Enum", "profileVisibility_idx": "Integer", "education": "Object", "certifications": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Premuimsub` API **Rest Route** The `deletePremuimSub` API REST controller can be triggered via the following route: `/v1/premuimsub/:premiumsubscriptionId` **Rest Request Parameters** The `deletePremuimSub` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | premiumsubscriptionId | ID | true | request.params?.["premiumsubscriptionId"] | **premiumsubscriptionId** : 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/premuimsub/:premiumsubscriptionId** ```js axios({ method: 'DELETE', url: `/v1/premuimsub/${premiumsubscriptionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "premiumsubscription", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Certification` API Edit an existing certification entry. **Rest Route** The `updateCertification` API REST controller can be triggered via the following route: `/v1/certifications/:certificationId` **Rest Request Parameters** The `updateCertification` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | certificationId | ID | true | request.params?.["certificationId"] | **certificationId** : 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 **PATCH /v1/certifications/:certificationId** ```js axios({ method: 'PATCH', url: `/v1/certifications/${certificationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "certification", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "certification": { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Premuimsub` API **Rest Route** The `createPremuimSub` API REST controller can be triggered via the following route: `/v1/premuimsub` **Rest Request Parameters** The `createPremuimSub` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | profileId | ID | true | request.body?.["profileId"] | | currency | String | true | request.body?.["currency"] | | status | String | true | request.body?.["status"] | | price | Double | true | request.body?.["price"] | | userId | ID | true | request.body?.["userId"] | **profileId** : **currency** : **status** : **price** : **userId** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/premuimsub** ```js axios({ method: 'POST', url: '/v1/premuimsub', data: { profileId:"ID", currency:"String", status:"String", price:"Double", userId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "premiumsubscription", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Certifications` API Lists all available certifications for profile selection/display. **Rest Route** The `listCertifications` API REST controller can be triggered via the following route: `/v1/certifications` **Rest Request Parameters** **Filter Parameters** The `listCertifications` api supports 1 optional filter parameter for filtering list results: **name** (`String`): Filter by name - Single (partial match, case-insensitive): `?name=` - Multiple: `?name=&name=` - Null: `?name=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/certifications** ```js axios({ method: 'GET', url: '/v1/certifications', data: { }, params: { // Filter parameters (see Filter Parameters section above) // name: '' // Filter by name } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "certifications", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "certifications": [ { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Premuimsub` API **Rest Route** The `updatePremuimSub` API REST controller can be triggered via the following route: `/v1/premuimsub/:premiumsubscriptionId` **Rest Request Parameters** The `updatePremuimSub` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | premiumsubscriptionId | ID | true | request.params?.["premiumsubscriptionId"] | | profileId | ID | false | request.body?.["profileId"] | | currency | String | false | request.body?.["currency"] | | status | String | false | request.body?.["status"] | | price | Double | false | request.body?.["price"] | | userId | ID | false | request.body?.["userId"] | **premiumsubscriptionId** : This id paremeter is used to select the required data object that will be updated **profileId** : **currency** : **status** : **price** : **userId** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/premuimsub/:premiumsubscriptionId** ```js axios({ method: 'PATCH', url: `/v1/premuimsub/${premiumsubscriptionId}`, data: { profileId:"ID", currency:"String", status:"String", price:"Double", userId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "premiumsubscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Premuimsub` API **Rest Route** The `getPremuimSub` API REST controller can be triggered via the following route: `/v1/premuimsub/:premiumsubscriptionId` **Rest Request Parameters** The `getPremuimSub` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | premiumsubscriptionId | ID | true | request.params?.["premiumsubscriptionId"] | **premiumsubscriptionId** : 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/premuimsub/:premiumsubscriptionId** ```js axios({ method: 'GET', url: `/v1/premuimsub/${premiumsubscriptionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "premiumsubscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Certification` API Add a new certification for user profiles. Must be unique by name. **Rest Route** The `createCertification` API REST controller can be triggered via the following route: `/v1/certifications` **Rest Request Parameters** The `createCertification` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | **name** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/certifications** ```js axios({ method: 'POST', url: '/v1/certifications', data: { name:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "certification", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "certification": { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Certification` API Retrieves a certification entry by ID. **Rest Route** The `getCertification` API REST controller can be triggered via the following route: `/v1/certifications/:certificationId` **Rest Request Parameters** The `getCertification` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | certificationId | ID | true | request.params?.["certificationId"] | **certificationId** : 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/certifications/:certificationId** ```js axios({ method: 'GET', url: `/v1/certifications/${certificationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "certification", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "certification": { "id": "ID", "name": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Premuimsub` API **Rest Route** The `listPremuimSub` API REST controller can be triggered via the following route: `/v1/premuimsub` **Rest Request Parameters** **Filter Parameters** The `listPremuimSub` api supports 6 optional filter parameters for filtering list results: **subscriptionProfileId** (`ID`): Filter by subscriptionProfileId - Single: `?subscriptionProfileId=` - Multiple: `?subscriptionProfileId=&subscriptionProfileId=` - Null: `?subscriptionProfileId=null` **subscriptionCurrency** (`String`): Filter by subscriptionCurrency - Single (partial match, case-insensitive): `?subscriptionCurrency=` - Multiple: `?subscriptionCurrency=&subscriptionCurrency=` - Null: `?subscriptionCurrency=null` **subscriptionStatus** (`String`): Filter by subscriptionStatus - Single (partial match, case-insensitive): `?subscriptionStatus=` - Multiple: `?subscriptionStatus=&subscriptionStatus=` - Null: `?subscriptionStatus=null` **subscriptionPrice** (`Double`): Filter by subscriptionPrice - Single: `?subscriptionPrice=` - Multiple: `?subscriptionPrice=&subscriptionPrice=` - Range: `?subscriptionPrice=$lt-`, `$lte-`, `$gt-`, `$gte-`, `$btw--` - Null: `?subscriptionPrice=null` **subscriptionUserId** (`ID`): Filter by subscriptionUserId - Single: `?subscriptionUserId=` - Multiple: `?subscriptionUserId=&subscriptionUserId=` - Null: `?subscriptionUserId=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/premuimsub** ```js axios({ method: 'GET', url: '/v1/premuimsub', data: { }, params: { // Filter parameters (see Filter Parameters section above) // subscriptionProfileId: '' // Filter by subscriptionProfileId // subscriptionCurrency: '' // Filter by subscriptionCurrency // subscriptionStatus: '' // Filter by subscriptionStatus // subscriptionPrice: '' // Filter by subscriptionPrice // subscriptionUserId: '' // Filter by subscriptionUserId // 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": "premiumsubscriptions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "premiumsubscriptions": [ { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Delete Certification` API Deletes a certification entry from the dictionary. **Rest Route** The `deleteCertification` API REST controller can be triggered via the following route: `/v1/certifications/:certificationId` **Rest Request Parameters** The `deleteCertification` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | certificationId | ID | true | request.params?.["certificationId"] | **certificationId** : 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/certifications/:certificationId** ```js axios({ method: 'DELETE', url: `/v1/certifications/${certificationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "certification", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "certification": { "id": "ID", "name": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Premiumsubscriptionpayment` API This route is used to get the payment information by ID. **Rest Route** The `getPremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpayment/:sys_premiumsubscriptionPaymentId` **Rest Request Parameters** The `getPremiumsubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_premiumsubscriptionPaymentId | ID | true | request.params?.["sys_premiumsubscriptionPaymentId"] | **sys_premiumsubscriptionPaymentId** : 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/premiumsubscriptionpayment/:sys_premiumsubscriptionPaymentId** ```js axios({ method: 'GET', url: `/v1/premiumsubscriptionpayment/${sys_premiumsubscriptionPaymentId}`, 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_premiumsubscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_premiumsubscriptionPayment": { "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 Premiumsubscriptionpayments` API This route is used to list all payments. **Rest Route** The `listPremiumsubscriptionPayments` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpayments` **Rest Request Parameters** **Filter Parameters** The `listPremiumsubscriptionPayments` 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 premiumsubscription 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/premiumsubscriptionpayments** ```js axios({ method: 'GET', url: '/v1/premiumsubscriptionpayments', 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_premiumsubscriptionPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_premiumsubscriptionPayments": [ { "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 Premiumsubscriptionpayment` API This route is used to create a new payment. **Rest Route** The `createPremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpayment` **Rest Request Parameters** The `createPremiumsubscriptionPayment` 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 premiumsubscription 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/premiumsubscriptionpayment** ```js axios({ method: 'POST', url: '/v1/premiumsubscriptionpayment', 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_premiumsubscriptionPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_premiumsubscriptionPayment": { "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 Premiumsubscriptionpayment` API This route is used to update an existing payment. **Rest Route** The `updatePremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpayment/:sys_premiumsubscriptionPaymentId` **Rest Request Parameters** The `updatePremiumsubscriptionPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_premiumsubscriptionPaymentId | ID | true | request.params?.["sys_premiumsubscriptionPaymentId"] | | 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_premiumsubscriptionPaymentId** : 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/premiumsubscriptionpayment/:sys_premiumsubscriptionPaymentId** ```js axios({ method: 'PATCH', url: `/v1/premiumsubscriptionpayment/${sys_premiumsubscriptionPaymentId}`, 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_premiumsubscriptionPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_premiumsubscriptionPayment": { "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 Premiumsubscriptionpayment` API This route is used to delete a payment. **Rest Route** The `deletePremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpayment/:sys_premiumsubscriptionPaymentId` **Rest Request Parameters** The `deletePremiumsubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_premiumsubscriptionPaymentId | ID | true | request.params?.["sys_premiumsubscriptionPaymentId"] | **sys_premiumsubscriptionPaymentId** : 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/premiumsubscriptionpayment/:sys_premiumsubscriptionPaymentId** ```js axios({ method: 'DELETE', url: `/v1/premiumsubscriptionpayment/${sys_premiumsubscriptionPaymentId}`, 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_premiumsubscriptionPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_premiumsubscriptionPayment": { "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 Premiumsubscriptionpaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getPremiumsubscriptionPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpaymentbyorderid/:orderId` **Rest Request Parameters** The `getPremiumsubscriptionPaymentByOrderId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source premiumsubscription 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/premiumsubscriptionpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/premiumsubscriptionpaymentbyorderid/${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_premiumsubscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_premiumsubscriptionPayment": { "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 Premiumsubscriptionpaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getPremiumsubscriptionPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/premiumsubscriptionpaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getPremiumsubscriptionPaymentByPaymentId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | **paymentId** : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/premiumsubscriptionpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/premiumsubscriptionpaymentbypaymentid/${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_premiumsubscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_premiumsubscriptionPayment": { "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 Premiumsubscriptionpayment` API Start payment for premiumsubscription **Rest Route** The `startPremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/startpremiumsubscriptionpayment/:premiumsubscriptionId` **Rest Request Parameters** The `startPremiumsubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | premiumsubscriptionId | ID | true | request.params?.["premiumsubscriptionId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **premiumsubscriptionId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startpremiumsubscriptionpayment/:premiumsubscriptionId** ```js axios({ method: 'PATCH', url: `/v1/startpremiumsubscriptionpayment/${premiumsubscriptionId}`, 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": "premiumsubscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Refresh Premiumsubscriptionpayment` API Refresh payment info for premiumsubscription from Stripe **Rest Route** The `refreshPremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/refreshpremiumsubscriptionpayment/:premiumsubscriptionId` **Rest Request Parameters** The `refreshPremiumsubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | premiumsubscriptionId | ID | true | request.params?.["premiumsubscriptionId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **premiumsubscriptionId** : 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/refreshpremiumsubscriptionpayment/:premiumsubscriptionId** ```js axios({ method: 'PATCH', url: `/v1/refreshpremiumsubscriptionpayment/${premiumsubscriptionId}`, 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": "premiumsubscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Callback Premiumsubscriptionpayment` API Refresh payment values by gateway webhook call for premiumsubscription **Rest Route** The `callbackPremiumsubscriptionPayment` API REST controller can be triggered via the following route: `/v1/callbackpremiumsubscriptionpayment` **Rest Request Parameters** The `callbackPremiumsubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | premiumsubscriptionId | ID | false | request.body?.["premiumsubscriptionId"] | **premiumsubscriptionId** : 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/callbackpremiumsubscriptionpayment** ```js axios({ method: 'POST', url: '/v1/callbackpremiumsubscriptionpayment', data: { premiumsubscriptionId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "premiumsubscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "premiumsubscription": { "id": "ID", "profileId": "ID", "currency": "String", "status": "String", "price": "Double", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Get Paymentcustomerbyuserid` API This route is used to get the payment customer information by user id. **Rest Route** The `getPaymentCustomerByUserId` API REST controller can be triggered via the following route: `/v1/paymentcustomers/:userId` **Rest Request Parameters** The `getPaymentCustomerByUserId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```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** The `listPaymentCustomerMethods` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who owns the payment method. The parameter is used to query data. **Filter Parameters** The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results: **paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform. - 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": [] } ``` ### 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 ## linkedin-agenthub-service **Version:** `1.0.0` AI Agent Hub ## 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 AgentHub Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AgentHub Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the AgentHub Service via HTTP requests for purposes such as creating, updating, deleting and querying AgentHub 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 AgentHub 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 AgentHub 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 | linkedin-access-token| | Cookie | linkedin-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 AgentHub 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 AgentHub 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://linkedin.prw.mindbricks.com/agenthub-api` * **Staging:** `https://linkedin-stage.mindbricks.co/agenthub-api` * **Production:** `https://linkedin.mindbricks.co/agenthub-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 AgentHub 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 `AgentHub` 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 `AgentHub` 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 `AgentHub` 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 AgentHub 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. ### Sys_agentOverride resource *Resource Definition* : Runtime overrides for design-time agents. Null fields use the design default. *Sys_agentOverride Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **agentName** | String | | | *Design-time agent name this override applies to.* | | **provider** | String | | | *Override AI provider (e.g., openai, anthropic).* | | **model** | String | | | *Override model name.* | | **systemPrompt** | Text | | | *Override system prompt.* | | **temperature** | Double | | | *Override temperature (0-2).* | | **maxTokens** | Integer | | | *Override max tokens.* | | **responseFormat** | String | | | *Override response format (text/json).* | | **selectedTools** | Object | | | *Array of tool names from the catalog that this agent can use.* | | **guardrails** | Object | | | *Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.* | | **enabled** | Boolean | | | *Enable or disable this agent.* | | **updatedBy** | ID | | | *User who last updated this override.* | ### Sys_agentExecution resource *Resource Definition* : Agent execution log. Records each agent invocation with input, output, and performance metrics. *Sys_agentExecution Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **agentName** | String | | | *Agent that was executed.* | | **agentType** | Enum | | | *Whether this was a design-time or dynamic agent.* | | **source** | Enum | | | *How the agent was triggered.* | | **userId** | ID | | | *User who triggered the execution.* | | **input** | Object | | | *Request input (truncated for large payloads).* | | **output** | Object | | | *Response output (truncated for large payloads).* | | **toolCalls** | Integer | | | *Number of tool calls made during execution.* | | **tokenUsage** | Object | | | *Token usage: { prompt, completion, total }.* | | **durationMs** | Integer | | | *Execution time in milliseconds.* | | **status** | Enum | | | *Execution status.* | | **error** | Text | | | *Error message if execution failed.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### agentType Enum Property *Property Definition* : Whether this was a design-time or dynamic agent.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **design** | `"design""` | 0 | | **dynamic** | `"dynamic""` | 1 | ##### source Enum Property *Property Definition* : How the agent was triggered.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **rest** | `"rest""` | 0 | | **sse** | `"sse""` | 1 | | **kafka** | `"kafka""` | 2 | | **agent** | `"agent""` | 3 | ##### status Enum Property *Property Definition* : Execution status.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **success** | `"success""` | 0 | | **error** | `"error""` | 1 | | **timeout** | `"timeout""` | 2 | ### Sys_toolCatalog resource *Resource Definition* : Cached tool catalog discovered from project services. Refreshed periodically. *Sys_toolCatalog Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **toolName** | String | | | *Full tool name (e.g., service:apiName).* | | **serviceName** | String | | | *Source service name.* | | **description** | Text | | | *Tool description.* | | **parameters** | Object | | | *JSON Schema of tool parameters.* | | **lastRefreshed** | Date | | | *When this tool was last discovered/refreshed.* | ## Business Api ### `Get Agentoverride` API **[Default get API]** — This is the designated default `get` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `getAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'GET', url: `/v1/agentoverride/${sys_agentOverrideId}`, 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_agentOverride", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentoverrides` API **[Default list API]** — This is the designated default `list` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentOverrides` API REST controller can be triggered via the following route: `/v1/agentoverrides` **Rest Request Parameters** The `listAgentOverrides` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverrides** ```js axios({ method: 'GET', url: '/v1/agentoverrides', 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_agentOverrides", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentOverrides": [ { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Agentoverride` API **[Default update API]** — This is the designated default `update` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `updateAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `updateAgentOverride` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | | provider | String | | request.body?.["provider"] | | model | String | | request.body?.["model"] | | systemPrompt | Text | | request.body?.["systemPrompt"] | | temperature | Double | | request.body?.["temperature"] | | maxTokens | Integer | | request.body?.["maxTokens"] | | responseFormat | String | | request.body?.["responseFormat"] | | selectedTools | Object | | request.body?.["selectedTools"] | | guardrails | Object | | request.body?.["guardrails"] | | enabled | Boolean | | request.body?.["enabled"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be updated **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **enabled** : Enable or disable this agent. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'PATCH', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", enabled:"Boolean", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Create Agentoverride` API **[Default create API]** — This is the designated default `create` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `createAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride` **Rest Request Parameters** The `createAgentOverride` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | agentName | String | true | request.body?.["agentName"] | | provider | String | false | request.body?.["provider"] | | model | String | false | request.body?.["model"] | | systemPrompt | Text | false | request.body?.["systemPrompt"] | | temperature | Double | false | request.body?.["temperature"] | | maxTokens | Integer | false | request.body?.["maxTokens"] | | responseFormat | String | false | request.body?.["responseFormat"] | | selectedTools | Object | false | request.body?.["selectedTools"] | | guardrails | Object | false | request.body?.["guardrails"] | **agentName** : Design-time agent name this override applies to. **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/agentoverride** ```js axios({ method: 'POST', url: '/v1/agentoverride', data: { agentName:"String", provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Delete Agentoverride` API **[Default delete API]** — This is the designated default `delete` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `deleteAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'DELETE', url: `/v1/agentoverride/${sys_agentOverrideId}`, 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_agentOverride", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `List Toolcatalog` API **[Default list API]** — This is the designated default `list` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listToolCatalog` API REST controller can be triggered via the following route: `/v1/toolcatalog` **Rest Request Parameters** **Filter Parameters** The `listToolCatalog` api supports 1 optional filter parameter for filtering list results: **serviceName** (`String`): Source service name. - Single (partial match, case-insensitive): `?serviceName=` - Multiple: `?serviceName=&serviceName=` - Null: `?serviceName=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalog** ```js axios({ method: 'GET', url: '/v1/toolcatalog', data: { }, params: { // Filter parameters (see Filter Parameters section above) // serviceName: '' // Filter by serviceName } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_toolCatalogs": [ { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Toolcatalogentry` API **[Default get API]** — This is the designated default `get` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getToolCatalogEntry` API REST controller can be triggered via the following route: `/v1/toolcatalogentry/:sys_toolCatalogId` **Rest Request Parameters** The `getToolCatalogEntry` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_toolCatalogId | ID | true | request.params?.["sys_toolCatalogId"] | **sys_toolCatalogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalogentry/:sys_toolCatalogId** ```js axios({ method: 'GET', url: `/v1/toolcatalogentry/${sys_toolCatalogId}`, 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_toolCatalog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_toolCatalog": { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentexecutions` API **[Default list API]** — This is the designated default `list` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentExecutions` API REST controller can be triggered via the following route: `/v1/agentexecutions` **Rest Request Parameters** **Filter Parameters** The `listAgentExecutions` api supports 5 optional filter parameters for filtering list results: **agentName** (`String`): Agent that was executed. - Single (partial match, case-insensitive): `?agentName=` - Multiple: `?agentName=&agentName=` - Null: `?agentName=null` **agentType** (`Enum`): Whether this was a design-time or dynamic agent. - Single: `?agentType=` (case-insensitive) - Multiple: `?agentType=&agentType=` - Null: `?agentType=null` **source** (`Enum`): How the agent was triggered. - Single: `?source=` (case-insensitive) - Multiple: `?source=&source=` - Null: `?source=null` **userId** (`ID`): User who triggered the execution. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **status** (`Enum`): Execution status. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecutions** ```js axios({ method: 'GET', url: '/v1/agentexecutions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // agentName: '' // Filter by agentName // agentType: '' // Filter by agentType // source: '' // Filter by source // userId: '' // Filter by userId // status: '' // Filter by status } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecutions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentExecutions": [ { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Agentexecution` API **[Default get API]** — This is the designated default `get` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentExecution` API REST controller can be triggered via the following route: `/v1/agentexecution/:sys_agentExecutionId` **Rest Request Parameters** The `getAgentExecution` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentExecutionId | ID | true | request.params?.["sys_agentExecutionId"] | **sys_agentExecutionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecution/:sys_agentExecutionId** ```js axios({ method: 'GET', url: `/v1/agentexecution/${sys_agentExecutionId}`, 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_agentExecution", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentExecution": { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### 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 ## BFF SERVICE **Version:** `1.0.0` BFF service is a microservice that acts as a bridge between the client and the backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance. ## 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 BFF Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our BFF Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the BFF Service via HTTP requests for purposes such as listing, filtering, and searching data. **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 BFF 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. --- ## Resources ### Elastic Index Resource _Resource Definition_: A virtual resource representing dynamic search data from a specified index. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/:indexName/list` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-----------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ```

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property.

--- _Default access route_: _GET_ `/:indexName/list` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-----------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/${indexName}/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/:indexName/count` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/:indexName/count` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | q | String | No | query.q | ```js axios({ method: "GET", url: `/${indexName}/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/:indexName/schema` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | ```js axios({ method: "GET", url: `/${indexName}/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /:indexName/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | ```js axios({ method: "GET", url: `/${indexName}/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /:indexName/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/filters`, data: { filterName: "String", conditions: "Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /:indexName/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | filterId | String | Yes | path.param | ```js axios({ method: "DELETE", url: `/${indexName}/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/:indexName/:id` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/${indexName}/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- --- # REST API GUIDE ## NOTIFICATION SERVICE **Version:** `1.0.0` The Notification service is a microservice that allows sending notifications through SMS, Email, and Push channels. Providers can be configured dynamically through the `.env` file. ## 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 Notification Service REST API. This document provides a comprehensive overview of the available endpoints, how they work, and how to use them efficiently. **Intended Audience** This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the Notification Service. It assumes familiarity with microservices architecture and RESTful APIs. **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 Notification Service also supports alternative methods of interaction, such as messaging via a Kafka message broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. --- ## Routes ### Route: Register Device _Route Definition_: Registers a device for a user. _Route Type_: create _Default access route_: _POST_ `/devices/register` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | device | Object | Yes | body | | userId | ID | Yes | req.userId | ```js axios({ method: "POST", url: `/devices/register`, data: { device:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Unregister Device _Route Definition_: Removes a registered device. _Route Type_: delete _Default access route_: _DELETE_ `/devices/unregister/:deviceId` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | deviceId | ID | Yes | path.param | | userId | ID | Yes | req.userId | ```js axios({ method: "DELETE", url: `/devices/unregister/${deviceId}`, data:{}, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Get Notifications _Route Definition_: Retrieves a paginated list of notifications. _Route Type_: get _Default access route_: _GET_ `/notifications` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy| | userId | ID | Yes | req.userId | ```js axios({ method: "GET", url: `/notifications`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Send Notification _Route Definition_: Sends a notification to specified recipients. _Route Type_: create _Default access route_: _POST_ `/notifications` ### Parameters | Parameter | Type | Required | Population | |---------------|--------|----------|------------| |notification | Object | Yes | body | ```js axios({ method: "POST", url: `/notifications`, data: { notification:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Mark Notifications as Seen _Route Definition_: Marks selected notifications as seen. _Route Type_: update _Default access route_: _POST_ `/notifications/seen` ### Parameters | Parameter | Type | Required | Population | |------------------ |--------|----------|------------| | notificationIds | Array | Yes | body | | userId | ID | Yes | req.userId | ```js axios({ method: "POST", url: `/notifications/seen`, data: { notificationIds:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. --- --- --- *Generated by Mindbricks Genesis Engine*