Code Examples
Complete, production-ready examples for common integrations.
Complete JavaScript Client
A full-featured JavaScript client class for integrating with the API:
api-client.jsjavascript
class APIClient {
constructor(apiKey, baseUrl = 'https://yourdomain.com/api/v1') {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
}
async request(endpoint, options = {}) {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'API request failed');
}
return response.json();
}
// Assets
async listAssets(params = {}) {
const queryString = new URLSearchParams(params).toString();
return this.request(`/assets?${queryString}`);
}
async createAsset(data) {
return this.request('/assets', {
method: 'POST',
body: JSON.stringify(data),
});
}
// Libraries
async createLibrary(data) {
return this.request('/libraries', {
method: 'POST',
body: JSON.stringify(data),
});
}
// Leads
async createLead(data) {
return this.request('/leads', {
method: 'POST',
body: JSON.stringify(data),
});
}
}
// Usage
const api = new APIClient(process.env.API_KEY);
// Fetch PDF assets
const pdfs = await api.listAssets({ asset_type: 'pdf' });
// Create a lead
const lead = await api.createLead({
name: 'John Doe',
email: 'john@example.com',
source: 'website_form'
});Python Client
api_client.pypython
import requests
from typing import Dict, List
import os
class APIClient:
def __init__(self, api_key: str, base_url: str = 'https://yourdomain.com/api/v1'):
self.api_key = api_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
})
def _request(self, method: str, endpoint: str, **kwargs) -> Dict:
url = f'{self.base_url}{endpoint}'
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
return response.json()
def list_assets(self, **params) -> Dict:
return self._request('GET', '/assets', params=params)
def create_asset(self, data: Dict) -> Dict:
return self._request('POST', '/assets', json=data)
def create_library(self, data: Dict) -> Dict:
return self._request('POST', '/libraries', json=data)
def create_lead(self, data: Dict) -> Dict:
return self._request('POST', '/leads', json=data)
# Usage
api = APIClient(os.getenv('API_KEY'))
# Fetch assets
assets = api.list_assets(per_page=50)
# Create a lead
lead = api.create_lead({
'name': 'Jane Smith',
'email': 'jane@example.com',
'source': 'api_integration'
})React Integration
hooks/useAPI.jsjavascript
import { useState, useEffect } from 'react';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;
const API_KEY = process.env.NEXT_PUBLIC_API_KEY;
export function useAssets(filters = {}) {
const [assets, setAssets] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchAssets() {
try {
setLoading(true);
const queryString = new URLSearchParams(filters).toString();
const response = await fetch(`${API_BASE_URL}/assets?${queryString}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
const data = await response.json();
setAssets(data.data || []);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchAssets();
}, [JSON.stringify(filters)]);
return { assets, loading, error };
}
// Usage in component
export default function AssetGallery() {
const { assets, loading, error } = useAssets({ asset_type: 'pdf' });
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div className="grid grid-cols-3 gap-4">
{assets.map(asset => (
<div key={asset.id} className="card">
<h3>{asset.title}</h3>
<p>{asset.description}</p>
</div>
))}
</div>
);
}WordPress Plugin
api-integration.phpphp
<?php
class APIIntegration {
private $api_key;
private $base_url = 'https://yourdomain.com/api/v1';
public function __construct($api_key) {
$this->api_key = $api_key;
}
private function request($endpoint, $method = 'GET', $data = null) {
$url = $this->base_url . $endpoint;
$args = array(
'method' => $method,
'headers' => array(
'Authorization' => 'Bearer ' . $this->api_key,
'Content-Type' => 'application/json'
),
'timeout' => 30
);
if ($data) {
$args['body'] = json_encode($data);
}
$response = wp_remote_request($url, $args);
if (is_wp_error($response)) {
return false;
}
return json_decode(wp_remote_retrieve_body($response), true);
}
public function get_assets($type = null) {
$endpoint = '/assets';
if ($type) {
$endpoint .= '?asset_type=' . urlencode($type);
}
return $this->request($endpoint);
}
public function create_lead($data) {
return $this->request('/leads', 'POST', $data);
}
}
// Usage: Display assets shortcode
function display_api_assets($atts) {
$api = new APIIntegration(get_option('api_key'));
$result = $api->get_assets('pdf');
if (!$result || !isset($result['data'])) {
return 'Failed to load assets';
}
ob_start();
foreach ($result['data'] as $asset) {
echo '<div class="asset-item">';
echo '<h3>' . esc_html($asset['title']) . '</h3>';
echo '<p>' . esc_html($asset['description']) . '</p>';
echo '</div>';
}
return ob_get_clean();
}
add_shortcode('api_assets', 'display_api_assets');
?>Error Handling Best Practices
async function makeAPIRequest(endpoint, options = {}) {
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
...options.headers,
},
});
// Check rate limits
const rateLimitRemaining = response.headers.get('X-RateLimit-Remaining');
if (rateLimitRemaining < 10) {
console.warn('API rate limit running low:', rateLimitRemaining);
}
if (!response.ok) {
if (response.status === 401) {
throw new Error('Invalid API key');
} else if (response.status === 403) {
throw new Error('Insufficient permissions');
} else if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
throw new Error(`Rate limit exceeded. Retry after ${retryAfter}s`);
}
const error = await response.json();
throw new Error(error.message || 'API request failed');
}
return await response.json();
} catch (error) {
console.error('API Error:', error);
throw error;
}
}Next Steps
- • Review Getting Started guide
- • Explore Assets API
- • Check out Dashboard to get your API key