PHP code example of dvids / api-client

1. Go to this page and download the library: Download dvids/api-client 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/ */

    

dvids / api-client example snippets



DvidsApi\DvidsClient;

$client = new DvidsClient();

// Step 1: Create authorization URL
$oauth2Flow = $client->createOAuth2Flow(
    clientId: 'your-client-id',
    redirectUri: 'https://your-app.com/callback',
    scopes: ['basic', 'email', 'upload']
);

// Redirect user to authorization URL
header('Location: ' . $oauth2Flow['authorization_url']);

// Step 2: Handle callback (in your callback handler)
if (isset($_GET['code']) && isset($_GET['state'])) {
    $tokenResponse = $oauth2Flow['exchange_token'](
        code: $_GET['code'],
        clientSecret: 'your-client-secret',
        receivedState: $_GET['state']
    );
    
    // Store these securely
    $accessToken = $tokenResponse['access_token'];
    $refreshToken = $tokenResponse['refresh_token'];
}

// Add your access token from OAuth2 flow (see example below)
$authenticatedClient = $client->withAccessToken('your-access-token');

// Get 5 units matching the name Army
$unitSearchResults = $authenticatedClient->serviceUnits()->searchByName('Army', 5);

if (!empty($unitSearchResults['data'])) {
    // Pick the first one
    $unit = \DvidsApi\Model\ServiceUnit::fromArray($unitSearchResults['data'][0]);
    echo "{$unit->name} ({$unit->abbreviation}) - Branch: {$unit->branch->name}\n";
}

// Simplified workflow - handles batch creation and upload internally
$photo = $authenticatedClient->photos()->createCompletePhotoWorkflowWithServiceUnitVirin(
    '/path/to/photo.jpg',           // imageFilePath
    $unit->id,                      // serviceUnitId
    new DateTimeImmutable('2024-10-01'),     // createdAt
    'Training Exercise',            // title
    'Military training exercise.',  // description
    'Cleared for public release by [email protected].',  // instructions
    ['training', 'military'],       // tags
    [], // authorIds
    'DE' // country code
);

// See https://api.dvidshub.net/docs/dynamic_thumbnails
$thumbnailUrl = str_replace('{thumbnailSpec}', '400w_q95', $photo->thumbnailUrlTemplate);

echo "{$photo->id}: {$thumbnailUrl}\n";

try {
    echo "=== ServiceUnit Client Example ===\n\n";
    
    // 1. Search for service units by name
    echo "1. Searching for service units by name 'Army':\n";
    $searchResults = $authenticatedClient->serviceUnits()->searchByName('Army', 5);
    
    if (!empty($searchResults['data'])) {
        foreach ($searchResults['data'] as $unitData) {
            $unit = \DvidsApi\Model\ServiceUnit::fromArray($unitData);
            echo "  - {$unit->name} ({$unit->abbreviation}) - Branch: {$unit->branch->name}\n";
        }
    } else {
        echo "  No units found\n";
    }
    echo "\n";
    
    // 2. Search by abbreviation
    echo "2. Searching for service units by abbreviation 'USN':\n";
    $abbreviationResults = $authenticatedClient->serviceUnits()->searchByAbbreviation('USN', 3);
    
    if (!empty($abbreviationResults['data'])) {
        foreach ($abbreviationResults['data'] as $unitData) {
            $unit = \DvidsApi\Model\ServiceUnit::fromArray($unitData);
            echo "  - {$unit->name} ({$unit->abbreviation}) - ID: {$unit->id}\n";
        }
    } else {
        echo "  No units found\n";
    }
    echo "\n";
    
    // 3. Search by branch
    echo "3. Searching for service units by branch 'navy':\n";
    $branchResults = $authenticatedClient->serviceUnits()->searchByBranch('navy', 5);
    
    if (!empty($branchResults['data'])) {
        foreach ($branchResults['data'] as $unitData) {
            $unit = \DvidsApi\Model\ServiceUnit::fromArray($unitData);
            echo "  - {$unit->name} ({$unit->abbreviation})\n";
        }
    } else {
        echo "  No units found\n";
    }
    echo "\n";
    
    // 4. Get a specific service unit by ID
    if (!empty($searchResults['data'])) {
        $firstUnitId = $searchResults['data'][0]['id'];
        echo "4. Getting specific service unit by ID '{$firstUnitId}':\n";
        
        $specificUnit = $authenticatedClient->serviceUnits()->getServiceUnit($firstUnitId);
        echo "  - Name: {$specificUnit->name}\n";
        echo "  - Abbreviation: {$specificUnit->abbreviation}\n";
        echo "  - Branch: {$specificUnit->branch->name}\n";
        echo "  - DVIAN: " . ($specificUnit->dvian ?? 'N/A') . "\n";
        echo "  - Requires Publishing Approval: " . ($specificUnit->

// Search for authors
$results = $authenticatedClient->authors()->searchByName('John Smith');

foreach ($results['data'] as $author) {
    echo "Author: {$author->name}\n";
    echo "Vision ID: {$author->visionId}\n";
    
    if ($author->jobGrade) {
        echo "Rank: {$author->jobGrade->name} ({$author->jobGrade->abbreviation})\n";
        echo "Branch: {$author->jobGrade->branch->getDisplayName()}\n";
    }
}

// Get specific author
$author = $authenticatedClient->authors()->getAuthor('author-id');

// Create VIRIN for author
$virin = $authenticatedClient->authors()->createVirin(
    authorId: 'author-id',
    date: new DateTimeImmutable()
);

// Create batch
$batch = $authenticatedClient->batches()->createBatch();

// Create batch upload and upload file in one step
$uploadResult = $authenticatedClient->batches()->createAndUploadFile(
    batchId: $batch->id,
    filePath: '/path/to/photo.jpg',
    contentType: 'image/jpeg'
);

$batchUploadId = $uploadResult['batch_upload']->id;

// Get available graphic categories
$categories = $authenticatedClient->graphics()->getGraphicCategories();

// Create a batch and upload a graphic file
$batch = $authenticatedClient->batches()->createBatch();
$uploadResult = $authenticatedClient->batches()->createAndUploadFile($batch->id, '/path/to/design.png', 'image/png');

// Create graphic with metadata
$graphic = $authenticatedClient->graphics()->createSimpleGraphic(
    batchId: $batch->id,
    title: 'Military Infographic',
    description: 'Educational infographic about procedures',
    instructions: 'Cleared for public release',
    createdAt: new DateTimeImmutable(),
    virin: '241001-A-AB123-1001',
    country: 'US',
    batchUploadId: $uploadResult['batch_upload']->id,
    categoryId: $categories['data'][0]['id'],
    serviceUnitId: 'service-unit-id',
    tags: ['education', 'procedures']
);

echo "Created graphic: {$graphic->title} (Status: {$graphic->status?->getDisplayName()})";

// Search for available publications
$publications = $authenticatedClient->publications()->searchByTitle('Engineer Magazine');

// Create a batch and upload PDF with publication issue in one step
$batch = $authenticatedClient->batches()->createBatch();
$result = $authenticatedClient->publications()->createPublicationIssueWithUpload(
    batchId: $batch->id,
    pdfFilePath: '/path/to/issue.pdf',
    description: 'October 2024 Engineering Publication',
    createdAt: new DateTimeImmutable(),
    publicationId: $publications['data'][0]->id,
    batchClient: $authenticatedClient->batches()
);

$publicationIssue = $result['publication_issue'];
echo "Created publication issue: {$publicationIssue->description}";

new DvidsClient(
    string $baseUrl = 'https://submitapi.dvidshub.net',
    ?string $accessToken = null,
    array $defaultHeaders = [],
    int $timeout = 30,
    bool $verifySSL = true
)

use DvidsApi\Exception\{
    ApiException,
    BadRequestException,
    UnauthorizedException,
    AuthenticationException,
    NotFoundException,
    ConflictException
};

try {
    $author = $client->authors()->getAuthor('non-existent-id');
} catch (NotFoundException $e) {
    echo "Author not found: {$e->getMessage()}";
} catch (UnauthorizedException $e) {
    echo "Authentication 

$client = new DvidsClient(
    baseUrl: 'https://custom-api.example.com',
    accessToken: 'token',
    defaultHeaders: ['X-Custom-Header' => 'value'],
    timeout: 60,
    verifySSL: false
);

$apiClient = $client->getApiClient();
$response = $apiClient->get('/author', ['name' => 'John']);

// Create models programmatically
$author = new Author(
    id: 'author-123',
    name: 'John Smith',
    visionId: 'AB123',
    jobGrade: new JobGrade(
        name: 'Captain',
        associatedPressName: 'Capt.',
        abbreviation: 'CPT',
        branch: Branch::ARMY
    )
);

// Convert to array for API requests
$data = $author->toArray();

// Parse from API responses
$author = Author::fromArray($apiResponse['data']);