Skip to main content

Working with Card Images

The Card Images API allows you to upload, manage, and download trading card images. This guide covers everything you need to know about working with card images in the Trading Card API.

Overview

The Card Images API provides endpoints for:

  • Uploading card images with automatic JPEG conversion
  • Downloading images with multiple size variants (thumbnails)
  • Managing images with full CRUD operations
  • Soft delete support for image retention
  • Front and back images for each card

All images are automatically processed and converted to JPEG format for consistency, and thumbnail variants are generated asynchronously.

Image Requirements

Supported Formats

  • JPEG (.jpg, .jpeg)
  • PNG (.png)
  • WebP (.webp)

All uploaded images are automatically converted to JPEG format.

Size Limits

  • Maximum file size: 10MB
  • Maximum dimensions: 4000 x 4000 pixels
  • Minimum dimensions: No minimum (but high quality images recommended)

Image Types

Each card can have two types of images:

  • front: The front side of the card
  • back: The back side of the card
Unique Constraint

Each card can only have one front image and one back image. Uploading a new front or back image will replace the existing one for that card.

Uploading Card Images

Using PHP

<?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'
]);

// Prepare the image data
$imageData = [
'type' => 'card_images',
'attributes' => [
'card_id' => '550e8400-e29b-41d4-a716-446655440000',
'image_type' => 'front'
]
];

// Upload the image
$response = $client->cardImages()->create([
'file' => new \CURLFile('/path/to/card-front.jpg', 'image/jpeg', 'card-front.jpg'),
'data' => json_encode($imageData)
]);

echo "Image uploaded successfully!\n";
echo "Image ID: " . $response['data']['id'] . "\n";
echo "Width: " . $response['data']['attributes']['width'] . "px\n";
echo "Height: " . $response['data']['attributes']['height'] . "px\n";
echo "File size: " . round($response['data']['attributes']['file_size'] / 1024, 2) . " KB\n";

Using JavaScript

const TradingCardAPI = require('trading-card-api');
const fs = require('fs');
const FormData = require('form-data');

const client = new TradingCardAPI({
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
baseUrl: 'https://api.tradingcardapi.com'
});

// Prepare the form data
const form = new FormData();
form.append('file', fs.createReadStream('/path/to/card-front.jpg'));
form.append('data', JSON.stringify({
type: 'card_images',
attributes: {
card_id: '550e8400-e29b-41d4-a716-446655440000',
image_type: 'front'
}
}));

// Upload the image
const response = await client.cardImages.create(form);

console.log('Image uploaded successfully!');
console.log('Image ID:', response.data.id);
console.log('Width:', response.data.attributes.width, 'px');
console.log('Height:', response.data.attributes.height, 'px');
console.log('File size:', (response.data.attributes.file_size / 1024).toFixed(2), 'KB');

Using Python

from trading_card_api import Client
import json

client = Client(
client_id='your_client_id',
client_secret='your_client_secret',
base_url='https://api.tradingcardapi.com'
)

# Prepare the upload
with open('/path/to/card-front.jpg', 'rb') as image_file:
files = {
'file': ('card-front.jpg', image_file, 'image/jpeg')
}
data = {
'data': json.dumps({
'type': 'card_images',
'attributes': {
'card_id': '550e8400-e29b-41d4-a716-446655440000',
'image_type': 'front'
}
})
}

response = client.card_images.create(files=files, data=data)

print('Image uploaded successfully!')
print(f"Image ID: {response['data']['id']}")
print(f"Width: {response['data']['attributes']['width']}px")
print(f"Height: {response['data']['attributes']['height']}px")
print(f"File size: {response['data']['attributes']['file_size'] / 1024:.2f} KB")

Using cURL

curl -X POST https://api.tradingcardapi.com/v1/card-images \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: multipart/form-data" \
-F "file=@/path/to/card-front.jpg" \
-F 'data={"type":"card_images","attributes":{"card_id":"550e8400-e29b-41d4-a716-446655440000","image_type":"front"}}'

Downloading Card Images

The API provides a special /download endpoint that returns the actual image file (not JSON).

Size Variants

Images are available in multiple sizes with automatic thumbnail generation:

  • original: The original uploaded image (converted to JPEG, 100% quality)
  • large: 600px width, 85% JPEG quality
  • medium: 300px width, 80% JPEG quality
  • small: 150px width, 75% JPEG quality

Thumbnails are generated asynchronously after upload. If a thumbnail is not yet ready, the original image is returned. All variants maintain the original aspect ratio.

Responsive Images

For optimal performance across devices, use size variants with responsive image techniques like srcset and sizes. See the Responsive Card Images guide for detailed examples and best practices.

CDN Delivery

All card images are delivered via DigitalOcean Spaces CDN with versioned URLs for automatic cache invalidation. The download endpoint returns a 302 redirect to the CDN URL (not proxied), allowing direct fetching from the nearest edge location. See the CDN Integration guide for details on versioned URLs, cache headers, and performance optimization.

Using PHP

$imageId = '123e4567-e89b-12d3-a456-426614174000';

// Download medium size variant
$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_HTTPHEADER, [
'Authorization: Bearer ' . $client->getAccessToken()
]);

$imageData = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
file_put_contents('card-image-medium.jpg', $imageData);
echo "Image downloaded successfully!\n";
}

Using JavaScript

const imageId = '123e4567-e89b-12d3-a456-426614174000';
const size = 'medium'; // original, large, medium, or small

const imageUrl = `https://api.tradingcardapi.com/v1/card-images/${imageId}/download?size=${size}`;

const response = await fetch(imageUrl, {
headers: {
'Authorization': `Bearer ${client.accessToken}`
}
});

if (response.ok) {
const buffer = await response.arrayBuffer();
fs.writeFileSync('card-image-medium.jpg', Buffer.from(buffer));
console.log('Image downloaded successfully!');
}

Using Python

import requests

image_id = '123e4567-e89b-12d3-a456-426614174000'
size = 'medium' # original, large, medium, or small

image_url = f'https://api.tradingcardapi.com/v1/card-images/{image_id}/download?size={size}'

headers = {'Authorization': f'Bearer {client.access_token}'}
response = requests.get(image_url, headers=headers)

if response.status_code == 200:
with open('card-image-medium.jpg', 'wb') as f:
f.write(response.content)
print('Image downloaded successfully!')

Listing Card Images

Get all images for a specific card

curl -X GET "https://api.tradingcardapi.com/v1/card-images?filter[card_id]=550e8400-e29b-41d4-a716-446655440000" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
curl -X GET "https://api.tradingcardapi.com/v1/card-images?include=card" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Updating Card Images

You can update the image type or replace the image file.

$imageId = '123e4567-e89b-12d3-a456-426614174000';

$response = $client->cardImages()->update($imageId, [
'type' => 'card_images',
'id' => $imageId,
'attributes' => [
'image_type' => 'back'
]
]);

Deleting Card Images

Card images use soft delete, so deleted images are retained in the database but marked as deleted.

$imageId = '123e4567-e89b-12d3-a456-426614174000';

$client->cardImages()->delete($imageId);

echo "Image deleted successfully!\n";

Error Handling

Validation Errors

{
"errors": [
{
"status": "422",
"title": "Validation Error",
"detail": "The file field is required.",
"source": {
"pointer": "/data/attributes/file"
}
}
]
}

Common Errors

Error CodeDescriptionSolution
422File too large (> 10MB)Reduce file size before upload
422Invalid file formatUse JPEG, PNG, or WebP
422Dimensions exceed 4000x4000Resize image before upload
422Duplicate image type for cardDelete existing image or use update endpoint
404Card not foundVerify the card_id exists
401UnauthorizedCheck your authentication token

Handling Upload Errors

try {
$response = $client->cardImages()->create([
'file' => new \CURLFile($filePath),
'data' => json_encode($imageData)
]);
} catch (\TradingCardAPI\Exceptions\ValidationException $e) {
foreach ($e->getErrors() as $error) {
echo "Error: " . $error['detail'] . "\n";
}
} catch (\TradingCardAPI\Exceptions\ApiException $e) {
echo "API Error: " . $e->getMessage() . "\n";
}

Best Practices

Image Optimization

  1. Compress images before upload - Use tools like TinyPNG or ImageOptim
  2. Use appropriate dimensions - 1200-2400px width is ideal for card images
  3. Prefer JPEG for photos - Better compression for card images
  4. Use PNG for graphics - If transparency is needed (will be converted to JPEG)

Performance Tips

  1. Use thumbnail variants - Load small or medium for listings, large or original for detail views
  2. Implement responsive images - Use srcset and sizes to deliver optimal images for each device (see Responsive Card Images guide)
  3. Leverage CDN delivery - All images are delivered via global CDN with versioned URLs for automatic cache invalidation (see CDN Integration guide)
  4. Cache downloaded images - Store images locally to reduce API calls
  5. Lazy load images - Load images as needed, not all at once
  6. Check thumbnail availability - Wait for thumbnails to be generated for best quality

Security Considerations

  1. Validate files client-side - Check file type and size before upload
  2. Handle errors gracefully - Don't expose internal errors to users
  3. Use HTTPS - Always use secure connections for image uploads/downloads
  4. Rotate access tokens - Refresh tokens regularly

Troubleshooting

Images not uploading

Problem: Upload request returns 422 error

Solutions:

  • Check file size is under 10MB
  • Verify file format is JPEG, PNG, or WebP
  • Ensure dimensions don't exceed 4000x4000px
  • Confirm card_id is valid UUID

Thumbnails not available

Problem: Requesting a thumbnail size returns the original image

Solutions:

  • Wait a few seconds - thumbnails are generated asynchronously
  • Request the original size if thumbnails aren't critical
  • Poll the card-images endpoint to check if variants are ready

Download endpoint returns JSON error

Problem: Expected image file but got JSON error response

Solutions:

  • Verify image ID exists
  • Check authentication token is valid
  • Ensure image hasn't been soft-deleted
  • Confirm you're using the /download endpoint, not the standard GET endpoint

Duplicate image error

Problem: Cannot upload front/back image because one already exists

Solutions:

  • Delete the existing image first
  • Use PUT/PATCH to update the existing image
  • Change the image_type to the opposite side

Next Steps