Color Palette Generator API Guide
Overview
The Color Palette Generator API provides a simple way to create harmonious color combinations for your design projects. Whether you need complementary colors, analogous schemes, or predefined palettes, this API offers multiple ways to generate beautiful color combinations.
Quick Start
# Generate a random palette
curl "https://blstmo.com/api/color-palette"
# Generate a complementary palette based on a specific color
curl "https://blstmo.com/api/color-palette?type=complementary&color=%23FF5733"
# Get a predefined palette
curl "https://blstmo.com/api/color-palette?type=sunset"
Rate Limiting
The API is rate-limited to 120 requests per minute. If you exceed this limit, you will receive a 429 status code with an error message indicating that the rate limit has been exceeded.
API Reference
Endpoint
GET https://blstmo.com/api/color-palette
Query Parameters
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
type | string | No | random | Type of palette to generate: ‘complementary’, ‘analogous’, ‘triadic’, ‘monochromatic’, ‘random’, or predefined palette names (‘sunset’, ‘forest’, ‘ocean’, ‘pastel’, ‘neon’, ‘grayscale’) |
color | string | No | Random | Base color in hexadecimal format (e.g., ‘#FF5733’). Required for ‘complementary’, ‘analogous’, ‘triadic’, and ‘monochromatic’ types |
count | number | No | 6 | Number of colors to include in the palette (1-10) |
Response Format
{
colors: string[]; // Array of hex color codes
type: string; // Type of palette generated
baseColor?: string; // Base color used (for generated palettes)
name?: string; // Name of the palette (for predefined palettes)
}
Palette Types
Complementary
Generates a palette based on colors opposite each other on the color wheel. Provides high contrast and visual impact.
GET /api/color-palette?type=complementary&color=#FF5733
Analogous
Creates a palette using colors adjacent to each other on the color wheel. Provides a harmonious, cohesive look.
GET /api/color-palette?type=analogous&color=#FF5733
Triadic
Generates a palette using three colors equally spaced around the color wheel. Offers vibrant contrast while maintaining harmony.
GET /api/color-palette?type=triadic&color=#FF5733
Monochromatic
Creates a palette using different shades and tints of a single color. Perfect for subtle, elegant designs.
GET /api/color-palette?type=monochromatic&color=#FF5733
Random
Generates a completely random palette of colors.
GET /api/color-palette?type=random
Predefined Palettes
The API includes several carefully curated predefined palettes:
sunset
: Warm, vibrant colors inspired by sunset huesforest
: Natural, earthy tones inspired by forest landscapesocean
: Cool, calming blues and teals inspired by ocean waterspastel
: Soft, light colors perfect for gentle designsneon
: Bright, high-contrast colors for bold designsgrayscale
: A range of gray tones from black to white
GET /api/color-palette?type=sunset
Error Responses
Status | Description |
---|---|
400 | Invalid parameters (e.g., invalid color format, invalid type) |
429 | Rate limit exceeded |
500 | Server error |
Implementation Examples
JavaScript/TypeScript
async function getColorPalette(options: {
type?: string;
color?: string;
count?: number;
}) {
const params = new URLSearchParams();
if (options.type) params.append('type', options.type);
if (options.color) params.append('color', options.color);
if (options.count) params.append('count', options.count.toString());
const response = await fetch(`https://blstmo.com/api/color-palette?${params}`);
if (response.status === 429) {
throw new Error('Rate limit exceeded. Please try again later.');
}
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to generate palette');
}
return data;
}
// Example usage
try {
// Get a complementary palette based on a specific color
const palette = await getColorPalette({
type: 'complementary',
color: '#3498db',
count: 6
});
console.log('Generated palette:', palette);
// Use the colors in your application
palette.colors.forEach(color => {
// Apply colors to elements
console.log(`Using color: ${color}`);
});
} catch (error) {
console.error('Error:', error.message);
}
Python
import requests
from typing import Dict, List, Optional, Any
def get_color_palette(
type: Optional[str] = None,
color: Optional[str] = None,
count: Optional[int] = None
) -> Dict[str, Any]:
"""
Generate a color palette using the API.
Args:
type: Type of palette ('complementary', 'analogous', 'triadic',
'monochromatic', 'random', or predefined names)
color: Base color in hex format (e.g., '#FF5733')
count: Number of colors to include (1-10)
Returns:
Dictionary containing the generated palette
Raises:
requests.exceptions.HTTPError: If the API request fails
ValueError: If the rate limit is exceeded
"""
params = {}
if type: params['type'] = type
if color: params['color'] = color
if count: params['count'] = count
response = requests.get(
'https://blstmo.com/api/color-palette',
params=params
)
if response.status_code == 429:
raise ValueError('Rate limit exceeded. Please try again later.')
response.raise_for_status()
return response.json()
# Example usage
try:
# Get a triadic palette
palette = get_color_palette(
type='triadic',
color='#2ecc71',
count=6
)
print(f"Generated {palette['type']} palette:")
for color in palette['colors']:
print(f"- {color}")
except (requests.exceptions.RequestException, ValueError) as e:
print(f"Error: {str(e)}")
Use Cases
1. Web Design
Generate color schemes for websites, ensuring visual harmony and accessibility:
// Generate a website color scheme
const palette = await getColorPalette({ type: 'analogous', color: '#3498db' });
document.documentElement.style.setProperty('--primary-color', palette.colors[0]);
document.documentElement.style.setProperty('--secondary-color', palette.colors[1]);
document.documentElement.style.setProperty('--accent-color', palette.colors[2]);
document.documentElement.style.setProperty('--background-color', palette.colors[3]);
document.documentElement.style.setProperty('--text-color', palette.colors[4]);
2. Data Visualization
Create visually distinct but harmonious colors for charts and graphs:
// Generate colors for a chart
const chartPalette = await getColorPalette({
type: 'triadic',
color: '#2ecc71',
count: 8
});
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug'],
datasets: [{
label: 'Monthly Data',
data: [12, 19, 3, 5, 2, 3, 7, 8],
backgroundColor: chartPalette.colors
}]
}
});
3. Design Systems
Generate consistent color palettes for design systems and style guides:
// Generate a design system color palette
const mainPalette = await getColorPalette({ type: 'complementary', color: '#9b59b6' });
const accentPalette = await getColorPalette({ type: 'analogous', color: mainPalette.colors[3] });
const designSystem = {
colors: {
primary: mainPalette.colors[0],
secondary: mainPalette.colors[1],
tertiary: mainPalette.colors[2],
accent1: accentPalette.colors[0],
accent2: accentPalette.colors[1],
accent3: accentPalette.colors[2],
background: '#ffffff',
text: '#333333'
}
};
console.log('Design System Colors:', designSystem.colors);
Best Practices
1. Color Accessibility
When using generated palettes, ensure sufficient contrast for text readability:
// Check contrast ratio between text and background
function hasGoodContrast(textColor, backgroundColor) {
// Simplified contrast check - implement a proper WCAG contrast algorithm in production
const textRgb = hexToRgb(textColor);
const bgRgb = hexToRgb(backgroundColor);
// Calculate luminance difference (simplified)
const luminanceDiff = Math.abs(
(0.299 * textRgb.r + 0.587 * textRgb.g + 0.114 * textRgb.b) -
(0.299 * bgRgb.r + 0.587 * bgRgb.g + 0.114 * bgRgb.b)
);
return luminanceDiff > 128; // Simplified threshold
}
2. Caching
Cache palette results to reduce API calls:
const paletteCache = new Map();
async function getCachedPalette(options) {
const cacheKey = JSON.stringify(options);
if (paletteCache.has(cacheKey)) {
return paletteCache.get(cacheKey);
}
const palette = await getColorPalette(options);
paletteCache.set(cacheKey, palette);
return palette;
}
3. Error Handling
Implement proper error handling and fallbacks:
async function getPaletteWithFallback(options) {
try {
return await getColorPalette(options);
} catch (error) {
console.error('Failed to get palette:', error);
// Fallback to a safe default palette
return {
colors: ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', '#1abc9c'],
type: 'fallback'
};
}
}
Support
For support, please contact our team at [email protected].