PHP code example of cardtechie / tradingcardapi-sdk-php

1. Go to this page and download the library: Download cardtechie/tradingcardapi-sdk-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cardtechie / tradingcardapi-sdk-php example snippets


use CardTechie\TradingCardApiSdk\Facades\TradingCardApiSdk;

// Get a specific card
$card = TradingCardApiSdk::card()->get('card-id');

// Search for cards
$cards = TradingCardApiSdk::card()->list(['name' => 'Pikachu']);

// Get player information
$player = TradingCardApiSdk::player()->get('player-id');

// Get paginated list of players
$players = TradingCardApiSdk::player()->list(['limit' => 25, 'page' => 1]);

// Search for players (returns Collection)
$players = TradingCardApiSdk::player()->all(['full_name' => 'Michael Jordan']);

// Get a set with related data
$set = tradingcardapi()->set()->get('set-id', [' 'New Team',
    'location' => 'City Name'
]);

use CardTechie\TradingCardApiSdk\Exceptions\{
    CardNotFoundException,
    ConflictException,
    ValidationException,
    RateLimitException,
    AuthenticationException
};

try {
    $card = TradingCardApiSdk::card()->get('invalid-id');
} catch (CardNotFoundException $e) {
    // Handle missing card
    echo "Card not found: " . $e->getMessage();
} catch (ConflictException $e) {
    // Handle duplicate resource (HTTP 409)
    echo "Conflict: " . $e->getMessage();
} catch (ValidationException $e) {
    // Handle validation errors
    foreach ($e->getValidationErrors() as $field => $errors) {
        echo "Field $field: " . implode(', ', $errors);
    }
} catch (RateLimitException $e) {
    // Handle rate limiting
    echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds";
}

use CardTechie\TradingCardApiSdk\TradingCardApi;

$api = new TradingCardApi();
$genres = $api->genre()->list();

$cards = TradingCardApi::card()->list();

$cards->getMeta()->total;        // e.g. 1500
$cards->getLinks()->next;        // e.g. https://api.example.com/cards?page=2

$player = $cards->getRelationships()['players'][0];
(array) $player->getMeta();       // []  — empty by design

use CardTechie\TradingCardApiSdk\Facades\TradingCardApiSdk;

// Get a specific player
$player = TradingCardApiSdk::player()->get('player-id');

// Create a new player
$player = TradingCardApiSdk::player()->create([
    'first_name' => 'Michael',
    'last_name' => 'Jordan'
]);

// Update player information
$player = TradingCardApiSdk::player()->update('player-id', [
    'first_name' => 'Michael Jeffrey',
    'last_name' => 'Jordan'
]);

// Delete a player
TradingCardApiSdk::player()->delete('player-id');

// Get paginated list of players
$players = TradingCardApiSdk::player()->list([
    'limit' => 50,
    'page' => 1,
    'sort' => 'last_name'
]);

// Search for players (returns Collection)
$players = TradingCardApiSdk::player()->all([
    'full_name' => 'Michael Jordan',
    'parent_id' => null  // Only parent players, not aliases
]);

// Find players by partial name
$players = TradingCardApiSdk::player()->all([
    'first_name' => 'Michael'
]);

// Working with player relationships
$player = TradingCardApiSdk::player()->get('player-id');

// Get parent player (if this is an alias)
$parent = $player->getParent();

// Get all aliases of this player
$aliases = $player->getAliases();

// Get teams this player has been associated with
$teams = $player->getTeams();

// Get all player-team relationships
$playerteams = $player->getPlayerteams();

// Check if player is an alias
if ($player->isAlias()) {
    echo "This is an alias of: " . $player->getParent()->full_name;
}

// Check if player has aliases
if ($player->hasAliases()) {
    echo "This player has " . $player->getAliases()->count() . " aliases";
}

// Create a parent player
$parent = TradingCardApiSdk::player()->create([
    'first_name' => 'Michael',
    'last_name' => 'Jordan'
]);

// Create an alias player with parent relationship
$alias = TradingCardApiSdk::player()->create(
    ['first_name' => 'Mike', 'last_name' => 'Jordan'],
    ['parent' => ['data' => ['type' => 'players', 'id' => $parent->id]]]
);

// List deleted players
$deletedPlayers = TradingCardApiSdk::player()->listDeleted();

// Get a specific deleted player
$deletedPlayer = TradingCardApiSdk::player()->deleted('player-id');

$player = TradingCardApiSdk::player()->get('player-id');

// Access player data
echo $player->first_name;        // "Michael"
echo $player->last_name;         // "Jordan"
echo $player->full_name;         // "Michael Jordan" (computed attribute)
echo $player->last_name_first;   // "Jordan, Michael" (computed attribute)

// Check relationships
echo $player->parent_id;         // UUID of parent player (if alias)

$set = tradingcardapi()->set()->get('set-id');

echo $set->name;   // "2023 Topps Chrome Black Refractor /99"
echo $set->serial; // 99

// Get current counts for all entity types
$counts = $api->stats()->getCounts();

// Access counts for a specific entity type
$setsCount = $counts->getByEntityType('sets');
echo $setsCount->total;      // Total count
echo $setsCount->published;  // Published count
echo $setsCount->draft;      // Draft count
echo $setsCount->archived;   // Archived count

// Get growth metrics (default: 7 days)
$growth = $api->stats()->getGrowth();
// Or specify a period: '7d', '30d', '90d', 'week', 'month'
$growth = $api->stats()->getGrowth('30d');

$setsGrowth = $growth->getByEntityType('sets');
echo $setsGrowth->current;          // Current count
echo $setsGrowth->previous;         // Previous period count
echo $setsGrowth->change;           // Absolute change
echo $setsGrowth->percentageChange; // Percentage change

// Get historical snapshots
$snapshots = $api->stats()->getSnapshots();

// With filters
$snapshots = $api->stats()->getSnapshots([
    'entity_type' => 'sets',
    'from' => '2024-11-01',
    'to' => '2024-11-30',
]);

foreach ($snapshots->snapshots as $snapshot) {
    echo $snapshot->date;        // Snapshot date
    echo $snapshot->entityType;  // Entity type
    echo $snapshot->total;       // Total at that point
}

// Get all sources for a specific set
$sources = $api->setSource()->forSet('set-id');

// Get a specific source
$source = $api->setSource()->get('source-id');

// Create a new set source
$source = $api->setSource()->create([
    'set_id' => 'set-uuid',
    'source_url' => 'https://example.com/checklist',
    'source_name' => 'Example Source',
    'source_type' => 'checklist',  // checklist, metadata, or images
]);

// Update a source
$source = $api->setSource()->update('source-id', [
    'source_url' => 'https://example.com/updated-checklist',
    'verified_at' => '2024-01-15T10:30:00Z',
]);

// Delete a source
$api->setSource()->delete('source-id');

// Include sources when fetching a set
$set = $api->set()->get('set-id', ['

$internal = $api->internal();

// workflow and audit-log resources are now under internal()
$actionable = $internal->workflow()->actionableSets();
$logs       = $internal->auditLog()->getAuditLogs();

$workflow = $api->internal()->workflow();

// Get sets that have actionable workflow steps
// Returns a typed ActionableSetsResponse (->sets is an array of ActionableSet)
$actionable = $workflow->actionableSets();
foreach ($actionable->sets as $set) {
    echo $set->attributes->name;
}

// Filter actionable sets
$actionable = $workflow->actionableSets(['filter[sport]' => 'baseball']);

// Get workflow status for a specific set (via Set resource — still public)
$workflowStatus = $api->set()->workflow('set-id');

// Update a workflow step (set-todo) status
$result = $workflow->updateSetTodo('todo-id', [
    'status' => 'completed',
]);

// Bulk initialize workflow todos for all existing sets
$job = $workflow->bulkInitializeWorkflow();
echo $job->data->job_id;   // Job ID to poll for status
echo $job->data->status;   // 'queued'

// Initialize workflow todos for specific sets only
$job = $workflow->bulkInitializeWorkflow([
    'set_ids' => ['set-id-1', 'set-id-2'],
]);

// Poll bulk initialization job status
$status = $workflow->getBulkInitializeStatus($job->data->job_id);
echo $status->data->status;     // 'queued', 'processing', or 'completed'
echo $status->data->processed;  // Sets processed so far
echo $status->data->total;      // Total sets to process

// Get workflow todos for a specific set
$result = $workflow->getSetTodos('set-id');
foreach ($result->todos as $todo) {
    echo $todo->step;    // e.g. 'discover_sources'
    echo $todo->status;  // e.g. 'completed'
}

// Get all sets blocked for human review
$reviewQueue = $workflow->getReviewQueue();

// Filter review queue by workflow step
$parseReview = $workflow->getReviewQueue('parse');

// Flag a workflow step for human review
$workflow->flagForReview('todo-id', 'Data quality issue detected');

// Resolve a review (resets to pending)
$workflow->resolveReview('todo-id');
$workflow->resolveReview('todo-id', 'Verified card data is correct');

// Use WorkflowStatus and WorkflowStep enums instead of magic strings
$workflow->updateSetTodo('todo-id', [
    'status' => \CardTechie\TradingCardApiSdk\Enums\WorkflowStatus::COMPLETED->value,
]);

$auditLog = $api->internal()->auditLog();

// Get audit logs with pagination
$logs = $auditLog->getAuditLogs();

// Filter audit logs
$logs = $auditLog->getAuditLogs([
    'auditable_type' => 'Set',
    'auditable_id' => 'set-uuid',
    'agent_id' => 'agent-uuid',
    'event_type' => 'created',
    'start_date' => '2026-01-01',
    'end_date' => '2026-04-13',
    'per_page' => 25,
    'page' => 1,
]);

// Create an audit event
$event = $auditLog->createAuditEvent([
    'auditable_type' => 'Set',
    'auditable_id' => 'set-uuid',
    'event_type' => 'manual_review',
    'description' => 'Manual review completed',
]);

// Upload a card image
$image = $api->cardImage()->upload(
    $request->file('image'),  // UploadedFile or file path
    'card-id',
    'front'  // 'front' or 'back'
);

// Upload with additional attributes
$image = $api->cardImage()->upload(
    '/path/to/image.jpg',
    'card-id',
    'front',
    ['is_primary' => true]
);

// Get a card image
$image = $api->cardImage()->get('image-id');

// Get download URL
$url = $api->cardImage()->getDownloadUrl('image-id');           // original size
$url = $api->cardImage()->getDownloadUrl('image-id', 'small');  // small variant

// Update image metadata
$image = $api->cardImage()->update('image-id', ['is_primary' => true]);

// List card images with filtering
$images = $api->cardImage()->list(['filter[card_id]' => 'card-id']);

// Delete a card image
$api->cardImage()->delete('image-id');

return [
    'url' => env('TRADINGCARDAPI_URL', ''),
    'ssl_verify' => (bool) env('TRADINGCARDAPI_SSL_VERIFY', true),
    'client_id' => env('TRADINGCARDAPI_CLIENT_ID', ''),
    'client_secret' => env('TRADINGCARDAPI_CLIENT_SECRET', ''),
    'scope' => env('TRADINGCARDAPI_SCOPE', 'read:published'),
    'timeout' => (float) env('TRADINGCARDAPI_TIMEOUT', 10),
    'connect_timeout' => (float) env('TRADINGCARDAPI_CONNECT_TIMEOUT', 5),
    'retry' => [
        'enabled' => (bool) env('TRADINGCARDAPI_RETRY_ENABLED', false),
        'max_attempts' => (int) env('TRADINGCARDAPI_RETRY_MAX_ATTEMPTS', 3),
        'base_delay' => (int) env('TRADINGCARDAPI_RETRY_BASE_DELAY_MS', 1000),
    ],
];
bash
composer 
bash
php artisan vendor:publish --tag="tradingcardapi-config"