AgentDB with C# (.NET)
Use AgentDB as the database of your C# (.NET) app. This page shows every call you need, with HttpClient and System.Text.Json. No NuGet packages.
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. In ASP.NET Core, register one HttpClient (for example with IHttpClientFactory) and read the key from configuration or user secrets. Call AgentDB from controllers or minimal-API handlers.
#Before you start
- .NET 8 or newer (the example project targets .NET 9).
- A workspace with the example schema:
contact,companyandworks_at. - Three environment variables on your server:
AGENTDB_URL,AGENTDB_API_KEYandAGENTDB_WORKSPACE. See Environment variables.
#Connect
Read the settings from the environment. The key never appears in the code.
static readonly string BaseUrl = (Environment.GetEnvironmentVariable("AGENTDB_URL") ?? "https://app.agentdb.link").TrimEnd('/');
static readonly string ApiKey = Env("AGENTDB_API_KEY"); // a server-side secret: never in browser code
static readonly string Workspace = Env("AGENTDB_WORKSPACE"); // ws_...
static readonly string ApiUrl = $"{BaseUrl}/v1/workspaces/{Workspace}";
static readonly HttpClient Http = new();
static string Env(string name)
{
var value = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrEmpty(value)) throw new InvalidOperationException("Set AGENTDB_API_KEY and AGENTDB_WORKSPACE");
return value;
}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.
/// <summary>An AgentDB error: HTTP status plus the error envelope {code, message, retryable, details}.</summary>
class AgentDBError(int status, JsonNode? error)
: Exception($"{status} {(string?)error?["code"] ?? "HTTP_ERROR"}: {(string?)error?["message"] ?? ""}")
{
public int Status { get; } = status;
public string Code { get; } = (string?)error?["code"] ?? "HTTP_ERROR";
public bool Retryable { get; } = error?["retryable"]?.GetValueKind() == JsonValueKind.True;
public JsonNode Details { get; } = error?["details"] ?? new JsonObject();
}
/// <summary>
/// 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 raw response; Api() below returns its "data" part.
/// </summary>
static async Task<HttpResponseMessage> Send(string method, string path, object? json = null, byte[]? body = null, string? idempotencyKey = null)
{
var safeToRepeat = method == "GET" || idempotencyKey != null;
for (var attempt = 0; ; attempt++)
{
// A request message can be sent only once, so build a new one for every attempt.
var req = new HttpRequestMessage(new HttpMethod(method), ApiUrl + path);
req.Headers.Add("Authorization", $"Bearer {ApiKey}");
if (json != null) req.Content = new StringContent(JsonSerializer.Serialize(json), Encoding.UTF8, "application/json");
if (body != null)
{
req.Content = new ByteArrayContent(body);
req.Content.Headers.ContentType = new("application/octet-stream");
}
if (idempotencyKey != null) req.Headers.Add("Idempotency-Key", idempotencyKey);
HttpResponseMessage res;
try
{
res = await Http.SendAsync(req);
}
catch (HttpRequestException) when (safeToRepeat && attempt < 4)
{
await Task.Delay(500 * (1 << attempt));
continue;
}
if ((res.StatusCode == HttpStatusCode.TooManyRequests || res.StatusCode == HttpStatusCode.ServiceUnavailable) && attempt < 4)
{
var retryAfter = res.Headers.RetryAfter?.Delta;
await Task.Delay(retryAfter > TimeSpan.Zero ? retryAfter.Value : TimeSpan.FromMilliseconds(500 * (1 << attempt) + Random.Shared.Next(250)));
continue;
}
if (!res.IsSuccessStatusCode)
{
JsonNode? envelope = null;
try { envelope = JsonNode.Parse(await res.Content.ReadAsStringAsync()); } catch (JsonException) { }
throw new AgentDBError((int)res.StatusCode, envelope?["error"]);
}
return res;
}
}
/// <summary>One API call that answers with JSON. Returns the "data" part.</summary>
static async Task<JsonNode> Api(string method, string path, object? json = null, string? idempotencyKey = null)
{
var res = await Send(method, path, json: json, idempotencyKey: idempotencyKey);
return JsonNode.Parse(await res.Content.ReadAsStringAsync())!["data"]!;
}Check the connection by reading the schema:
var schema = await Api("GET", "/object-types");
var objects = schema["objects"]!.AsArray();
Console.WriteLine("Objects: " + string.Join(", ", objects.Select(o => (string)o!["name"]!)));#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.
var ada = await Api("POST", "/records",
new { @object = "contact", data = new { name = "Ada Lovelace", email = $"ada-{run}@example.com", score = 72 } },
idempotencyKey: Guid.NewGuid().ToString()); // safe to retry: the same key never writes twice
var adaId = (string)ada["id"]!;
Console.WriteLine($"Created {adaId} version {ada["version"]}");The Idempotency-Key header makes a retry safe. See Idempotency keys.
#Read a record
var record = await Api("GET", $"/records/{adaId}");
Console.WriteLine($"{record["data"]!["name"]} {record["data"]!["email"]} version {record["version"]}");#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:
// Read, change, write with the current version. On VERSION_CONFLICT: read again and retry.
static async Task<JsonNode> UpdateRecord(string id, Func<JsonNode, object> change, int attempts = 3)
{
for (var i = 1; ; i++)
{
var current = await Api("GET", $"/records/{id}");
try
{
return await Api("PATCH", $"/records/{id}", new { version = (int)current["version"]!, data = change(current["data"]!) });
}
catch (AgentDBError err) when (err.Code == "VERSION_CONFLICT" && i < attempts)
{
// Someone else changed the record: loop to read it again.
}
}
}
var updated = await UpdateRecord(adaId, data => new { score = (int)data["score"]! + 10 });
Console.WriteLine($"Score {updated["data"]!["score"]} version {updated["version"]}");This is what the conflict looks like:
try
{
await Api("PATCH", $"/records/{adaId}", new { version = 1, data = new { score = 0 } }); // stale version
}
catch (AgentDBError err) when (err.Code == "VERSION_CONFLICT")
{
Console.WriteLine($"Conflict: the record is now at version {err.Details["current_version"]}");
}#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.
// Every record that matches, page by page (limit up to 200; follow next_cursor).
static async Task<List<JsonNode>> QueryAll(string obj, object where, object sort, int pageSize = 2)
{
var all = new List<JsonNode>();
string? cursor = null;
do
{
var body = new JsonObject
{
["object"] = obj,
["where"] = JsonSerializer.SerializeToNode(where),
["sort"] = JsonSerializer.SerializeToNode(sort),
["limit"] = pageSize,
};
if (cursor != null) body["cursor"] = cursor;
var page = await Api("POST", "/query", body);
all.AddRange(page["records"]!.AsArray().Select(r => r!));
cursor = (string?)page["next_cursor"]; // null on the last page
} while (cursor != null);
return all;
}
var good = await QueryAll(
"contact",
new { all = new object[] { new { field = "score", op = "gte", value = 70 }, new { field = "email", op = "neq", value = "nobody@example.com" } } },
new[] { new { field = "score", order = "desc" } });
foreach (var c in good) Console.WriteLine($"{c["data"]!["score"]} {c["data"]!["name"]}");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:
var company = await Api("POST", "/records", new { @object = "company", data = new { name = $"Example Ltd {run}" } });
var companyId = (string)company["id"]!;
await Api("POST", "/links",
new { relationship = "works_at", source_record_id = adaId, target_record_id = companyId },
idempotencyKey: $"link-{adaId}-{companyId}");
var related = (await Api("GET", $"/records/{adaId}/related?relationship=works_at"))["records"]!.AsArray();
Console.WriteLine("Ada works at " + string.Join(", ", related.Select(r => (string)r!["data"]!["name"]!)));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.
var bytes = Encoding.UTF8.GetBytes($"Meeting notes for Ada ({run})\n");
// 1. Announce the file, 2. send the raw bytes, 3. attach it to a record.
var file = await Api("POST", "/files", new { filename = "notes.txt", content_type = "text/plain", size = bytes.Length });
var fileId = (string)file["id"]!;
await Send("PUT", $"/files/{fileId}/content", body: bytes);
await Api("POST", "/attachments", new { file_id = fileId, record_id = adaId });
// Download with the key (server side) ...
var download = await Send("GET", $"/files/{fileId}/content");
var back = await download.Content.ReadAsByteArrayAsync();
// ... or make a signed link that expires, for an <img> or a download button in your page.
var link = await Api("POST", $"/files/{fileId}/links", new { expires_in_seconds = 600 });
Console.WriteLine($"Signed link until {link["expires_at"]}");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.
try
{
await Api("GET", "/records/rec_doesnotexist");
}
catch (AgentDBError err) // a network error is an HttpRequestException, not an AgentDB answer
{
Console.WriteLine($"{err.Status} {err.Code} {err.Message}"); // 404 NOT_FOUND ...
if (err.Retryable) Console.WriteLine("Safe to retry later");
}HttpClient throws HttpRequestException on network errors; the helper retries those only when the call is safe to repeat.
Common codes:
| Code | HTTP | What to do |
|---|---|---|
VALIDATION_ERROR, FIELD_TYPE_MISMATCH | 400 | Fix the request; details names the field. |
UNAUTHENTICATED | 401 | Check the key. |
FORBIDDEN | 403 | The key's role or a permission rule does not allow this. |
NOT_FOUND | 404 | Check the id and the workspace. |
VERSION_CONFLICT | 409 | Read again and retry the update. |
RATE_LIMITED | 429 | Wait 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.
var key = Guid.NewGuid().ToString(); // one key per intention; reuse it only to retry the same request
var request = new { @object = "contact", data = new { name = "Mary Somerville", email = $"mary-{run}@example.com" } };
var first = await Api("POST", "/records", request, idempotencyKey: key);
var retry = await Api("POST", "/records", request, idempotencyKey: key); // e.g. after a timeout
Console.WriteLine((string?)first["id"] == (string?)retry["id"] ? "Same record, written once" : "Duplicate!");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/csharp/Program.cs, examples/languages/csharp/Crm.csproj. Set the three environment variables and run:
dotnet runIt 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.