Code Examples
Real-world examples for integrating with the Pixelsuite API
Quick Start Examples
PHP with cURL
<?php
// Load API key from environment or configuration
$apiKey = getenv('PIXELSUITE_API_KEY');
// Make authenticated request to get client info
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.pixelsuite.com.au/v1/client',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
]
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// Parse response
$data = json_decode($response, true);
if ($httpCode === 200 && $data['success']) {
$client = $data['data']['client'];
echo "Client: {$client['displayName']}\n";
echo "Venues: " . count($data['data']['venues']) . "\n";
} else {
echo "Error: " . ($data['message'] ?? 'Unknown error') . "\n";
}
?>
PHP with Guzzle
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$apiKey = getenv('PIXELSUITE_API_KEY');
$client = new Client([
'base_uri' => 'https://api.pixelsuite.com.au/v1/',
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Content-Type' => 'application/json'
]
]);
try {
$response = $client->get('client');
$data = json_decode($response->getBody(), true);
if ($data['success']) {
echo "Client: " . $data['data']['client']['displayName'] . "\n";
echo "Timezone: " . $data['data']['client']['timezone'] . "\n";
}
} catch (RequestException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
JavaScript Examples
Modern JavaScript (Fetch API)
const apiKey = process.env.PIXELSUITE_API_KEY;
async function getClientInfo() {
try {
const response = await fetch('https://api.pixelsuite.com.au/v1/client', {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.success) {
console.log('Client:', data.data.client.displayName);
console.log('Venues:', data.data.venues.length);
} else {
console.error('Error:', data.message);
}
} catch (error) {
console.error('Request failed:', error);
}
}
getClientInfo();
Node.js with Axios
const axios = require('axios');
const apiKey = process.env.PIXELSUITE_API_KEY;
const api = axios.create({
baseURL: 'https://api.pixelsuite.com.au/v1',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
// Make request
api.get('/client')
.then(response => {
const data = response.data;
if (data.success) {
console.log('Client:', data.data.client.displayName);
console.log('Venues:', data.data.venues.length);
}
})
.catch(error => {
if (error.response) {
console.error('Error:', error.response.data.message);
} else {
console.error('Request failed:', error.message);
}
});
Python Examples
Python with Requests
import os
import requests
# Load API key from environment
api_key = os.getenv('PIXELSUITE_API_KEY')
# Make authenticated request
response = requests.get(
'https://api.pixelsuite.com.au/v1/client',
headers={
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
)
# Parse response
data = response.json()
if response.status_code == 200 and data['success']:
client = data['data']['client']
print(f"Client: {client['displayName']}")
print(f"Venues: {len(data['data']['venues'])}")
else:
print(f"Error: {data.get('message', 'Unknown error')}")
Python Class Example
import os
import requests
from typing import Dict, Any, Optional
class PixelsuiteAPI:
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.getenv('PIXELSUITE_API_KEY')
self.base_url = 'https://api.pixelsuite.com.au/v1'
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
})
def _request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
url = f'{self.base_url}/{endpoint.lstrip("/")}'
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
return response.json()
def get_client(self) -> Dict[str, Any]:
return self._request('GET', '/client')
def get_channels(self, page: int = 1, limit: int = 50) -> Dict[str, Any]:
return self._request('GET', '/channels', params={'page': page, 'limit': limit})
def get_channel_content(self, guid: str, screen_mode: str = 'land') -> Dict[str, Any]:
return self._request('POST', '/channel/content', json={
'guid': guid,
'screenMode': screen_mode
})
# Usage
api = PixelsuiteAPI()
# Get client information
client_data = api.get_client()
print(f"Client: {client_data['data']['client']['displayName']}")
# Get channels list
channels = api.get_channels(limit=10)
print(f"Total channels: {channels['data']['pagination']['total']}")
Error Handling
Comprehensive Error Handling (JavaScript)
async function callAPIWithErrorHandling(endpoint) {
try {
const response = await fetch(`https://api.pixelsuite.com.au/v1/${endpoint}`, {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
const data = await response.json();
// Check HTTP status
if (!response.ok) {
switch (response.status) {
case 401:
throw new Error('Authentication failed - check your API key');
case 403:
throw new Error('Access forbidden - insufficient permissions');
case 404:
throw new Error('Endpoint or resource not found');
case 429:
throw new Error('Rate limit exceeded - try again later');
case 500:
throw new Error('Server error - please contact support');
default:
throw new Error(data.message || 'Unknown error');
}
}
// Check API success flag
if (!data.success) {
throw new Error(data.message || 'Request failed');
}
return data.data;
} catch (error) {
console.error('API Error:', error.message);
// Log request ID for support
if (error.response?.data?.requestId) {
console.error('Request ID:', error.response.data.requestId);
}
throw error;
}
}
Retry Logic with Exponential Backoff (PHP)
<?php
function makeAPIRequest($url, $apiKey, $maxRetries = 3) {
$attempt = 0;
$backoff = 1; // Initial backoff in seconds
while ($attempt < $maxRetries) {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey
]
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// Success
if ($httpCode >= 200 && $httpCode < 300) {
return json_decode($response, true);
}
// Rate limit or server error - retry
if ($httpCode === 429 || $httpCode >= 500) {
$attempt++;
if ($attempt < $maxRetries) {
sleep($backoff);
$backoff *= 2; // Exponential backoff
continue;
}
}
// Other errors - don't retry
throw new Exception("API request failed with status $httpCode");
}
throw new Exception("Max retries exceeded");
}
?>
Working with Pagination
Fetching All Pages (JavaScript)
async function fetchAllChannels(apiKey) {
const allChannels = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const response = await fetch(
`https://api.pixelsuite.com.au/v1/channels?page=${page}&limit=100`,
{
headers: { 'Authorization': `Bearer ${apiKey}` }
}
);
const data = await response.json();
if (data.success) {
allChannels.push(...data.data.channels);
hasMore = data.data.pagination.hasMore;
page++;
} else {
throw new Error(data.message);
}
}
return allChannels;
}
// Usage
const allChannels = await fetchAllChannels(apiKey);
console.log(`Fetched ${allChannels.length} channels`);
Best Practices
Security & Performance Tips
- API Key Security: Store API keys in environment variables or secure vaults, never hardcode them in source code
- Error Handling: Always check both HTTP status codes and the
successfield in responses - Rate Limiting: Monitor rate limit headers and implement exponential backoff for retry logic
- HTTPS Only: Always use HTTPS for API requests to ensure encrypted communication
- Caching: Cache responses when appropriate to reduce API calls and improve performance
- Logging: Log API errors with request IDs for easier debugging and support
- Timeouts: Set reasonable timeouts (30-60 seconds) to prevent hanging requests
- Pagination: Use appropriate page sizes (50-100) to balance performance and data completeness
Next Steps
Now that you've seen code examples, explore these resources: