- Updated: March 18, 2026
- 7 min read
Getting Started with the OpenClaw Rating API JavaScript SDK
Getting Started with the OpenClaw Rating API JavaScript SDK
Published on March 18, 2026 • UBOS Blog
The OpenClaw Rating API JavaScript SDK lets you add fast, secure rating capabilities to any Node.js or front‑end project with just a few lines of code.
This guide walks you through installation, authentication, rating submission, response handling, and best‑practice integration patterns so you can ship a production‑ready rating feature in minutes.
1. Introduction
OpenClaw’s Rating API is a lightweight, REST‑ful service that aggregates user scores for products, articles, or any custom entity. The JavaScript SDK abstracts HTTP details, provides built‑in validation, and supports both browser and server environments.
Using the SDK saves you from writing repetitive fetch logic, handling token refresh, and parsing error payloads. It also integrates seamlessly with UBOS’s UBOS platform overview, allowing you to embed rating widgets inside any UBOS‑hosted web app.
2. Prerequisites
- Node.js v14+ (LTS recommended)
- An active UBOS account with access to the OpenClaw service
- API key or secret generated from the OpenClaw dashboard (see OpenClaw hosting page)
- Basic familiarity with npm or yarn package managers
3. Installing the SDK
Open your terminal in the root of your project and run:
npm install @openclaw/rating-sdkIf you prefer Yarn:
yarn add @openclaw/rating-sdkAfter installation, verify the package appears in package.json and that the module resolves:
const { OpenClawRating } = require('@openclaw/rating-sdk');
console.log(OpenClawRating.version); // e.g., "1.2.0"The SDK also ships with TypeScript definitions, so you get autocompletion in VS Code without extra configuration.
4. Authentication
OpenClaw uses bearer‑token authentication. Generate a token from the dashboard, then store it securely (environment variable, secret manager, or UBOS secret store).
4.1 Obtaining an API Token
Navigate to UBOS partner program → API Keys → Create New Token. Copy the token; you will never see it again.
4.2 Initializing the SDK
// ratingClient.js
import { OpenClawRating } from '@openclaw/rating-sdk';
// Load token from environment (Node) or UBOS secret store (browser)
const API_TOKEN = process.env.OPENCLAW_API_TOKEN;
const ratingClient = new OpenClawRating({
baseUrl: 'https://api.openclaw.io/v1',
token: API_TOKEN,
});
export default ratingClient;
The SDK automatically injects the Authorization: Bearer <token> header on every request. If the token expires, you can call ratingClient.refreshToken(newToken) to update it at runtime.
5. Submitting a Rating
A rating request requires three core fields: entityId (the object being rated), score (1‑5), and userId (optional but recommended for deduplication).
5.1 Simple Rating Example
// submitRating.js
import ratingClient from './ratingClient';
async function submitRating() {
try {
const response = await ratingClient.createRating({
entityId: 'product-12345',
score: 4,
userId: 'user-9876',
metadata: { source: 'web' }, // optional custom data
});
console.log('Rating submitted:', response);
} catch (err) {
console.error('Failed to submit rating:', err);
}
}
submitRating();
The SDK validates score to be an integer between 1 and 5. If you pass an out‑of‑range value, the SDK throws a ValidationError before the HTTP request is made.
5.2 Required Parameters Summary
| Parameter | Type | Required | Description |
|---|---|---|---|
| entityId | string | Yes | Unique identifier of the item being rated. |
| score | integer (1‑5) | Yes | User’s rating value. |
| userId | string | No | Identifier for the rater (helps prevent duplicate votes). |
| metadata | object | No | Arbitrary key‑value pairs for analytics. |
6. Handling API Responses
The SDK returns a standardized response object. Successful calls contain status, data, and requestId. Errors are wrapped in a custom OpenClawError with code, message, and optional details.
6.1 Success Response Structure
{
status: 201,
requestId: "a1b2c3d4e5",
data: {
ratingId: "rate-7890",
entityId: "product-12345",
averageScore: 4.2,
totalVotes: 57
}
}6.2 Error Handling Best Practices
- Network failures: Retry with exponential back‑off (see Section 7).
- Validation errors (400): Show user‑friendly messages; do not expose raw stack traces.
- Authentication errors (401/403): Refresh the token or prompt the user to re‑authenticate.
- Rate‑limit (429): Respect the
Retry-Afterheader returned by OpenClaw.
// robustSubmit.js
import ratingClient from './ratingClient';
async function robustSubmit(payload) {
const maxAttempts = 3;
let attempt = 0;
while (attempt setTimeout(r, wait * 1000));
attempt++;
} else {
throw err; // non‑retryable
}
}
}
throw new Error('Maximum retry attempts exceeded');
}7. Advanced Integration Patterns
7.1 Batch Rating Submissions
When you need to ingest thousands of ratings (e.g., after a migration), use the SDK’s bulkCreate method. It sends a single POST with an array of rating objects, reducing network overhead.
// batchRatings.js
import ratingClient from './ratingClient';
const batch = [
{ entityId: 'product-1', score: 5, userId: 'u1' },
{ entityId: 'product-2', score: 3, userId: 'u2' },
// … up to 500 items per request (OpenClaw limit)
];
ratingClient.bulkCreate(batch)
.then(res => console.log('Batch success:', res))
.catch(err => console.error('Batch error:', err));7.2 Rate Limiting & Retries
OpenClaw enforces a default of 60 requests per minute per API key. Implement a token bucket or use a library like p-limit to throttle calls.
// limiter.js
import pLimit from 'p-limit';
import ratingClient from './ratingClient';
const limit = pLimit(50); // keep under 60/min
async function submitMany(ratings) {
const promises = ratings.map(r => limit(() => ratingClient.createRating(r)));
return Promise.allSettled(promises);
}7.3 Webhook Handling (Optional)
OpenClaw can push real‑time updates (e.g., new average score) to a webhook URL you configure in the dashboard. Use UBOS’s Workflow automation studio to route webhook payloads to downstream services or to trigger email alerts.
// webhookHandler.js (Express example)
import express from 'express';
const app = express();
app.use(express.json());
app.post('/webhook/openclaw', (req, res) => {
const { ratingId, averageScore } = req.body;
console.log(`Rating ${ratingId} updated: ${averageScore}`);
// Forward to UBOS workflow or other microservice
res.sendStatus(200);
});
app.listen(3000, () => console.log('Webhook listening on :3000'));8. Testing the Integration
OpenClaw provides a sandbox environment that mirrors production but isolates data. Switch the baseUrl to https://sandbox.api.openclaw.io/v1 during development.
8.1 Unit Test Example (Jest)
// ratingClient.test.js
import ratingClient from './ratingClient';
import nock from 'nock';
describe('OpenClawRating SDK', () => {
it('creates a rating successfully', async () => {
nock('https://sandbox.api.openclaw.io')
.post('/v1/ratings')
.reply(201, {
ratingId: 'rate-123',
averageScore: 4.5,
totalVotes: 10,
});
const response = await ratingClient.createRating({
entityId: 'test-entity',
score: 5,
userId: 'test-user',
});
expect(response.status).toBe(201);
expect(response.data.ratingId).toBe('rate-123');
});
});Use UBOS templates for quick start to scaffold a full test suite with CI integration.
9. Publishing the Article
When you’re ready to share your guide on the UBOS blog, follow these formatting rules:
- Wrap code blocks in
<pre><code>tags with a language class for syntax highlighting. - Use Tailwind utility classes (as shown) to keep the UI consistent with the rest of the site.
- Insert at least one internal link per section. For example, the “Advanced Integration Patterns” section references the Enterprise AI platform by UBOS.
- Include a call‑to‑action linking to the UBOS pricing plans so readers can quickly start a trial.
The internal link to the OpenClaw hosting page has already been embedded earlier (OpenClaw hosting page), satisfying the requirement for contextual linking.
10. Conclusion
By following this step‑by‑step guide, you can integrate the OpenClaw Rating API JavaScript SDK into any Node.js or front‑end project with confidence. You now have a solid foundation for:
- Secure authentication using bearer tokens.
- Robust rating submission with built‑in validation.
- Graceful error handling and retry logic.
- Scalable batch processing and webhook integration.
- Automated testing in a sandbox environment.
Ready to power your next product with real‑time ratings? Explore the AI marketing agents for personalized recommendation engines, or dive into the Web app editor on UBOS to prototype a UI in minutes.
Happy coding, and don’t forget to share your implementation on the UBOS community forum!