WebAPI vs OpenAPI Comparison
The Lovrabet data platform provides two complete API systems: WebAPI and OpenAPI. Each has its own characteristics and is suitable for different business scenarios. This article provides an in-depth comparison to help you choose the most appropriate integration method.
Core Differences Overview
| Dimension | WebAPI (Cookie Mode) | OpenAPI (Token/AccessKey Mode) |
|---|---|---|
| Authentication | Browser Cookie (user session) | HMAC-SHA256 signature (Token/AccessKey) |
| Environment | Browser only | Node.js server + Browser |
| Use Cases | Logged-in users accessing private data | Server integration, third-party systems, public data access |
| API Path Format | /api/{appCode}/{datasetCode}/{method} | /openapi/data/{method} |
| Request Body | Direct parameters { currentPage, pageSize } | Wrapped structure { appCode, datasetCode, paramMap } |
| Auth Headers | No special headers required | Must provide X-Token, X-Time-Stamp, etc. |
| Security | Relies on Lovrabet platform session | Independent signature verification + Token expiration control |
| Data Permissions | Based on user login permissions | Based on application authorization scope |
| CORS Handling | Requires credentials: 'include' | Standard CORS |
Industry Comparison and Positioning
WebAPI - Similar to "Session API"
WebAPI is similar to traditional web application Session-based API, commonly found in:
- SaaS platform user interface APIs - Like Salesforce, Notion web application internal APIs
- Embedded integration - Embedded in parent applications via iframe, sharing login state
- Single Page Applications (SPA) - React/Vue applications calling their own backend
Characteristics:
- Strong dependency on user login state
- No key and signature management required
- Permissions inherited from user roles
- Suitable for user-level operations
OpenAPI - Similar to "RESTful API"
OpenAPI follows industry-standard API-Key based authentication, similar to:
- AWS API - Using Access Key + Secret Key for HMAC signing
- Stripe API - Using API Key for authentication
- GitHub API - Using Personal Access Token
- Twilio API - Using Account SID + Auth Token
Characteristics:
- Independent authentication system, not dependent on user login
- Supports server-to-server (S2S) calls
- Suitable for system integration and automation
- Suitable for application-level operations
Detailed Comparison
1. Authentication Mechanisms
WebAPI - Cookie Authentication
import { createClient } from "@lovrabet/sdk";
// ✅ No authentication information needed
const client = createClient({
appCode: "your-app-code",
models: {
users: { tableName: "users", datasetCode: "ds-001" },
},
});
// Automatically uses browser Cookie, request will include credentials: 'include'
const users = await client.models.users.filter();
Advantages:
- Zero configuration, no key management needed
- Automatically inherits user permissions
- Suitable for rapid development
Disadvantages:
- Browser environment only
- Must be under Lovrabet domain or configure CORS
- Cannot be used for server-side or third-party integration
OpenAPI - Token/AccessKey Authentication
Mode 1: Server-side using AccessKey
import { createClient } from "@lovrabet/sdk";
const client = createClient({
appCode: "your-app-code",
accessKey: process.env.LOVRABET_ACCESS_KEY, // ⚠️ Only use on server-side
models: {
users: { tableName: "users", datasetCode: "ds-001" },
},
});
// SDK automatically generates signature: HMAC-SHA256(accessKey + timestamp + appCode + datasetCode)
const users = await client.models.users.filter();
Mode 2: Browser using pre-generated Token
// Server-side generates Token
import { generateOpenApiToken } from "@lovrabet/sdk";
const { token, timestamp, expiresAt } = await generateOpenApiToken({
appCode: "your-app-code",
datasetCode: "ds-001",
accessKey: process.env.LOVRABET_ACCESS_KEY,
});
// Browser uses Token
const client = createClient({
appCode: "your-app-code",
token: token,
timestamp: timestamp,
models: {
users: { tableName: "users", datasetCode: "ds-001" },
},
});
Advantages:
- Supports both server-side and browser
- Independent authentication, not dependent on user login
- Suitable for system integration and automation
- Fine-grained permission control
Disadvantages:
- AccessKey must be securely stored
- Token has expiration, needs refresh
- Browser requires additional Token generation endpoint
2. API Path Differences
WebAPI Path Structure
/api/{appCode}/{datasetCode}/{method}
Examples:
POST /api/app-c2dd52a2/0fefba76fe29440194841f4825df53ff/getList
POST /api/app-c2dd52a2/0fefba76fe29440194841f4825df53ff/getOne
POST /api/app-c2dd52a2/0fefba76fe29440194841f4825df53ff/create
Characteristics:
- RESTful style, path includes resource identifier
- Method names use camelCase (
getList,getOne) appCodeanddatasetCodeincluded in path
OpenAPI Path Structure
/openapi/data/{method} # Data operations
/openapi/dataset/{method} # Dataset metadata
Examples:
POST /openapi/data/get-list # Batch query
POST /openapi/data/get-one # Single record query
POST /openapi/data/create # Create data
Characteristics:
- Unified API endpoint
- Method names use kebab-case (
get-list,get-one) appCodeanddatasetCodepassed in request body and headers
3. Request Body Structure Differences
WebAPI Request Body
// getList request
POST /api/app-c2dd52a2/ds-001/getList
Content-Type: application/json
{
"currentPage": 1,
"pageSize": 20,
"status": "active",
"ytSortList": [
{ "gmt_create": "desc" }
]
}
Characteristics:
- Direct business parameters, no wrapping needed
- Flat parameter structure, clean and clear
OpenAPI Request Body
// getList request
POST /openapi/data/get-list
Content-Type: application/json
X-Time-Stamp: 1758903130713
X-App-Code: app-c2dd52a2
X-Dataset-Code: 0fefba76fe29440194841f4825df53ff
X-Token: jdqqGtzecF2I6FIW...
{
"appCode": "app-c2dd52a2",
"datasetCode": "0fefba76fe29440194841f4825df53ff",
"paramMap": {
"currentPage": 1,
"pageSize": 20,
"status": "active",
"ytSortList": [
{ "gmt_create": "desc" }
]
}
}
Characteristics:
- Must be wrapped in
{ appCode, datasetCode, paramMap }structure - Business parameters placed in
paramMap - Authentication information passed in both headers and body
When using the SDK, you don't need to worry about underlying differences. The SDK automatically chooses WebAPI or OpenAPI mode based on configuration, with identical calling patterns:
const users = await client.models.users.filter({
currentPage: 1,
pageSize: 20,
});
Use Case Selection Guide
Scenario 1: Developing Custom Pages on Lovrabet (Micro-frontend Integration)
Business Scenario:
You've built a business system on the Lovrabet platform (such as CRM, ERP, project management, etc.), the basic functionality meets your needs, but you want to develop some custom pages for specific business scenarios and integrate them seamlessly into the Lovrabet main application.
Typical Requirements:
- In Lovrabet's order management system, develop a "Sales Funnel Analysis" visualization dashboard
- Add a "Gantt Chart Timeline" interactive page to Lovrabet's project management system
- Develop a "Data Import Wizard" page to simplify bulk import processes
- Custom "Dashboard" page displaying enterprise-specific KPI metrics
Recommended Solution: ✅ WebAPI (Cookie Mode) + icestark Micro-frontend
Method 1: Quick Creation with Lovrabet CLI (Recommended)
Using Lovrabet CLI, you can create a micro-frontend sub-application with one command, automatically configuring icestark, SDK, and WebAPI authentication:
# Install CLI
npm install -g @lovrabet/cli
# Create project
lovrabet create my-custom-page
# Configure and pull SDK
lovrabet config set app <your-app-code>
lovrabet api pull
For complete creation and development workflow, please refer to Lovrabet CLI Quick Start
After creation, use the SDK in your project:
// Import from CLI auto-generated API files
import { lovrabetClient } from "@/api/client";
export default function Dashboard() {
const [orders, setOrders] = useState([]);
useEffect(() => {
// Automatically inherits Lovrabet main application session
lovrabetClient.models.orders
.filter(
{ status: "in_progress" },
[{ gmt_create: "desc" }] // Use sortList parameter for sorting
)
.then((res) => setOrders(res.tableData));
}, []);
return <SalesFunnelChart data={orders} />;
}
Method 2: Manual icestark Integration (Advanced)
If you need more flexible configuration, you can manually integrate icestark.
We provide a complete icestark sub-application example project with full configuration and best practices:
Core Code Example:
// Sub-application entry - src/index.tsx
import ReactDOM from "react-dom";
import { isInIcestark, setLibraryName } from "@ice/stark-app";
import { createClient } from "@lovrabet/sdk";
import App from "./App";
// Initialize SDK (automatically inherits Lovrabet session)
const client = createClient({
appCode: "your-app-code",
models: {
orders: { tableName: "orders", datasetCode: "ds-001" },
},
});
// icestark mount lifecycle
export function mount(props) {
ReactDOM.render(<App sdkClient={client} {...props} />, props.container);
}
// icestark unmount lifecycle
export function unmount(props) {
ReactDOM.unmountComponentAtNode(props.container);
}
// Set library name (must match webpack output.library configuration)
setLibraryName("lovrabetSubApp");
// Standalone running support (development debugging)
if (!isInIcestark()) {
ReactDOM.render(
<App sdkClient={client} />,
document.getElementById("ice-container")
);
}
Lovrabet Main Application Configuration:
After sub-application development is complete, you need to add page configuration in the Lovrabet platform to integrate the sub-application into the main application.
Configuration Steps:
-
Add Source Code Page in Lovrabet Platform
Log in to the Lovrabet platform, select "Add Page" → "Source Code Type Page" in the application, and configure the following:
-
Configure Routing Information
Configuration Options:
| Option | Description | Example |
|---|---|---|
| Route Path | Sub-application access path in main application | /sales-funnel |
| Micro-app Unique ID | icestark's appName, must match sub-application's setLibraryName() | salesFunnelApp |
| basename | Sub-application routing base path (optional) | Leave empty or fill route prefix |
| Resource Loading Method | Select import (for es module) | ES Module recommended |
| Resource Loading List | JS and CSS file URLs of sub-application build artifacts | https://your-domain.com/dist/main.jshttps://your-domain.com/dist/main.css |
Example Configuration:
Route Path: /sales-funnel
Micro-app Unique ID: salesFunnelApp
Resource Loading Method: import (for es module)
Resource Loading List:
https://your-domain.com/dist/sales-funnel/main.js
https://your-domain.com/dist/sales-funnel/main.css
Key Advantages:
- ✅ Seamless Integration - Sub-application automatically inherits Lovrabet main application session and permissions
- ✅ Zero Authentication Configuration - Using WebAPI Cookie mode, no AccessKey management needed
- ✅ CLI Tool Support - One-click creation, automatic configuration, rapid development
- ✅ Independent Development Debugging - Based on icestark, sub-applications can run standalone
Related Documentation:
Scenario 2: Developing Third-party Mini Programs or Standalone Applications
Business Scenario:
Based on business APIs generated by Lovrabet, develop an independent third-party application (such as WeChat Mini Program, Enterprise WeChat app, DingTalk Mini Program, etc.) with its own user system and permission control.
Typical Requirements:
- Develop a "Customer Query" WeChat Mini Program for sales personnel to use while traveling
- Develop Enterprise WeChat application for employees to approve work orders on mobile
- Develop DingTalk Mini Program to display real-time inventory data
- Develop standalone mobile app for partners to use
Recommended Solution: ✅ OpenAPI (Token Mode)
// Mini Program side - pages/index/index.js
import { createClient } from "@lovrabet/sdk";
Page({
async onLoad() {
// Step 1: Get Token from backend (backend uses AccessKey to generate)
const { token, timestamp } = await wx.request({
url: "https://your-backend.com/api/get-lovrabet-token",
method: "POST",
data: { userId: this.getUserId() }, // Pass Mini Program user ID
});
// Step 2: Create client using Token
const client = createClient({
appCode: "your-app-code",
token: token,
timestamp: timestamp,
models: {
customers: { tableName: "customers", datasetCode: "ds-001" },
},
});
// Step 3: Query customer data
const customers = await client.models.customers.filter({
salesperson: this.getUserName(), // Filter by salesperson
pageSize: 20,
});
this.setData({ customers });
},
});
Backend Token Generation Endpoint:
// Backend API - /api/get-lovrabet-token
import { generateOpenApiToken } from "@lovrabet/sdk";
export async function POST(request) {
const { userId } = await request.json();
// 1. Validate Mini Program user identity
const user = await validateWechatUser(userId);
if (!user) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
// 2. Generate Lovrabet OpenAPI Token
const { token, timestamp, expiresAt } = await generateOpenApiToken({
appCode: process.env.LOVRABET_APP_CODE,
datasetCode: process.env.LOVRABET_DATASET_CODE,
accessKey: process.env.LOVRABET_ACCESS_KEY,
});
// 3. Return to Mini Program
return Response.json({ token, timestamp, expiresAt });
}
Key Advantages:
- ✅ Independent User System - Mini Program users completely separate from Lovrabet users
- ✅ Autonomous Permission Control - Backend can dynamically generate Tokens with different permissions based on Mini Program user roles
- ✅ Cross-platform Support - Same API can be used for WeChat, Enterprise WeChat, DingTalk, standalone apps
- ✅ Secure and Controllable - Token valid for 10 minutes, backend can implement finer-grained permission control
Applicable Platforms: WeChat Mini Program, Enterprise WeChat, DingTalk, uniapp, React Native, Flutter, etc.
Scenario 3: Server-side Data Integration (BI/Data Warehouse)
Business Scenario:
Periodically sync business data from Lovrabet systems to enterprise data warehouses, BI systems, or big data platforms for in-depth analysis and report generation.
Typical Requirements:
- Sync Lovrabet order data to data warehouse every night
- Real-time sync customer information to enterprise CRM system
- Periodically export data to Excel for management review
- Connect with enterprise data platform for unified data governance
Recommended Solution: ✅ OpenAPI (AccessKey Mode)
// cron-job.js - Scheduled task script
import { createClient } from "@lovrabet/sdk";
import { syncToDataWarehouse } from "./utils";
const client = createClient({
appCode: process.env.LOVRABET_APP_CODE,
accessKey: process.env.LOVRABET_ACCESS_KEY,
models: {
orders: { tableName: "orders", datasetCode: "ds-001" },
customers: { tableName: "customers", datasetCode: "ds-002" },
},
});
// Execute daily at 2 AM
async function syncDailyData() {
console.log("Starting data sync...");
// Batch get yesterday's orders
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
let currentPage = 1;
let totalSynced = 0;
while (true) {
const { tableData, paging } = await client.models.orders.filter({
currentPage,
pageSize: 100,
create_date: yesterday.toISOString().split("T")[0],
});
// Sync to data warehouse
await syncToDataWarehouse(tableData);
totalSynced += tableData.length;
if (currentPage * paging.pageSize >= paging.totalCount) break;
currentPage++;
}
console.log(`Sync complete, total ${totalSynced} records`);
}
Key Advantages:
- ✅ Server-side Execution - Can safely use AccessKey with no leak risk
- ✅ Batch Processing - Supports efficient sync of large data volumes
- ✅ Stable and Reliable - Not dependent on user login, suitable for automated tasks
- ✅ Flexible Scheduling - Can be scheduled, real-time, or event-triggered as needed
Scenario 4: Third-party System Integration (ERP/OA/Finance Systems)
Business Scenario:
Enterprise already has ERP, OA, finance systems, etc., and needs data interoperability with Lovrabet systems to streamline business processes.
Typical Requirements:
- ERP system needs to read customer and order data from Lovrabet
- Finance system needs to get payment records from Lovrabet
- OA approval workflow needs to call Lovrabet data for validation
- E-commerce system needs to sync inventory information from Lovrabet
Recommended Solution: ✅ OpenAPI (AccessKey Mode)
# Python ERP system integration example
import requests
import hmac
import hashlib
import time
class LovrabetClient:
def __init__(self, app_code, access_key):
self.app_code = app_code
self.access_key = access_key
self.base_url = "https://runtime.lovrabet.com"
def generate_token(self, dataset_code):
timestamp = int(time.time() * 1000)
params = f"accessKey={self.access_key}&appCode={self.app_code}&datasetCode={dataset_code}&timeStamp={timestamp}"
token = hmac.new(
b"lovrabet",
params.encode('utf-8'),
hashlib.sha256
).hexdigest()
return token, timestamp
def get_orders(self, dataset_code):
token, timestamp = self.generate_token(dataset_code)
response = requests.post(
f"{self.base_url}/openapi/data/get-list",
headers={
"X-Time-Stamp": str(timestamp),
"X-App-Code": self.app_code,
"X-Dataset-Code": dataset_code,
"X-Token": token,
"Content-Type": "application/json"
},
json={
"appCode": self.app_code,
"datasetCode": dataset_code,
"paramMap": {
"currentPage": 1,
"pageSize": 50,
"status": "confirmed"
}
}
)
return response.json()
# Use in ERP system
client = LovrabetClient(
app_code="your-app-code",
access_key="your-access-key"
)
orders = client.get_orders("ds-001")
# Sync order data to ERP system
erp_system.sync_orders(orders['data']['tableData'])
Key Advantages:
- ✅ Cross-language Support - Python, Java, Go, PHP, or any backend language
- ✅ Standard Protocol - Based on HTTP + HMAC signature, industry-standard
- ✅ Independent Authentication - Not dependent on Lovrabet user login
- ✅ Enterprise-grade Stability - Suitable for critical business system integration
Scenario 5: SSR Applications (Next.js/Nuxt.js)
Business Scenario:
Build a server-side rendered (SSR) web application based on Lovrabet data that needs to access data on both server and browser sides.
Recommended Solution: ✅ Hybrid Mode (Server uses AccessKey, Browser uses Cookie or Token)
// app/dashboard/page.tsx - Next.js Server Component
import { createClient } from "@lovrabet/sdk";
async function getDashboardData() {
"use server";
// Server-side uses AccessKey
const client = createClient({
appCode: process.env.LOVRABET_APP_CODE,
accessKey: process.env.LOVRABET_ACCESS_KEY,
models: {
stats: { tableName: "stats", datasetCode: "ds-001" },
},
});
return await client.models.stats.filter();
}
export default async function DashboardPage() {
const stats = await getDashboardData();
// Server-side rendered, data already in HTML
return <DashboardView initialData={stats} />;
}
// app/profile/page.tsx - Client Component
("use client");
import { createClient } from "@lovrabet/sdk";
export default function ProfilePage() {
const [data, setData] = useState(null);
useEffect(() => {
// Browser uses Cookie (if user is logged into Lovrabet)
const client = createClient({
appCode: "your-app-code",
models: {
users: { tableName: "users", datasetCode: "ds-001" },
},
});
client.models.users.getOne(userId).then(setData);
}, []);
return <ProfileView data={data} />;
}
Key Advantages:
- ✅ SEO Friendly - Server-side rendering, searchable by search engines
- ✅ First Screen Performance - Data fetched on server, faster loading
- ✅ Flexible Switching - Choose server-side or client-side data fetching based on scenario
Security Comparison
WebAPI Security Mechanisms
Advantages:
- ✅ Relies on Lovrabet platform's user authentication system, mature and reliable
- ✅ Automatically inherits user permissions, no unauthorized access
- ✅ No key management on frontend, avoiding leak risks
Limitations:
- ⚠️ Must be under trusted domain or with correct CORS configuration
- ⚠️ Using Cookie authentication, application layer needs to implement CSRF protection (such as CSRF Token, SameSite Cookie, etc.)
- ⚠️ Browser environment only, cannot be used on server-side
Best Practices:
// ✅ Correct: Use in browser
const client = createClient({
appCode: "your-app-code",
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// ❌ Wrong: Cannot use in Node.js
// Because there's no browser Cookie
WebAPI uses Cookie authentication, CSRF protection is your application's responsibility, not the API layer's responsibility. Recommendations:
- Use CSRF Token: Add CSRF Token validation in forms
- SameSite Cookie: Set Cookie's
SameSiteattribute - Validate Referer/Origin: Validate request origin on backend
- Use Framework CSRF Middleware: Such as Express's
csurf, Next.js's built-in protection, etc.
OpenAPI mode is not affected by CSRF because it uses Token-based authentication, not dependent on browser auto-included Cookies.
OpenAPI Security Mechanisms
Advantages:
- ✅ HMAC-SHA256 signature, industry standard, secure and reliable
- ✅ Token expiration control (10 minutes), reducing leak risk
- ✅ Independent authentication, not dependent on user login state
- ✅ Supports application-level fine-grained permission control
Limitations:
- ⚠️ Serious consequences if AccessKey is leaked
- ⚠️ Requires secure storage and transmission of keys
- ⚠️ Token has expiration, needs refresh handling
Best Practices:
// ✅ Correct: Server-side uses AccessKey
// server.js (Node.js)
const client = createClient({
appCode: process.env.APP_CODE,
accessKey: process.env.LOVRABET_ACCESS_KEY, // Read from environment variable
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// ✅ Correct: Browser uses pre-generated Token
// client.js (Browser)
const { token, timestamp } = await fetch("/api/token").then((r) => r.json());
const client = createClient({
appCode: "your-app-code",
token: token,
timestamp: timestamp,
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// ❌ Wrong: Hardcoding AccessKey in browser code
const client = createClient({
accessKey: "sk_live_xxxx", // Dangerous! Will be exposed in source code
});
Key Management Recommendations:
# .env file (don't commit to Git)
LOVRABET_APP_CODE=app-c2dd52a2
LOVRABET_ACCESS_KEY=your-secret-access-key
LOVRABET_DATASET_CODE=0fefba76fe29440194841f4825df53ff
# .gitignore
.env
.env.local
Token Management and Refresh
Token Validity Period
OpenAPI Token is valid for 10 minutes, must be regenerated after expiration.
Detecting Token Expiration
import { isTokenExpiring, getTokenRemainingTime } from "@lovrabet/sdk";
// Check if about to expire (remaining time < 1 minute)
if (isTokenExpiring(timestamp)) {
console.log("Token about to expire, needs refresh");
}
// Get remaining time (milliseconds)
const remaining = getTokenRemainingTime(timestamp);
console.log(`Token remaining ${remaining / 1000} seconds`);
Auto-refresh Strategies
Strategy 1: Timed Refresh
let tokenData = await fetchToken();
let client = createClient({
appCode: "your-app-code",
token: tokenData.token,
timestamp: tokenData.timestamp,
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// Refresh every 8 minutes (leaving 2 minutes buffer)
setInterval(async () => {
tokenData = await fetchToken();
client.setToken(tokenData.token, tokenData.timestamp);
}, 8 * 60 * 1000);
Strategy 2: Lazy Refresh (Check Before Request)
import { isTokenExpiring } from "@lovrabet/sdk";
async function fetchData() {
// Check if Token is about to expire before request
if (isTokenExpiring(tokenData.timestamp)) {
tokenData = await fetchToken();
client.setToken(tokenData.token, tokenData.timestamp);
}
return await client.models.users.filter();
}
Strategy 3: Error Retry (Recommended)
async function fetchDataWithRetry() {
try {
return await client.models.users.filter();
} catch (error) {
// If Token expired error (1003), refresh and retry
if (error.statusCode === 1003) {
tokenData = await fetchToken();
client.setToken(tokenData.token, tokenData.timestamp);
return await client.models.users.filter(); // Retry
}
throw error;
}
}
Performance Comparison
| Aspect | WebAPI | OpenAPI |
|---|---|---|
| Request Latency | Low (direct call) | Low (direct call) |
| Signature Calculation | None | HMAC-SHA256 (~1ms) |
| Token Refresh | No refresh needed | Refresh every 10 minutes |
| Concurrent Performance | High | High |
| Server-side Calls | Not supported | Supported |
Performance Recommendations:
- WebAPI - Suitable for high-frequency user interactions, no signature overhead
- OpenAPI - Signature calculation overhead negligible (<1ms), suitable for large batch data sync
Migration Guide
Migrating from WebAPI to OpenAPI
Scenario: Need to call API from server-side
// Before: WebAPI (browser only)
const client = createClient({
appCode: "your-app-code",
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// After: OpenAPI (server-side available)
const client = createClient({
appCode: "your-app-code",
accessKey: process.env.LOVRABET_ACCESS_KEY, // Add AccessKey
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// Calling pattern remains the same, SDK auto-adapts
const users = await client.models.users.filter();
Migrating from OpenAPI to WebAPI
Scenario: Browser-side application for logged-in users, want to simplify authentication
// Before: OpenAPI (needs Token management)
const { token, timestamp } = await fetch("/api/token").then((r) => r.json());
const client = createClient({
appCode: "your-app-code",
token: token,
timestamp: timestamp,
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// After: WebAPI (automatically uses Cookie)
const client = createClient({
appCode: "your-app-code",
// Without accessKey or token, automatically uses Cookie
models: { users: { tableName: "users", datasetCode: "ds-001" } },
});
// Calling pattern remains the same
const users = await client.models.users.filter();
FAQ
Q1: How to determine which mode is currently being used?
const client = createClient({
/* ... */
});
// Check if using OpenAPI mode
if (client.isOpenApiMode()) {
console.log("Currently using OpenAPI (Token/AccessKey)");
} else {
console.log("Currently using WebAPI (Cookie)");
}
Q2: Can both modes be used in the same application?
Yes! Automatically select based on runtime environment:
// lib/sdk-client.ts
import { createClient } from "@lovrabet/sdk";
export function getClient() {
// Server-side: Use OpenAPI AccessKey
if (typeof window === "undefined") {
return createClient({
appCode: process.env.APP_CODE,
accessKey: process.env.LOVRABET_ACCESS_KEY,
models: {
/* ... */
},
});
}
// Browser-side: Use WebAPI Cookie
return createClient({
appCode: process.env.NEXT_PUBLIC_APP_CODE,
models: {
/* ... */
},
});
}
Q3: Does WebAPI support CORS?
Yes, but configuration is required:
// Need to configure allowed domains in Lovrabet platform
// Or deploy frontend under the same domain as Lovrabet
Q4: Can the OpenAPI signature algorithm be customized?
No. The signature algorithm is fixed as HMAC-SHA256, with secretKey fixed as "lovrabet", this is to ensure security and compatibility.
Q5: What happens if Token expires?
try {
const users = await client.models.users.filter();
} catch (error) {
if (error.statusCode === 1003) {
console.error("Token expired, please refresh Token");
// Refresh logic
}
}
Quick Selection Guide
| Business Scenario | Recommended Solution | Core Reason |
|---|---|---|
| Lovrabet Micro-frontend Custom Pages | WebAPI (Cookie) | Seamlessly inherit main app session, zero configuration |
| Third-party Mini Programs/Standalone Apps | OpenAPI (Token) | Independent user system, autonomous permission control |
| Data Sync to BI/Data Warehouse | OpenAPI (AccessKey) | Server-side batch processing, stable and reliable |
| ERP/OA/Finance System Integration | OpenAPI (AccessKey) | Cross-language support, enterprise-grade stability |
| Next.js SSR Applications | Hybrid Mode | Server uses AccessKey, Browser uses Cookie |
Core Principles:
- 🎯 Developing within Lovrabet → Use WebAPI, enjoy integrated experience
- 🚀 Standalone Application Development → Use OpenAPI, autonomous and controllable
- 🔄 System Integration → Use OpenAPI (AccessKey), standard protocol
- 🎨 Need Flexibility → Both modes can be used together
- Micro-frontend Integration? Scroll up to see "Scenario 1: Developing Custom Pages on Lovrabet"
- Mini Program Development? Scroll up to see "Scenario 2: Developing Third-party Mini Programs or Standalone Applications"
- Data Integration? Scroll up to see "Scenario 3" and "Scenario 4"
Related Documentation
- Quick Start - Complete examples for all three authentication modes
- Authentication Guide - In-depth understanding of authentication mechanisms
- API Reference - Complete API documentation
Need Help?
If you encounter issues:
- Check GitHub Issues
- Contact your business manager for technical support