AgentDBDocs

AgentDB with PHP

Use AgentDB as the database of your PHP app. This page shows every call you need, with PHP's built-in curl extension. No Composer packages. With Guzzle, the calls look the same: one function, the same headers.

You can copy each block into your own code. Together they form one program that our tests run.

This page is tested: its code runs locally and in CI against a fresh AgentDB on every change.

Server-side only. This code runs on your server. In Laravel or Symfony, read the key with env() or the secrets vault, and call AgentDB from a controller or a service class. Never print the key into a Blade or Twig template.

#Before you start

  • PHP 8.1 or newer with the curl extension (enabled on almost every host).
  • A workspace with the example schema: contact, company and works_at.
  • Three environment variables on your server: AGENTDB_URL, AGENTDB_API_KEY and AGENTDB_WORKSPACE. See Environment variables.

#Connect

Read the settings from the environment. The key never appears in the code.

PHPexamples/languages/php/crm.php
$baseUrl = rtrim(getenv('AGENTDB_URL') ?: 'https://app.agentdb.link', '/');
$apiKey = getenv('AGENTDB_API_KEY');      // a server-side secret: never in browser code
$workspace = getenv('AGENTDB_WORKSPACE'); // ws_...
if (!$apiKey || !$workspace) {
    fwrite(STDERR, "Set AGENTDB_API_KEY and AGENTDB_WORKSPACE\n");
    exit(1);
}
define('AGENTDB_API', "$baseUrl/v1/workspaces/$workspace");
define('AGENTDB_KEY', $apiKey);

Every call goes through one small helper. It sends the key in the Authorization: Bearer header, turns AgentDB errors into one error type, and retries when that is safe.

PHPexamples/languages/php/crm.php
/** An AgentDB error: HTTP status plus the error envelope {code, message, retryable, details}. */
final class AgentDBError extends RuntimeException
{
    public function __construct(
        public readonly int $status,
        public readonly string $errorCode,
        string $message,
        public readonly bool $retryable,
        public readonly array $details,
    ) {
        parent::__construct("$status $errorCode: $message");
    }
}

/**
 * One API call. Sends the key in the Authorization header. Retries 429 and 503 with Retry-After
 * (or exponential backoff), and network errors when the call is safe to repeat (GET, or a write
 * with an Idempotency-Key). Returns the "data" part of the answer, or the raw body.
 */
function api(string $method, string $path, ?array $json = null, ?string $body = null, ?string $idempotencyKey = null, bool $raw = false): mixed
{
    $headers = ['Authorization: Bearer ' . AGENTDB_KEY];
    $payload = null;
    if ($json !== null) {
        $headers[] = 'Content-Type: application/json';
        $payload = json_encode($json, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
    }
    if ($body !== null) {
        $headers[] = 'Content-Type: application/octet-stream';
        $payload = $body;
    }
    if ($idempotencyKey !== null) {
        $headers[] = "Idempotency-Key: $idempotencyKey";
    }
    $safeToRepeat = $method === 'GET' || $idempotencyKey !== null;
    for ($attempt = 0; ; $attempt++) {
        $retryAfter = null;
        $ch = curl_init(AGENTDB_API . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$retryAfter): int {
                if (stripos($line, 'retry-after:') === 0) {
                    $retryAfter = (int) trim(substr($line, 12));
                }
                return strlen($line);
            },
        ]);
        if ($payload !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        }
        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $networkError = curl_error($ch);
        unset($ch);
        if ($response === false) {
            if ($safeToRepeat && $attempt < 4) {
                usleep(500_000 * 2 ** $attempt);
                continue;
            }
            throw new RuntimeException("Network error: $networkError");
        }
        if (($status === 429 || $status === 503) && $attempt < 4) {
            usleep($retryAfter ? $retryAfter * 1_000_000 : 500_000 * 2 ** $attempt + random_int(0, 250_000));
            continue;
        }
        if ($status >= 400) {
            $error = json_decode((string) $response, true)['error'] ?? [];
            throw new AgentDBError($status, $error['code'] ?? 'HTTP_ERROR', $error['message'] ?? '', ($error['retryable'] ?? false) === true, $error['details'] ?? []);
        }
        return $raw ? $response : json_decode($response, true, 512, JSON_THROW_ON_ERROR)['data'];
    }
}

/** A random UUID (v4) for Idempotency-Key headers. */
function uuid(): string
{
    $b = random_bytes(16);
    $b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
    $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}

Check the connection by reading the schema:

PHPexamples/languages/php/crm.php
$schema = api('GET', '/object-types');
echo 'Objects: ', implode(', ', array_column($schema['objects'], 'name')), "\n";

#Create a record

Send the object name and the field values. AgentDB checks each value against its field type. The answer holds the new record with its id and version 1.

PHPexamples/languages/php/crm.php
$ada = api('POST', '/records',
    json: ['object' => 'contact', 'data' => ['name' => 'Ada Lovelace', 'email' => "ada-$run@example.com", 'score' => 72]],
    idempotencyKey: uuid(), // safe to retry: the same key never writes twice
);
echo "Created {$ada['id']} version {$ada['version']}\n";

The Idempotency-Key header makes a retry safe. See Idempotency keys.

#Read a record

PHPexamples/languages/php/crm.php
$record = api('GET', "/records/{$ada['id']}");
echo "{$record['data']['name']} {$record['data']['email']} version {$record['version']}\n";

#Update a record

An update names the version you read. If someone changed the record since then, AgentDB refuses with VERSION_CONFLICT (HTTP 409) and writes nothing. Read it again, apply your change, and try again:

PHPexamples/languages/php/crm.php
/** Read, change, write with the current version. On VERSION_CONFLICT: read again and retry. */
function updateRecord(string $id, callable $change, int $attempts = 3): array
{
    for ($i = 1; ; $i++) {
        $current = api('GET', "/records/$id");
        try {
            return api('PATCH', "/records/$id", json: ['version' => $current['version'], 'data' => $change($current['data'])]);
        } catch (AgentDBError $e) {
            if ($e->errorCode === 'VERSION_CONFLICT' && $i < $attempts) {
                continue;
            }
            throw $e;
        }
    }
}

$updated = updateRecord($ada['id'], fn (array $data) => ['score' => $data['score'] + 10]);
echo "Score {$updated['data']['score']} version {$updated['version']}\n";

This is what the conflict looks like:

PHPexamples/languages/php/crm.php
try {
    api('PATCH', "/records/{$ada['id']}", json: ['version' => 1, 'data' => ['score' => 0]]); // stale version
} catch (AgentDBError $e) {
    if ($e->errorCode !== 'VERSION_CONFLICT') {
        throw $e;
    }
    echo "Conflict: the record is now at version {$e->details['current_version']}\n";
}

#Query with filters, sort and pages

A query takes an object, a where filter, a sort and a limit (at most 200). Every condition in all must match. Use the in operator for "one of several values". Operators: eq, neq, in, lt, lte, gt, gte, is_null, is_not_null.

When more records match, the answer holds a next_cursor. Send it as cursor with the same query to get the next page. A next_cursor of null means you have them all.

PHPexamples/languages/php/crm.php
/** Every record that matches, page by page (limit up to 200; follow next_cursor). */
function queryAll(string $object, array $where, array $sort, int $pageSize = 2): array
{
    $out = [];
    $cursor = null;
    do {
        $body = ['object' => $object, 'where' => $where, 'sort' => $sort, 'limit' => $pageSize];
        if ($cursor !== null) {
            $body['cursor'] = $cursor;
        }
        $page = api('POST', '/query', json: $body);
        array_push($out, ...$page['records']);
        $cursor = $page['next_cursor']; // null on the last page
    } while ($cursor !== null);
    return $out;
}

$good = queryAll('contact',
    ['all' => [['field' => 'score', 'op' => 'gte', 'value' => 70], ['field' => 'email', 'op' => 'neq', 'value' => 'nobody@example.com']]],
    [['field' => 'score', 'order' => 'desc']],
);
foreach ($good as $c) {
    echo "{$c['data']['score']} {$c['data']['name']}\n";
}

See Querying for text search, totals and saved views.

#Link records

A relationship type such as works_at links a contact to a company. Create a link, then list the records on the other side:

PHPexamples/languages/php/crm.php
$company = api('POST', '/records', json: ['object' => 'company', 'data' => ['name' => "Example Ltd $run"]]);
api('POST', '/links',
    json: ['relationship' => 'works_at', 'source_record_id' => $ada['id'], 'target_record_id' => $company['id']],
    idempotencyKey: "link-{$ada['id']}-{$company['id']}",
);
$related = api('GET', "/records/{$ada['id']}/related?relationship=works_at");
echo 'Ada works at ', implode(', ', array_map(fn ($r) => $r['data']['name'], $related['records'])), "\n";

Add direction=incoming to list from the other side, for example all contacts of a company.

#Files

A file upload has three steps: announce the file with its name, type and size; send the raw bytes; attach it to a record. AgentDB checks that the bytes match the type.

PHPexamples/languages/php/crm.php
$bytes = "Meeting notes for Ada ($run)\n";
// 1. Announce the file, 2. send the raw bytes, 3. attach it to a record.
$file = api('POST', '/files', json: ['filename' => 'notes.txt', 'content_type' => 'text/plain', 'size' => strlen($bytes)]);
api('PUT', "/files/{$file['id']}/content", body: $bytes);
api('POST', '/attachments', json: ['file_id' => $file['id'], 'record_id' => $ada['id']]);
// Download with the key (server side) ...
$back = api('GET', "/files/{$file['id']}/content", raw: true);
// ... or make a signed link that expires, for an <img> or a download button in your page.
$link = api('POST', "/files/{$file['id']}/links", json: ['expires_in_seconds' => 600]);
echo "Signed link until {$link['expires_at']}\n";

To show a file in a browser, give the page the signed link, never your key. The link expires and can be revoked. See Files and imports.

#Errors

Every error has a stable code, a message, a retryable flag and details, plus an HTTP status. Act on the code.

PHPexamples/languages/php/crm.php
try {
    api('GET', '/records/rec_doesnotexist');
} catch (AgentDBError $e) { // a network error throws RuntimeException instead
    echo "{$e->status} {$e->errorCode} {$e->getMessage()}\n"; // 404 NOT_FOUND ...
    if ($e->retryable) {
        echo "Safe to retry later\n";
    }
}

curl_exec returns false on network errors; the helper retries those only when the call is safe to repeat.

Common codes:

CodeHTTPWhat to do
VALIDATION_ERROR, FIELD_TYPE_MISMATCH400Fix the request; details names the field.
UNAUTHENTICATED401Check the key.
FORBIDDEN403The key's role or a permission rule does not allow this.
NOT_FOUND404Check the id and the workspace.
VERSION_CONFLICT409Read again and retry the update.
RATE_LIMITED429Wait for Retry-After, then retry.

The error codes page lists them all.

#Rate limits and retries

AgentDB limits how many requests a key and a workspace may send. Over the limit, it answers 429 RATE_LIMITED with a Retry-After header in seconds.

The request helper above already handles this:

  • On 429 or 503, it waits for Retry-After, or backs off (0.5, 1, 2, 4 seconds), then tries again.
  • On a network error, it retries only reads and writes with an idempotency key.
  • It gives up after a few attempts and reports the error.

To load many records, use one batch call instead of one call per record: POST /records/upsert takes up to 500 items. See records_upsert_batch.

#Idempotency keys

A timeout can leave you unsure whether a write happened. Send an Idempotency-Key header with each write you may retry. If the same key comes again with the same request, AgentDB returns the first result and writes nothing twice. Keys are kept for 7 days.

PHPexamples/languages/php/crm.php
$key = uuid(); // one key per intention; reuse it only to retry the same request
$request = ['object' => 'contact', 'data' => ['name' => 'Mary Somerville', 'email' => "mary-$run@example.com"]];
$first = api('POST', '/records', json: $request, idempotencyKey: $key);
$retry = api('POST', '/records', json: $request, idempotencyKey: $key); // e.g. after a timeout
echo $first['id'] === $retry['id'] ? "Same record, written once\n" : "Duplicate!\n";

Use a new key for each new intention, such as each form submission. The same key with a different request fails with IDEMPOTENCY_KEY_REUSED.

#Run the full example

The complete program is examples/languages/php/crm.php. Set the three environment variables and run:

Shell
php crm.php

It prints one OK line per topic: OK connect, OK create, OK read, OK update, OK query, OK relationships, OK files, OK errors and OK idempotency.