Code Examples
Practical code examples for integrating with the Cherry.tv Affiliates API
Code Examples
This page provides practical examples of how to integrate with the Cherry.tv Affiliates API using various programming languages.
JavaScript/Node.js
Basic Model Listing
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://api.cherry.tv';
async function getModels(filters = {}) {
const params = new URLSearchParams({
apiKey: API_KEY,
...filters
});
try {
const response = await fetch(`${BASE_URL}/affiliates/v1/models?${params}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const models = await response.json();
return models;
} catch (error) {
console.error('Error fetching models:', error);
throw error;
}
}
// Usage examples
async function examples() {
// Get all online female models
const onlineFemales = await getModels({
gender: 0,
status: 1,
limit: 20
});
// Get models by tag
const blondeModels = await getModels({
tag: 'blonde',
status: 1
});
// Get top models by viewer count
const topModels = await getModels({
status: 1,
order: 'viewer',
sort: 'desc',
limit: 10
});
console.log('Online females:', onlineFemales.length);
console.log('Blonde models:', blondeModels.length);
console.log('Top models:', topModels.length);
}
Get Specific Model Information
async function getModelInfo(modelId) {
const params = new URLSearchParams({
apiKey: API_KEY
});
try {
const response = await fetch(`${BASE_URL}/affiliates/v1/models/${modelId}?${params}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const modelInfo = await response.json();
return modelInfo;
} catch (error) {
console.error('Error fetching model info:', error);
throw error;
}
}
// Usage
async function displayModelInfo(modelId) {
const info = await getModelInfo(modelId);
console.log(`Model: ${info.model.name} (@${info.model.username})`);
console.log(`Status: ${info.room.status === 1 ? 'Online' : 'Offline'}`);
console.log(`Viewers: ${info.room.viewers}`);
console.log(`Affiliate URL: ${info.links.affiliate_url}`);
}
Python
Using requests library
import requests
from typing import Dict, List, Optional
class CherryTVAPI:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.cherry.tv"
def _make_request(self, endpoint: str, params: Dict = None) -> Dict:
"""Make a request to the API with error handling."""
if params is None:
params = {}
params['apiKey'] = self.api_key
try:
response = requests.get(f"{self.base_url}{endpoint}", params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"API request failed: {e}")
raise
def get_models(self, **filters) -> List[Dict]:
"""Get list of models with optional filters."""
return self._make_request("/affiliates/v1/models", filters)
def get_model_info(self, model_id: str) -> Dict:
"""Get detailed information about a specific model."""
return self._make_request(f"/affiliates/v1/models/{model_id}")
# Usage examples
def main():
api = CherryTVAPI("your-api-key-here")
# Get online female models
online_females = api.get_models(
gender=0,
status=1,
limit=20,
order="viewer",
sort="desc"
)
print(f"Found {len(online_females)} online female models")
# Display top 5 models
for i, model_data in enumerate(online_females[:5]):
model = model_data['model']
room = model_data['room']
print(f"{i+1}. {model['name']} (@{model['username']})")
print(f" Viewers: {room['viewers']}")
print(f" Age: {model['age']}")
print(f" Country: {model['country_name']}")
print(f" Affiliate URL: {model_data['links']['affiliate_url']}")
print()
if __name__ == "__main__":
main()
PHP
Basic Implementation
<?php
class CherryTVAPI {
private $apiKey;
private $baseUrl = 'https://api.cherry.tv';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
private function makeRequest($endpoint, $params = []) {
$params['apiKey'] = $this->apiKey;
$url = $this->baseUrl . $endpoint . '?' . http_build_query($params);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json',
'timeout' => 30
]
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception('API request failed');
}
return json_decode($response, true);
}
public function getModels($filters = []) {
return $this->makeRequest('/affiliates/v1/models', $filters);
}
public function getModelInfo($modelId) {
return $this->makeRequest("/affiliates/v1/models/{$modelId}");
}
}
// Usage example
try {
$api = new CherryTVAPI('your-api-key-here');
// Get online models
$onlineModels = $api->getModels([
'status' => 1,
'limit' => 10,
'order' => 'viewer',
'sort' => 'desc'
]);
echo "Top Online Models:\n";
foreach ($onlineModels as $modelData) {
$model = $modelData['model'];
$room = $modelData['room'];
echo "- {$model['name']} (@{$model['username']})\n";
echo " Viewers: {$room['viewers']}\n";
echo " Affiliate URL: {$modelData['links']['affiliate_url']}\n\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
cURL Examples
Get Models List
# Get all online models
curl -X GET "https://api.cherry.tv/affiliates/v1/models?apiKey=YOUR_API_KEY&status=1"
# Get female models with specific tags
curl -X GET "https://api.cherry.tv/affiliates/v1/models?apiKey=YOUR_API_KEY&gender=0&tag=blonde&status=1&limit=20"
# Get top models by viewer count
curl -X GET "https://api.cherry.tv/affiliates/v1/models?apiKey=YOUR_API_KEY&status=1&order=viewer&sort=desc&limit=10"
Get Specific Model
# Get model information by ID
curl -X GET "https://api.cherry.tv/affiliates/v1/models/12345?apiKey=YOUR_API_KEY"
React Component Example
import React, { useState, useEffect } from 'react';
const ModelList = ({ apiKey }) => {
const [models, setModels] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchModels = async () => {
try {
const params = new URLSearchParams({
apiKey: apiKey,
status: 1, // Online only
limit: 20,
order: 'viewer',
sort: 'desc'
});
const response = await fetch(`https://api.cherry.tv/affiliates/v1/models?${params}`);
if (!response.ok) {
throw new Error('Failed to fetch models');
}
const data = await response.json();
setModels(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchModels();
}, [apiKey]);
if (loading) return <div>Loading models...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div className="model-list">
<h2>Top Online Models</h2>
<div className="models-grid">
{models.map((modelData) => (
<div key={modelData.model.id} className="model-card">
<img
src={modelData.model.avatar}
alt={modelData.model.name}
className="model-avatar"
/>
<h3>{modelData.model.name}</h3>
<p>@{modelData.model.username}</p>
<p>Viewers: {modelData.room.viewers}</p>
<p>Age: {modelData.model.age}</p>
<div className="model-tags">
{modelData.model.tags.slice(0, 3).map((tag, index) => (
<span key={index} className="tag">#{tag}</span>
))}
</div>
<a
href={modelData.links.affiliate_url}
target="_blank"
rel="noopener noreferrer"
className="visit-room-btn"
>
Visit Room
</a>
</div>
))}
</div>
</div>
);
};
export default ModelList;
Error Handling Best Practices
Retry Logic Example (JavaScript)
async function apiRequestWithRetry(url, maxRetries = 3, delay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url);
if (response.ok) {
return await response.json();
}
// If it's a client error (4xx), don't retry
if (response.status >= 400 && response.status < 500) {
throw new Error(`Client error: ${response.status}`);
}
// For server errors (5xx), retry
if (attempt === maxRetries) {
throw new Error(`Server error after ${maxRetries} attempts: ${response.status}`);
}
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}
Caching Example
class CherryTVAPIWithCache {
constructor(apiKey, cacheTimeout = 60000) { // 1 minute cache
this.apiKey = apiKey;
this.cache = new Map();
this.cacheTimeout = cacheTimeout;
}
async getModels(filters = {}) {
const cacheKey = JSON.stringify(filters);
const cached = this.cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
return cached.data;
}
const params = new URLSearchParams({
apiKey: this.apiKey,
...filters
});
const response = await fetch(`https://api.cherry.tv/affiliates/v1/models?${params}`);
const data = await response.json();
this.cache.set(cacheKey, {
data,
timestamp: Date.now()
});
return data;
}
}
These examples should help you get started with integrating the Cherry.tv Affiliates API into your applications. Remember to replace 'your-api-key-here'
with your actual API key provided by Cherry.tv.