Express.js SDK
The ApiRules JavaScript SDK provides an easy way to integrate ApiRules into your Express.js applications.
Installation
npm install apirules-sdk
Express.js Integration
Here's how to integrate ApiRules with your Express.js application:
const express = require('express');
const { ApiRules } = require('apirules-sdk');
const app = express();
const apiRules = new ApiRules({
apiKey: process.env.APIRULES_API_KEY,
});
// Example route with ApiRules validation with endpoint-id set in dashboard
// The request body will be automatically sent to our backend for LLM validation
// based on the rules configured in the dashboard for this endpoint-id
app.post('/', apiRules.validate('enpoint-id', 'strict'), (req, res) => {
// Default endpoint handler
res.send('Hello World!');
});
Features
Rate Limiting
The SDK includes built-in rate limiting to protect your API:
- 60 requests per minute per IP
- Rate limit headers included in responses (X-RateLimit-*)
- Automatic 429 status code when limit is exceeded
- Rate limit resets after the 1-minute window
// Rate limiting is automatically applied to all routes using the SDK
app.post('/api/users', apiRules.validate('create-user', 'strict'), (req, res) => {
// If rate limit is exceeded, this handler won't be called
// Client will receive 429 status code instead
res.json({ message: 'User created' });
});
Request Body Validation
The SDK automatically sends the request body to our backend for LLM validation:
- Request body is validated against rules configured in the dashboard
- LLM validation happens before the request reaches your route handler
- Validation results are cached for performance
- If validation failed it will throw 403 Error "Request blocked by the rules set in dashboard"
// Example with request body validation
app.post('/api/users', apiRules.validate('create-user'), (req, res) => {
// Request body has already been validated by LLM
// You can safely use the validated data
const { name, email } = req.body;
res.json({ message: 'User created' });
});
Error Handling
The SDK automatically handles errors and returns appropriate status codes:
- 429 for rate limit exceeded
- 403 for access denied
- 400 for LLM validation failures
- 500 for internal server errors
Validation Modes
The SDK supports two validation modes that determine how requests are handled when LLM validation fails:
Strict Mode
app.post('/comment', apiRules.validateExpress('createComment', 'strict'), (req, res) => {
// Request handler code
});
- Blocks requests that fail LLM validation
- Prevents invalid requests from reaching the endpoint handler
- Returns a 403 status code
- Recommended for critical endpoints where data integrity is essential
Advisory Mode
app.post('/post', apiRules.validateExpress('createPost', 'advisory'), (req, res) => {
// Request handler code
});
- Allows requests to proceed to the endpoint handler regardless of LLM validation results
- Provides validation results in the request object for optional handling
- All validation results are logged for monitoring and auditing
- Recommended for non-critical endpoints where you want to monitor validation but not block requests
Usage Guidelines
- Use strict mode for endpoints that require guaranteed data quality and security and you are sure LLM can handle it
- Use advisory mode for endpoints where you want to monitor validation patterns without blocking requests
- Coming soon: You can access validation results in your request handler for custom processing
For any request please reach out to info@apirules.io we will be more than happy to implement all sorts of monitorings and logging options for you!
Direct Validation
You can also use the SDK to make direct validation requests without Express middleware:
// Initialize the SDK
const apiRules = new ApiRules({
apiKey: process.env.APIRULES_API_KEY,
openAiToken: process.env.OPENAI_API_KEY // Optional: Use your own OpenAI token
});
// Make a validation request
const isValid = await apiRules.postRequest(
{ content: 'Hello, world!' }, // Request body to validate
'createComment', // Endpoint ID
'strict' // Validation mode (optional, defaults to 'strict')
);
if (isValid) {
// Proceed with the request
console.log('Content is valid');
} else {
// Handle invalid content
console.log('Content is invalid');
}
The postRequest
method:
- Automatically handles authentication
- Supports custom OpenAI tokens
- Returns a boolean decision
- Throws errors for invalid requests or server issues
- Caches responses for better performance
Error Handling
try {
const isValid = await apiRules.postRequest(
{ content: 'Hello, world!' },
'createComment',
'strict'
);
} catch (error) {
if (error.response) {
// Handle API errors
switch (error.response.status) {
case 400:
console.error('Invalid request:', error.response.data);
break;
case 401:
console.error('Missing API key');
break;
case 403:
console.error('Invalid API key');
break;
case 429:
console.error('Rate limit exceeded');
break;
default:
console.error('Server error:', error.response.data);
}
} else {
console.error('Network error:', error.message);
}
}
For any request please reach out to info@apirules.io we will be more than happy to implement all sorts of monitorings and logging options for you!