PHP Examples
Authentication
Using Personal Access Token (Recommended for Development)
<?php
require_once 'vendor/autoload.php';
use TradingCardAPI\Client;
// Initialize with Personal Access Token
$client = new Client([
'personal_access_token' => getenv('TRADING_CARD_API_PAT'),
'base_url' => 'https://api.tradingcardapi.com'
]);
// No additional authentication steps required!
// The token is automatically included in all requests
Using OAuth 2.0 Client Credentials (Recommended for Production)
<?php
require_once 'vendor/autoload.php';
use TradingCardAPI\Client;
// Initialize with OAuth credentials
$client = new Client([
'client_id' => getenv('TRADING_CARD_API_CLIENT_ID'),
'client_secret' => getenv('TRADING_CARD_API_CLIENT_SECRET'),
'base_url' => 'https://api.tradingcardapi.com'
]);
// Client handles OAuth token flow automatically
Basic Usage
<?php
require_once 'vendor/autoload.php';
use TradingCardAPI\Client;
$client = new Client([
'client_id' => 'your_client_id',
'client_secret' => 'your_client_secret',
'base_url' => 'https://api.tradingcardapi.com'
]);
// Get cards
$cards = $client->cards()->list([
'page[limit]' => 25,
'filter[year]' => 2023
]);
foreach ($cards['data'] as $card) {
echo $card['attributes']['name'] . "\n";
}
Advanced Filtering
// Search with multiple filters
$results = $client->cards()->list([
'filter[year]' => 1989,
'filter[name]' => '*Griffey*',
'include' => 'set,oncard',
'sort' => 'name',
'page[limit]' => 50
]);
Cards
Fetch Card with Image Reference
// Get a card and check for image_uuid
$cardId = '550e8400-e29b-41d4-a716-446655440000';
try {
$response = $client->cards()->get($cardId);
$card = $response['data'];
echo "Card: " . $card['attributes']['name'] . "\n";
echo "Number: " . $card['attributes']['number'] . "\n";
// Check if card has an image reference (v0.6.0+)
if (!empty($card['attributes']['image_uuid'])) {
echo "Image UUID: " . $card['attributes']['image_uuid'] . "\n";
} else {
echo "No image uploaded yet\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Include Card Images in Response
// Fetch card with related images included (v0.7.0+)
$cardId = '550e8400-e29b-41d4-a716-446655440000';
try {
$response = $client->cards()->get($cardId, [
'include' => 'images'
]);
$card = $response['data'];
echo "Card: " . $card['attributes']['name'] . "\n";
// Access included images
if (!empty($response['included'])) {
foreach ($response['included'] as $included) {
if ($included['type'] === 'card_images') {
echo "Image: " . $included['attributes']['side'] . "\n";
echo "URL: " . $included['attributes']['image_url'] . "\n";
}
}
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
List Cards with Images
// List cards and include their images
$results = $client->cards()->list([
'filter[set_id]' => '550e8400-e29b-41d4-a716-446655440000',
'include' => 'images,set',
'page[limit]' => 25
]);
foreach ($results['data'] as $card) {
echo $card['attributes']['number'] . " - " . $card['attributes']['name'];
// Check for image_uuid
if (!empty($card['attributes']['image_uuid'])) {
echo " [Has Image]";
}
echo "\n";
}
// Process included images
if (!empty($results['included'])) {
$images = array_filter($results['included'], function($item) {
return $item['type'] === 'card_images';
});
echo "\nTotal images included: " . count($images) . "\n";
}
File Uploads
Upload Card Image
// Upload a card image with validation and error handling
$imagePath = '/path/to/card-front.jpg';
// Validate file before upload
if (!file_exists($imagePath)) {
throw new Exception("Image file not found: $imagePath");
}
$fileSize = filesize($imagePath);
$maxSize = 10 * 1024 * 1024; // 10MB
if ($fileSize > $maxSize) {
throw new Exception("Image too large. Maximum size: 10MB");
}
// Validate image type
$mimeType = mime_content_type($imagePath);
$allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
if (!in_array($mimeType, $allowedTypes)) {
throw new Exception("Invalid image type. Allowed: JPEG, PNG");
}
try {
$imageData = [
'type' => 'card_images',
'attributes' => [
'card_id' => '550e8400-e29b-41d4-a716-446655440000',
'image_type' => 'front'
]
];
$response = $client->cardImages()->create([
'file' => new \CURLFile($imagePath, $mimeType, basename($imagePath)),
'data' => json_encode($imageData)
]);
echo "Image uploaded successfully!\n";
echo "Image ID: " . $response['data']['id'] . "\n";
echo "Small URL: " . $response['data']['attributes']['variants']['small']['url'] . "\n";
echo "Medium URL: " . $response['data']['attributes']['variants']['medium']['url'] . "\n";
echo "Large URL: " . $response['data']['attributes']['variants']['large']['url'] . "\n";
$imageId = $response['data']['id'];
} catch (Exception $e) {
echo "Upload failed: " . $e->getMessage() . "\n";
exit(1);
}
List Card Images
// List all images for a specific card
$cardId = '550e8400-e29b-41d4-a716-446655440000';
$images = $client->cardImages()->list([
'filter[card_id]' => $cardId
]);
foreach ($images['data'] as $image) {
echo "Image ID: " . $image['id'] . "\n";
echo "Type: " . $image['attributes']['image_type'] . "\n";
echo "Small URL: " . $image['attributes']['variants']['small']['url'] . "\n";
echo "---\n";
}
Download Card Image
// Download specific size variant
$imageId = '01234567-89ab-cdef-0123-456789abcdef';
$imageUrl = "https://api.tradingcardapi.com/v1/card-images/{$imageId}/download?size=medium";
$ch = curl_init($imageUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow CDN redirects
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $client->getAccessToken()
]);
$imageData = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $imageData) {
file_put_contents('card-image.jpg', $imageData);
echo "Image downloaded successfully\n";
} else {
echo "Download failed with HTTP code: $httpCode\n";
}
Update Image Metadata
// Update image metadata (e.g., change from front to back)
$imageId = '01234567-89ab-cdef-0123-456789abcdef';
try {
$response = $client->cardImages()->update($imageId, [
'type' => 'card_images',
'id' => $imageId,
'attributes' => [
'image_type' => 'back'
]
]);
echo "Image metadata updated successfully\n";
echo "New type: " . $response['data']['attributes']['image_type'] . "\n";
} catch (Exception $e) {
echo "Update failed: " . $e->getMessage() . "\n";
}
Delete Card Image
// Delete a card image
$imageId = '01234567-89ab-cdef-0123-456789abcdef';
try {
$client->cardImages()->delete($imageId);
echo "Image deleted successfully\n";
} catch (Exception $e) {
echo "Deletion failed: " . $e->getMessage() . "\n";
}
Responsive Images with Versioned CDN URLs
// Fetch image with versioned CDN URLs
$imageResponse = $client->cardImages()->get($imageId);
$attrs = $imageResponse['data']['attributes'];
// All URLs include version parameter (?v=timestamp) for automatic cache invalidation
$smallUrl = $attrs['variants']['small']['url'];
$mediumUrl = $attrs['variants']['medium']['url'];
$largeUrl = $attrs['variants']['large']['url'];
// Generate responsive image markup
echo '<img
src="' . htmlspecialchars($smallUrl) . '"
srcset="
' . htmlspecialchars($smallUrl) . ' 150w,
' . htmlspecialchars($mediumUrl) . ' 300w,
' . htmlspecialchars($largeUrl) . ' 600w
"
sizes="(max-width: 640px) 150px, 300px"
alt="Card image"
loading="lazy"
/>';
// Or create a reusable function
function generateResponsiveCardImage($client, $imageId, $cardName) {
$image = $client->cardImages()->get($imageId);
$attrs = $image['data']['attributes'];
return sprintf(
'<img src="%s" srcset="%s 150w, %s 300w, %s 600w" ' .
'sizes="(max-width: 640px) 150px, 300px" alt="%s" loading="lazy" />',
htmlspecialchars($attrs['variants']['small']['url']),
htmlspecialchars($attrs['variants']['small']['url']),
htmlspecialchars($attrs['variants']['medium']['url']),
htmlspecialchars($attrs['variants']['large']['url']),
htmlspecialchars($cardName)
);
}
Set Sources
Create Set Source
// Add a checklist source to a set
$setId = '550e8400-e29b-41d4-a716-446655440000';
try {
$sourceData = [
'type' => 'set_sources',
'attributes' => [
'set_id' => $setId,
'source_type' => 'checklist',
'source_name' => 'Beckett Online Price Guide',
'source_url' => 'https://www.beckett.com/price-guides'
]
];
$response = $client->setSources()->create($sourceData);
echo "Source created successfully!\n";
echo "Source ID: " . $response['data']['id'] . "\n";
echo "Type: " . $response['data']['attributes']['source_type'] . "\n";
echo "Name: " . $response['data']['attributes']['source_name'] . "\n";
} catch (Exception $e) {
echo "Failed to create source: " . $e->getMessage() . "\n";
}
List Sources for a Set
// Get all sources for a specific set
$setId = '550e8400-e29b-41d4-a716-446655440000';
$sources = $client->setSources()->list([
'filter[set_id]' => $setId
]);
echo "Found " . count($sources['data']) . " sources\n\n";
foreach ($sources['data'] as $source) {
echo "Source Type: " . $source['attributes']['source_type'] . "\n";
echo "Name: " . $source['attributes']['source_name'] . "\n";
echo "URL: " . $source['attributes']['source_url'] . "\n";
if (isset($source['attributes']['verified_at'])) {
echo "Verified: " . $source['attributes']['verified_at'] . "\n";
}
echo "---\n";
}
Get Set with Sources Included
// Fetch a set with all its sources using include parameter
$setId = '550e8400-e29b-41d4-a716-446655440000';
$response = $client->sets()->get($setId, [
'include' => 'sources'
]);
$set = $response['data'];
echo "Set: " . $set['attributes']['name'] . "\n";
echo "Year: " . $set['attributes']['year'] . "\n\n";
// Sources are in the included array
if (isset($response['included'])) {
echo "Data Sources:\n";
foreach ($response['included'] as $included) {
if ($included['type'] === 'set_sources') {
echo "- " . $included['attributes']['source_type'] . ": ";
echo $included['attributes']['source_name'] . "\n";
}
}
}
Update Source Verification
// Update a source to mark it as verified
$sourceId = '01234567-89ab-cdef-0123-456789abcdef';
try {
$response = $client->setSources()->update($sourceId, [
'type' => 'set_sources',
'id' => $sourceId,
'attributes' => [
'verified_at' => date('c') // ISO 8601 format
]
]);
echo "Source verified at: " . $response['data']['attributes']['verified_at'] . "\n";
} catch (Exception $e) {
echo "Verification failed: " . $e->getMessage() . "\n";
}
Delete Set Source
// Remove a source from a set
$sourceId = '01234567-89ab-cdef-0123-456789abcdef';
try {
$client->setSources()->delete($sourceId);
echo "Source deleted successfully\n";
} catch (Exception $e) {
echo "Deletion failed: " . $e->getMessage() . "\n";
}
Track Multiple Source Types
// Add multiple sources for different data types
$setId = '550e8400-e29b-41d4-a716-446655440000';
$sourceTypes = [
[
'type' => 'checklist',
'name' => 'COMC Database',
'url' => 'https://www.comc.com'
],
[
'type' => 'metadata',
'name' => 'CardboardConnection',
'url' => 'https://www.cardboardconnection.com'
],
[
'type' => 'images',
'name' => 'Trading Card Database',
'url' => 'https://www.tradingcarddb.com'
]
];
foreach ($sourceTypes as $sourceInfo) {
try {
$response = $client->setSources()->create([
'type' => 'set_sources',
'attributes' => [
'set_id' => $setId,
'source_type' => $sourceInfo['type'],
'source_name' => $sourceInfo['name'],
'source_url' => $sourceInfo['url']
]
]);
echo "Added " . $sourceInfo['type'] . " source: " . $sourceInfo['name'] . "\n";
} catch (Exception $e) {
echo "Failed to add " . $sourceInfo['type'] . " source: " . $e->getMessage() . "\n";
}
}
v2 Endpoints
Get Set Checklist (v2)
// v2 endpoint returns cards as primary data (correct JSON:API semantics)
$setId = '550e8400-e29b-41d4-a716-446655440000';
try {
$response = $client->get("/v2/sets/{$setId}/checklist");
$cards = $response['data'];
$set = $response['included'][0] ?? null;
foreach ($cards as $card) {
echo "Card #{$card['attributes']['number']}: {$card['attributes']['name']}\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Compact Format for Large Sets
// Use compact format to reduce response size by ~75%
$setId = '550e8400-e29b-41d4-a716-446655440000';
try {
$response = $client->get("/v2/sets/{$setId}/checklist", [
'format' => 'compact'
]);
foreach ($response['data'] as $card) {
$attrs = $card['attributes'];
printf("#%-4s %s\n", $attrs['number'], $attrs['name']);
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}