Overview
This guide provides real-world examples of using the WallWidgy API for common use cases. Each example includes a complete implementation and explanation.Random wallpaper fetcher
Get a random wallpaper from the entire collection:async function getRandomWallpaper() {
const response = await fetch(
'https://wallwidgy.com/api/wallpapers?count=1'
);
const data = await response.json();
return data.wallpapers[0];
}
// Usage
const wallpaper = await getRandomWallpaper();
console.log('Random wallpaper:', wallpaper);
// Set as background
document.body.style.backgroundImage = `url(${wallpaper})`;
Use
count=1 to get a single random wallpaper, or increase the count to get multiple random wallpapers at once.Category-based wallpaper gallery
Build a wallpaper gallery that lets users browse by category:const CATEGORIES = [
'abstract', 'amoled', 'anime', 'architecture',
'art', 'cars', 'minimal', 'nature', 'tech'
];
class WallpaperGallery {
constructor() {
this.currentCategory = 'all';
this.wallpapers = [];
}
async fetchByCategory(category, count = 10) {
const url = category === 'all'
? `https://wallwidgy.com/api/wallpapers?count=${count}`
: `https://wallwidgy.com/api/wallpapers?category=${category}&count=${count}`;
const response = await fetch(url);
const data = await response.json();
this.currentCategory = data.category;
this.wallpapers = data.wallpapers;
return this.wallpapers;
}
async loadMore(count = 10) {
const newWallpapers = await this.fetchByCategory(
this.currentCategory,
count
);
// Filter out duplicates
const unique = newWallpapers.filter(
wp => !this.wallpapers.includes(wp)
);
this.wallpapers.push(...unique);
return unique;
}
}
// Usage
const gallery = new WallpaperGallery();
// Load anime wallpapers
const animeWallpapers = await gallery.fetchByCategory('anime', 20);
console.log(`Loaded ${animeWallpapers.length} anime wallpapers`);
// Load more from the same category
const moreWallpapers = await gallery.loadMore(10);
console.log(`Loaded ${moreWallpapers.length} more wallpapers`);
Device-specific wallpaper app
Automatically detect device type and fetch appropriate wallpapers:class DeviceWallpaperApp {
constructor() {
this.deviceType = this.detectDeviceType();
}
detectDeviceType() {
const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent)
|| window.innerWidth < 768;
return isMobile ? 'mobile' : 'desktop';
}
async fetchWallpapers(options = {}) {
const {
category = null,
color = null,
count = 10
} = options;
const params = new URLSearchParams({
type: this.deviceType,
count: count.toString()
});
if (category) params.append('category', category);
if (color) params.append('color', color);
const response = await fetch(
`https://wallwidgy.com/api/wallpapers?${params}`
);
return await response.json();
}
async getForCurrentDevice(category, count = 5) {
return await this.fetchWallpapers({ category, count });
}
async searchByColor(color, count = 5) {
return await this.fetchWallpapers({ color, count });
}
}
// Usage
const app = new DeviceWallpaperApp();
console.log(`Device type: ${app.deviceType}`);
// Get anime wallpapers for this device
const wallpapers = await app.getForCurrentDevice('anime', 10);
console.log(`Got ${wallpapers.count} ${wallpapers.type} wallpapers`);
// Get blue wallpapers for this device
const blueWallpapers = await app.searchByColor('blue', 5);
Color theme matcher
Match wallpapers to your app’s color theme:import requests
from typing import List, Dict, Optional
class ColorThemeMatcher:
"""Fetch wallpapers that match your app's color theme"""
THEME_COLORS = {
'dark': 'black',
'light': 'white',
'ocean': 'blue',
'forest': 'green',
'sunset': 'orange',
'lavender': 'purple',
'rose': 'pink',
'minimal': 'gray'
}
def __init__(self, base_url: str = 'https://wallwidgy.com/api/wallpapers'):
self.base_url = base_url
def get_wallpapers_for_theme(
self,
theme: str,
device_type: Optional[str] = None,
category: Optional[str] = None,
count: int = 10
) -> List[str]:
"""Get wallpapers matching a color theme"""
color = self.THEME_COLORS.get(theme.lower())
if not color:
available = ', '.join(self.THEME_COLORS.keys())
raise ValueError(
f"Unknown theme '{theme}'. Available: {available}"
)
params = {'color': color, 'count': count}
if device_type:
params['type'] = device_type
if category:
params['category'] = category
response = requests.get(self.base_url, params=params)
response.raise_for_status()
return response.json()['wallpapers']
def get_complementary_wallpapers(
self,
primary_theme: str,
secondary_theme: str,
count_each: int = 5
) -> Dict[str, List[str]]:
"""Get wallpapers for two complementary themes"""
return {
primary_theme: self.get_wallpapers_for_theme(
primary_theme, count=count_each
),
secondary_theme: self.get_wallpapers_for_theme(
secondary_theme, count=count_each
)
}
# Usage
matcher = ColorThemeMatcher()
# Get dark theme wallpapers for mobile
dark_wallpapers = matcher.get_wallpapers_for_theme(
'dark',
device_type='mobile',
category='minimal',
count=10
)
print(f"Got {len(dark_wallpapers)} dark theme wallpapers")
# Get complementary themes
complementary = matcher.get_complementary_wallpapers('ocean', 'sunset', count_each=5)
print(f"Ocean: {len(complementary['ocean'])} wallpapers")
print(f"Sunset: {len(complementary['sunset'])} wallpapers")
Wallpaper rotation service
Automatically rotate wallpapers on a schedule:import requests
import time
import random
from typing import Optional
class WallpaperRotator:
"""Automatically rotate wallpapers based on preferences"""
def __init__(
self,
category: Optional[str] = None,
color: Optional[str] = None,
device_type: Optional[str] = 'desktop'
):
self.category = category
self.color = color
self.device_type = device_type
self.current_wallpaper = None
self.wallpaper_history = []
def fetch_new_wallpaper(self) -> str:
"""Fetch a new random wallpaper based on preferences"""
params = {'type': self.device_type, 'count': 1}
if self.category:
params['category'] = self.category
if self.color:
params['color'] = self.color
response = requests.get(
'https://wallwidgy.com/api/wallpapers',
params=params
)
data = response.json()
wallpaper = data['wallpapers'][0]
# Avoid repeating recent wallpapers
if wallpaper in self.wallpaper_history[-10:]:
return self.fetch_new_wallpaper()
self.current_wallpaper = wallpaper
self.wallpaper_history.append(wallpaper)
return wallpaper
def start_rotation(self, interval_seconds: int = 3600, callback=None):
"""Start rotating wallpapers at specified interval"""
print(f"Starting wallpaper rotation every {interval_seconds}s")
print(f"Category: {self.category or 'all'}")
print(f"Color: {self.color or 'all'}")
print(f"Device type: {self.device_type}")
while True:
try:
wallpaper = self.fetch_new_wallpaper()
print(f"\nNew wallpaper: {wallpaper}")
if callback:
callback(wallpaper)
time.sleep(interval_seconds)
except KeyboardInterrupt:
print("\nStopping wallpaper rotation")
break
except Exception as e:
print(f"Error: {e}")
time.sleep(60) # Wait 1 minute on error
# Usage example 1: Rotate nature wallpapers every hour
def apply_wallpaper(url):
# Download and set wallpaper (OS-specific implementation)
print(f"Applying wallpaper: {url}")
rotator = WallpaperRotator(
category='nature',
color='blue',
device_type='desktop'
)
# Start rotation (every hour)
# rotator.start_rotation(interval_seconds=3600, callback=apply_wallpaper)
# Usage example 2: Just get a new wallpaper on demand
new_wallpaper = rotator.fetch_new_wallpaper()
print(f"New wallpaper: {new_wallpaper}")
Multi-monitor wallpaper setup
Fetch different wallpapers for multiple monitors:class MultiMonitorWallpaper {
constructor(monitorCount) {
this.monitorCount = monitorCount;
this.wallpapers = [];
}
async fetchForAllMonitors(options = {}) {
const {
category = null,
color = null,
sameCategory = false
} = options;
if (sameCategory && category) {
// Fetch multiple wallpapers from the same category
const response = await fetch(
`https://wallwidgy.com/api/wallpapers?category=${category}&type=desktop&count=${this.monitorCount}`
);
const data = await response.json();
this.wallpapers = data.wallpapers;
} else {
// Fetch different categories for variety
const categories = ['nature', 'abstract', 'art', 'minimal', 'tech'];
const promises = [];
for (let i = 0; i < this.monitorCount; i++) {
const randomCategory = categories[i % categories.length];
const params = new URLSearchParams({
type: 'desktop',
count: '1'
});
if (category) {
params.set('category', category);
} else {
params.set('category', randomCategory);
}
if (color) params.set('color', color);
promises.push(
fetch(`https://wallwidgy.com/api/wallpapers?${params}`)
.then(res => res.json())
);
}
const results = await Promise.all(promises);
this.wallpapers = results.map(data => data.wallpapers[0]);
}
return this.wallpapers;
}
getWallpaperForMonitor(monitorIndex) {
return this.wallpapers[monitorIndex] || null;
}
}
// Usage
const multiMonitor = new MultiMonitorWallpaper(3);
// Option 1: Different categories for variety
await multiMonitor.fetchForAllMonitors();
// Option 2: Same category for cohesive look
await multiMonitor.fetchForAllMonitors({
category: 'nature',
sameCategory: true
});
// Apply wallpapers
for (let i = 0; i < 3; i++) {
const wallpaper = multiMonitor.getWallpaperForMonitor(i);
console.log(`Monitor ${i + 1}: ${wallpaper}`);
}
Smart wallpaper recommender
Recommend wallpapers based on user preferences and time of day:class SmartWallpaperRecommender {
constructor() {
this.userPreferences = {
favoriteCategories: [],
favoriteColors: [],
deviceType: this.detectDeviceType()
};
}
detectDeviceType() {
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ||
window.innerWidth < 768
? 'mobile'
: 'desktop';
}
getTimeBasedPreferences() {
const hour = new Date().getHours();
// Morning (6-12): Bright, energetic colors
if (hour >= 6 && hour < 12) {
return { colors: ['yellow', 'orange', 'white'], mood: 'energetic' };
}
// Afternoon (12-17): Balanced, natural colors
if (hour >= 12 && hour < 17) {
return { colors: ['blue', 'green', 'cyan'], mood: 'focused' };
}
// Evening (17-22): Warm, relaxing colors
if (hour >= 17 && hour < 22) {
return { colors: ['orange', 'purple', 'pink'], mood: 'relaxed' };
}
// Night (22-6): Dark, calming colors
return { colors: ['black', 'navy', 'purple'], mood: 'calm' };
}
async getRecommendations(count = 5) {
const timePrefs = this.getTimeBasedPreferences();
const color = timePrefs.colors[Math.floor(Math.random() * timePrefs.colors.length)];
const params = new URLSearchParams({
type: this.userPreferences.deviceType,
color: color,
count: count.toString()
});
// Add favorite category if available
if (this.userPreferences.favoriteCategories.length > 0) {
const randomCategory = this.userPreferences.favoriteCategories[
Math.floor(Math.random() * this.userPreferences.favoriteCategories.length)
];
params.set('category', randomCategory);
}
const response = await fetch(
`https://wallwidgy.com/api/wallpapers?${params}`
);
const data = await response.json();
return {
wallpapers: data.wallpapers,
mood: timePrefs.mood,
color: color,
category: data.category
};
}
setUserPreferences(preferences) {
this.userPreferences = { ...this.userPreferences, ...preferences };
}
}
// Usage
const recommender = new SmartWallpaperRecommender();
// Set user preferences
recommender.setUserPreferences({
favoriteCategories: ['anime', 'art', 'nature'],
favoriteColors: ['blue', 'purple']
});
// Get time-based recommendations
const recommendations = await recommender.getRecommendations(10);
console.log(`Mood: ${recommendations.mood}`);
console.log(`Color: ${recommendations.color}`);
console.log(`Category: ${recommendations.category}`);
console.log(`Wallpapers: ${recommendations.wallpapers.length}`);
Batch wallpaper downloader
Download multiple wallpapers with filtering:import requests
import os
from pathlib import Path
from urllib.parse import urlparse
from typing import Optional, List
class WallpaperDownloader:
"""Download wallpapers in batch with filters"""
def __init__(self, download_dir: str = './wallpapers'):
self.download_dir = Path(download_dir)
self.download_dir.mkdir(parents=True, exist_ok=True)
def fetch_wallpapers(
self,
category: Optional[str] = None,
color: Optional[str] = None,
device_type: Optional[str] = None,
count: int = 10
) -> List[str]:
"""Fetch wallpaper URLs from API"""
params = {'count': count}
if category:
params['category'] = category
if color:
params['color'] = color
if device_type:
params['type'] = device_type
response = requests.get(
'https://wallwidgy.com/api/wallpapers',
params=params
)
response.raise_for_status()
return response.json()['wallpapers']
def download_wallpaper(self, url: str) -> str:
"""Download a single wallpaper"""
filename = Path(urlparse(url).path).name
filepath = self.download_dir / filename
if filepath.exists():
print(f"Already exists: {filename}")
return str(filepath)
print(f"Downloading: {filename}")
response = requests.get(url, stream=True)
response.raise_for_status()
with open(filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Saved: {filepath}")
return str(filepath)
def download_batch(
self,
category: Optional[str] = None,
color: Optional[str] = None,
device_type: Optional[str] = None,
count: int = 10
) -> List[str]:
"""Fetch and download multiple wallpapers"""
print(f"Fetching {count} wallpapers...")
print(f"Category: {category or 'all'}")
print(f"Color: {color or 'all'}")
print(f"Device type: {device_type or 'all'}")
print()
urls = self.fetch_wallpapers(category, color, device_type, count)
print(f"Found {len(urls)} wallpapers\n")
downloaded = []
for i, url in enumerate(urls, 1):
print(f"[{i}/{len(urls)}] ", end='')
try:
filepath = self.download_wallpaper(url)
downloaded.append(filepath)
except Exception as e:
print(f"Error downloading {url}: {e}")
print(f"\nDownloaded {len(downloaded)} wallpapers to {self.download_dir}")
return downloaded
# Usage
downloader = WallpaperDownloader(download_dir='./my_wallpapers')
# Download 20 anime wallpapers for mobile
downloader.download_batch(
category='anime',
device_type='mobile',
count=20
)
# Download 10 blue nature wallpapers for desktop
downloader.download_batch(
category='nature',
color='blue',
device_type='desktop',
count=10
)
Best practices
Always handle API errors gracefully and implement retry logic for production applications.
Error handling
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Attempt ${i + 1} failed:`, error.message);
if (i === maxRetries - 1) {
throw error;
}
// Wait before retrying (exponential backoff)
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}
// Usage
try {
const data = await fetchWithRetry(
'https://wallwidgy.com/api/wallpapers?category=anime&count=5'
);
console.log(data);
} catch (error) {
console.error('Failed to fetch wallpapers:', error);
}
Cache wallpaper URLs locally to reduce API calls and improve performance.