๐Ÿ“ฅList, Fetch, and Download Documents

This snippet mirrors the document retrieval recipe using PHP.

<?php

$token = getenv('AUTOCONTENT_TOKEN') ?: 'YOUR_API_TOKEN';
$documentId = getenv('DOCUMENT_ID') ?: 'YOUR_REQUEST_ID';
$baseUrl = 'https://api.autocontentapi.com';

function requestJson(string $url, string $token): string {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $token,
            'Accept: application/json',
        ],
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $response = curl_exec($ch);
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new RuntimeException($error);
    }

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status >= 400) {
        throw new RuntimeException("HTTP $status\n$response");
    }

    return $response;
}

function extensionFromContentType(string $contentType): string {
    if (str_contains($contentType, 'pdf')) return '.pdf';
    if (str_contains($contentType, 'html')) return '.html';
    return '.txt';
}

echo "Documents page:\n";
echo requestJson($baseUrl . '/documents/get?page=1&pageSize=10', $token) . "\n\n";

echo "Single document:\n";
echo requestJson($baseUrl . '/documents/' . $documentId, $token) . "\n\n";

$download = curl_init($baseUrl . '/documents/' . $documentId . '/download');
curl_setopt_array($download, [
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
]);

$response = curl_exec($download);
if ($response === false) {
    $error = curl_error($download);
    curl_close($download);
    throw new RuntimeException($error);
}

$status = curl_getinfo($download, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($download, CURLINFO_HEADER_SIZE);
$contentType = curl_getinfo($download, CURLINFO_CONTENT_TYPE) ?: 'text/plain';
curl_close($download);

if ($status >= 400) {
    fwrite(STDERR, "Download failed: HTTP $status\n" . substr($response, $headerSize) . "\n");
    exit(1);
}

$body = substr($response, $headerSize);
$extension = extensionFromContentType($contentType);
$outputPath = 'briefing-document-' . $documentId . $extension;
file_put_contents($outputPath, $body);

echo "Saved $outputPath\n";

Set YOUR_API_TOKEN (or AUTOCONTENT_TOKEN) and DOCUMENT_ID before running.

See also

Last updated