SDK Guide
Learn how to integrate and use AllBeAPI SDKs in your JavaScript and Python projects. Our SDKs provide a simple, consistent interface to access all available libraries.
Overview
AllBeAPI provides SDKs for JavaScript and Python that make it easy to integrate our universal library interface into your applications. Both SDKs offer the same functionality with language-specific optimizations and idioms.
🟨 JavaScript SDK
- Promise-based async/await support
- Browser and Node.js compatible
- TypeScript definitions included
- Automatic request/response handling
- Built-in error handling
🐍 Python SDK
- Pythonic API design
- Type hints for better IDE support
- Automatic retry mechanism
- Session management
- Comprehensive error handling
Installation
JavaScript SDK
Basic Usage
// Import the SDK (ES6 modules)
import { AllBeApi } from 'allbeapi';
// Or use CommonJS
const { AllBeApi } = require('allbeapi');
// Or use the global variable (browser)
// const api = new AllBeApi();
// Initialize the client
const api = new AllBeApi({
baseUrl: 'https://res.allbeapi.top', // Optional: custom endpoint
timeout: 10000, // Optional: request timeout in ms
apiKey: 'your-api-key' // Optional: if you have one
});
// Use async/await
async function example() {
try {
// Convert Markdown to HTML
const html = await api.marked.render('# Hello World');
console.log(html);
// Generate QR Code
const qrBlob = await api.pythonQrcode.generateQrcode('https://allbeapi.com');
console.log('QR Code generated:', qrBlob);
} catch (error) {
console.error('Error:', error);
}
}
Available Methods
Text Processing
// Markdown to HTML
await api.marked.render(markdown);
// HTML parsing and extraction
await api.beautifulsoup.parse(html, selector);
// HTML sanitization
await api.sanitizeHtml.clean(html, options);
Code Tools
// Code formatting
await api.prettier.format(code, { parser: 'babel' });
// Code linting
await api.eslint.analyze(code, config);
// Syntax highlighting
await api.pygments.highlight(code, language);
Data Processing
// JSON schema validation
await api.ajv.validate(schema, data);
// CSV to JSON conversion
await api.csvParser.parse(csvData);
// Text comparison
await api.diff.compare(text1, text2);
Media Generation
// QR code generation
await api.pythonQrcode.generateQrcode(data);
// Diagram creation
await api.mermaidCli.render(diagram);
// PDF generation
await api.pdfkit.create(content);
// Image processing
await api.pillow.resize(image, width, height);
Browser Example
<!DOCTYPE html>
<html>
<head>
<title>AllBeAPI Example</title>
<script src="https://cdn.allbeapi.com/js/allbeapi.min.js"></script>
</head>
<body>
<textarea id="markdown-input" placeholder="Enter markdown..."></textarea>
<button onclick="convertMarkdown()">Convert</button>
<div id="html-output"></div>
<script>
const api = new AllBeApi();
async function convertMarkdown() {
const input = document.getElementById('markdown-input').value;
const output = document.getElementById('html-output');
try {
const html = await api.marked.render(input);
output.innerHTML = html;
} catch (error) {
output.innerHTML = '<p style="color: red;">Error: ' + error.message + '</p>';
}
}
</script>
</body>
</html>
Python SDK
Basic Usage
# Import the SDK
from allbeapi import AllBeApi
# Initialize the client
api = AllBeApi(
base_url='https://res.allbeapi.top', # Optional: custom endpoint
timeout=10, # Optional: request timeout in seconds
api_key='your-api-key' # Optional: if you have one
)
# Basic usage examples
def main():
try:
# Convert Markdown to HTML
html = api.marked.render('# Hello World')
print(f"HTML: {html}")
# Generate QR Code
qr_bytes = api.python_qrcode.generate_qrcode('https://allbeapi.com')
with open('qr.png', 'wb') as f:
f.write(qr_bytes)
print("QR code saved to qr.png")
# Format Python code
formatted = api.prettier.format('x=1;y=2', parser='python')
print(f"Formatted: {formatted}")
except Exception as error:
print(f"Error: {error}")
if __name__ == "__main__":
main()
Available Methods
Text Processing
# Markdown to HTML
html = api.marked.render(markdown)
# HTML parsing
data = api.beautifulsoup.parse(html, selector)
# HTML sanitization
clean = api.sanitize_html.clean(html, options)
Code Tools
# Code formatting
formatted = api.prettier.format(code, parser='python')
# Syntax highlighting
highlighted = api.pygments.highlight(code, 'python')
# Code analysis (if available)
analysis = api.eslint.analyze(js_code)
Data Processing
# JSON validation
is_valid = api.ajv.validate(schema, data)
# CSV processing
json_data = api.csv_parser.parse(csv_string)
# Text comparison
diff = api.diff.compare(text1, text2)
Media Generation
# QR code generation
qr_bytes = api.python_qrcode.generate_qrcode(url)
# Image processing
resized = api.pillow.resize_image(image_bytes, 300, 200)
# PDF generation
pdf_bytes = api.pdfkit.create_pdf(content)
Complete Example
#!/usr/bin/env python3
"""
AllBeAPI Python SDK Example
This example demonstrates various features of the AllBeAPI Python SDK.
"""
import os
import json
from allbeapi import AllBeApi
def main():
# Initialize API client
api = AllBeApi()
# Example 1: Blog post processing
print("=== Blog Post Processing ===")
markdown_content = """
# My Tech Blog Post
This post covers **important** topics in web development.
## Code Example
```python
def hello_world():
print("Hello, AllBeAPI!")
```
Visit our [website](https://allbeapi.com) for more info.
"""
try:
# Convert markdown to HTML
html = api.marked.render(markdown_content)
print(f"Generated HTML (first 100 chars): {html[:100]}...")
# Create a QR code for sharing
qr_bytes = api.python_qrcode.generate_qrcode("https://myblog.com/post/1")
# Save QR code
with open("blog_share.png", "wb") as f:
f.write(qr_bytes)
print("✅ QR code saved as blog_share.png")
except Exception as e:
print(f"❌ Error in blog processing: {e}")
# Example 2: Data validation
print("\n=== Data Validation ===")
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "age"]
}
valid_data = {"name": "John Doe", "age": 30, "email": "[email protected]"}
invalid_data = {"name": "Jane", "age": -5}
try:
# Validate data
result1 = api.ajv.validate(schema, valid_data)
result2 = api.ajv.validate(schema, invalid_data)
print(f"Valid data validation: {result1}")
print(f"Invalid data validation: {result2}")
except Exception as e:
print(f"❌ Error in validation: {e}")
# Example 3: Code formatting
print("\n=== Code Formatting ===")
messy_code = "def func(x,y):return x+y;print('hello')"
try:
formatted = api.prettier.format(messy_code, parser='python')
print(f"Original: {messy_code}")
print(f"Formatted: {formatted}")
except Exception as e:
print(f"❌ Error in formatting: {e}")
if __name__ == "__main__":
main()
Configuration
JavaScript Configuration
const api = new AllBeApi({
// Base URL for the API (default: https://res.allbeapi.top)
baseUrl: 'https://your-custom-endpoint.com',
// Request timeout in milliseconds (default: 10000)
timeout: 15000,
// API key if required
apiKey: process.env.ALLBEAPI_KEY,
// Custom headers
headers: {
'User-Agent': 'MyApp/1.0.0',
'X-Custom-Header': 'value'
},
// Retry configuration
retry: {
attempts: 3,
delay: 1000
}
});
Python Configuration
import os
from allbeapi import AllBeApi
api = AllBeApi(
# Base URL for the API
base_url='https://your-custom-endpoint.com',
# Request timeout in seconds
timeout=15,
# API key if required
api_key=os.getenv('ALLBEAPI_KEY'),
# Custom headers
headers={
'User-Agent': 'MyApp/1.0.0',
'X-Custom-Header': 'value'
},
# Session configuration
session_config={
'verify_ssl': True,
'max_retries': 3
}
)
Error Handling
JavaScript Error Handling
try {
const result = await api.marked.render(markdown);
console.log('Success:', result);
} catch (error) {
// Handle different types of errors
if (error.response) {
// Server responded with error status
console.error('Server Error:', error.response.status, error.response.data);
} else if (error.request) {
// Request was made but no response received
console.error('Network Error:', error.message);
} else {
// Something else happened
console.error('Error:', error.message);
}
}
Python Error Handling
from allbeapi import AllBeApi, AllBeApiError, NetworkError, ValidationError
api = AllBeApi()
try:
result = api.marked.render(markdown)
print(f'Success: {result}')
except ValidationError as e:
print(f'Validation Error: {e}')
except NetworkError as e:
print(f'Network Error: {e}')
except AllBeApiError as e:
print(f'API Error: {e}')
except Exception as e:
print(f'Unexpected Error: {e}')
Best Practices
🔐 Security
- Never expose API keys in client-side code
- Use environment variables for configuration
- Validate and sanitize all user inputs
- Use HTTPS endpoints only
⚡ Performance
- Reuse API client instances
- Implement proper caching strategies
- Use appropriate timeout values
- Handle rate limiting gracefully
🛠️ Error Handling
- Always wrap API calls in try-catch blocks
- Implement retry logic for transient failures
- Log errors appropriately
- Provide meaningful error messages to users
📊 Monitoring
- Monitor API response times
- Track error rates and types
- Set up alerts for critical failures
- Use structured logging
Real-World Examples
Blog Content Management System
// Blog post processor using AllBeAPI
class BlogProcessor {
constructor() {
this.api = new AllBeApi();
}
async processPost(markdownContent, metadata) {
try {
// Convert markdown to HTML
const html = await this.api.marked.render(markdownContent);
// Generate social sharing QR code
const shareUrl = `https://myblog.com/post/${metadata.slug}`;
const qrBlob = await this.api.pythonQrcode.generateQrcode(shareUrl);
// Create PDF version
const pdfBuffer = await this.api.pdfkit.create({
content: html,
title: metadata.title,
author: metadata.author
});
return {
html,
qrCode: qrBlob,
pdf: pdfBuffer,
shareUrl
};
} catch (error) {
throw new Error(`Failed to process blog post: ${error.message}`);
}
}
}
Automated Documentation Generator
import os
from pathlib import Path
from allbeapi import AllBeApi
class DocumentationGenerator:
def __init__(self):
self.api = AllBeApi()
def generate_docs(self, source_dir, output_dir):
"""Generate documentation from markdown files."""
source_path = Path(source_dir)
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
for md_file in source_path.glob('**/*.md'):
try:
# Read markdown content
content = md_file.read_text(encoding='utf-8')
# Convert to HTML
html = self.api.marked.render(content)
# Create styled HTML document
full_html = self._create_html_document(html, md_file.stem)
# Write output
output_file = output_path / f"{md_file.stem}.html"
output_file.write_text(full_html, encoding='utf-8')
print(f"✅ Generated: {output_file}")
except Exception as e:
print(f"❌ Error processing {md_file}: {e}")
def _create_html_document(self, content, title):
return f"""
{title}
{content}
"""
Universal Data Validator
class DataValidator {
constructor() {
this.api = new AllBeApi();
}
async validateUserData(userData, schema) {
const validationResult = {
isValid: false,
errors: [],
sanitizedData: null
};
try {
// Validate against JSON schema
const schemaValidation = await this.api.ajv.validate(schema, userData);
if (!schemaValidation.valid) {
validationResult.errors.push(...schemaValidation.errors);
return validationResult;
}
// Sanitize HTML content if present
if (userData.bio) {
userData.bio = await this.api.sanitizeHtml.clean(userData.bio, {
allowedTags: ['p', 'br', 'strong', 'em'],
allowedAttributes: {}
});
}
validationResult.isValid = true;
validationResult.sanitizedData = userData;
} catch (error) {
validationResult.errors.push(`Validation failed: ${error.message}`);
}
return validationResult;
}
}