AgentDB with Java
Use AgentDB as the database of your Java app. This page shows every call you need, with java.net.http.HttpClient. No libraries. The JDK has no JSON parser, so the example carries a small one; in an application, use Jackson or Gson.
You can copy each block into your own code. Together they form one program that our tests run.
This page is tested in CI: its code runs against a fresh AgentDB on every change.
Server-side only. In Spring Boot, wrap these calls in a service bean and read the key from the environment or a secrets store. Call it from controllers; never from a browser.
#Before you start
- Java 21 or newer.
- 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 final String BASE_URL = Objects.requireNonNullElse(System.getenv("AGENTDB_URL"), "https://app.agentdb.link").replaceAll("/+$", "");
static final String API_KEY = System.getenv("AGENTDB_API_KEY"); // a server-side secret: never in browser code
static final String WORKSPACE = System.getenv("AGENTDB_WORKSPACE"); // ws_...
static final String API = BASE_URL + "/v1/workspaces/" + WORKSPACE;
static final HttpClient HTTP = HttpClient.newHttpClient();
static {
if (API_KEY == null || WORKSPACE == null) throw new IllegalStateException("Set AGENTDB_API_KEY and AGENTDB_WORKSPACE");
}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.
/** An AgentDB error: HTTP status plus the error envelope {code, message, retryable, details}. */
static class AgentDBError extends RuntimeException {
final int status;
final String code;
final boolean retryable;
final Map<String, Object> details;
AgentDBError(int status, Map<String, Object> error) {
super(status + " " + error.getOrDefault("code", "HTTP_ERROR") + ": " + error.getOrDefault("message", ""));
this.status = status;
this.code = (String) error.getOrDefault("code", "HTTP_ERROR");
this.retryable = Boolean.TRUE.equals(error.get("retryable"));
this.details = error.get("details") instanceof Map<?, ?> d ? map(d) : Map.of();
}
}
/**
* 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). Sends json as application/json, or body as raw bytes. Returns the raw response.
*/
static HttpResponse<byte[]> send(String method, String path, Object json, byte[] body, String idempotencyKey)
throws IOException, InterruptedException {
boolean safeToRepeat = method.equals("GET") || idempotencyKey != null;
for (int attempt = 0; ; attempt++) {
long backoff = 500L << attempt;
var request = HttpRequest.newBuilder(URI.create(API + path)).header("Authorization", "Bearer " + API_KEY);
if (json != null) {
request.header("Content-Type", "application/json").method(method, BodyPublishers.ofString(Json.write(json)));
} else if (body != null) {
request.header("Content-Type", "application/octet-stream").method(method, BodyPublishers.ofByteArray(body));
} else {
request.method(method, BodyPublishers.noBody());
}
if (idempotencyKey != null) request.header("Idempotency-Key", idempotencyKey);
HttpResponse<byte[]> res;
try {
res = HTTP.send(request.build(), BodyHandlers.ofByteArray());
} catch (IOException e) {
if (safeToRepeat && attempt < 4) {
Thread.sleep(backoff);
continue;
}
throw e;
}
int status = res.statusCode();
if ((status == 429 || status == 503) && attempt < 4) {
String retryAfter = res.headers().firstValue("Retry-After").orElse("");
long seconds = retryAfter.matches("\\d+") ? Long.parseLong(retryAfter) : 0;
Thread.sleep(seconds > 0 ? seconds * 1000 : backoff + (long) (Math.random() * 250));
continue;
}
if (status < 200 || status > 299) {
Map<String, Object> error = null;
try {
error = map(map(Json.parse(new String(res.body(), UTF_8))).get("error"));
} catch (RuntimeException notJson) {
// no error envelope: keep the defaults
}
throw new AgentDBError(status, error != null ? error : Map.of());
}
return res;
}
}
/** One API call that returns the "data" part of the answer. */
static Map<String, Object> api(String method, String path, Object json, String idempotencyKey)
throws IOException, InterruptedException {
var answer = Json.parse(new String(send(method, path, json, null, idempotencyKey).body(), UTF_8));
return map(map(answer).get("data"));
}
static Map<String, Object> api(String method, String path, Object json) throws IOException, InterruptedException {
return api(method, path, json, null);
}
static Map<String, Object> api(String method, String path) throws IOException, InterruptedException {
return api(method, path, null, null);
}
/** Casts for the parsed JSON: an object is a Map, an array is a List. */
@SuppressWarnings("unchecked")
static Map<String, Object> map(Object value) {
return (Map<String, Object>) value;
}
@SuppressWarnings("unchecked")
static List<Map<String, Object>> list(Object value) {
return (List<Map<String, Object>>) value;
}Check the connection by reading the schema:
var schema = api("GET", "/object-types");
var names = list(schema.get("objects")).stream().map(o -> (String) o.get("name")).toList();
System.out.println("Objects: " + String.join(", ", names));#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 = api("POST", "/records",
Map.of("object", "contact", "data", Map.of("name", "Ada Lovelace", "email", "ada-" + run + "@example.com", "score", 72)),
UUID.randomUUID().toString()); // safe to retry: the same key never writes twice
var adaId = (String) ada.get("id");
System.out.println("Created " + adaId + " version " + ada.get("version"));The Idempotency-Key header makes a retry safe. See Idempotency keys.
#Read a record
var record = api("GET", "/records/" + adaId);
var data = map(record.get("data"));
System.out.println(data.get("name") + " " + data.get("email") + " version " + record.get("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.
Map<String, Object> updated = null;
for (int attempt = 1; updated == null; attempt++) {
var current = api("GET", "/records/" + adaId);
long score = (Long) map(current.get("data")).get("score");
try {
updated = api("PATCH", "/records/" + adaId, Map.of("version", current.get("version"), "data", Map.of("score", score + 10)));
} catch (AgentDBError e) {
if (!e.code.equals("VERSION_CONFLICT") || attempt == 3) throw e;
}
}
System.out.println("Score " + map(updated.get("data")).get("score") + " version " + updated.get("version"));This is what the conflict looks like:
try {
api("PATCH", "/records/" + adaId, Map.of("version", 1, "data", Map.of("score", 0))); // stale version
} catch (AgentDBError e) {
if (!e.code.equals("VERSION_CONFLICT")) throw e;
System.out.println("Conflict: the record is now at version " + e.details.get("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).
var where = Map.of("all", List.of(
Map.of("field", "score", "op", "gte", "value", 70),
Map.of("field", "email", "op", "neq", "value", "nobody@example.com")));
var sort = List.of(Map.of("field", "score", "order", "desc"));
var good = new ArrayList<Map<String, Object>>();
String cursor = null;
do {
var query = new HashMap<String, Object>(Map.of("object", "contact", "where", where, "sort", sort, "limit", 2));
if (cursor != null) query.put("cursor", cursor);
var page = api("POST", "/query", query);
good.addAll(list(page.get("records")));
cursor = (String) page.get("next_cursor"); // null on the last page
} while (cursor != null);
for (var c : good) System.out.println(map(c.get("data")).get("score") + " " + map(c.get("data")).get("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 = api("POST", "/records", Map.of("object", "company", "data", Map.of("name", "Example Ltd " + run)));
var companyId = (String) company.get("id");
api("POST", "/links",
Map.of("relationship", "works_at", "source_record_id", adaId, "target_record_id", companyId),
"link-" + adaId + "-" + companyId);
var related = list(api("GET", "/records/" + adaId + "/related?relationship=works_at").get("records"));
System.out.println("Ada works at " + String.join(", ", related.stream().map(r -> (String) map(r.get("data")).get("name")).toList()));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.
byte[] bytes = ("Meeting notes for Ada (" + run + ")\n").getBytes(UTF_8);
// 1. Announce the file, 2. send the raw bytes, 3. attach it to a record.
var file = api("POST", "/files", Map.of("filename", "notes.txt", "content_type", "text/plain", "size", bytes.length));
var fileId = (String) file.get("id");
send("PUT", "/files/" + fileId + "/content", null, bytes, null);
api("POST", "/attachments", Map.of("file_id", fileId, "record_id", adaId));
// Download with the key (server side) ...
byte[] back = send("GET", "/files/" + fileId + "/content", null, null, null).body();
// ... or make a signed link that expires, for an <img> or a download button in your page.
var link = api("POST", "/files/" + fileId + "/links", Map.of("expires_in_seconds", 600));
System.out.println("Signed link until " + link.get("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 {
api("GET", "/records/rec_doesnotexist");
} catch (AgentDBError e) { // a network error is an IOException, not an AgentDB answer
System.out.println(e.getMessage()); // 404 NOT_FOUND: ...
if (e.retryable) System.out.println("Safe to retry later");
}HttpClient throws IOException 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 = UUID.randomUUID().toString(); // one key per intention; reuse it only to retry the same request
var request = Map.of("object", "contact", "data", Map.of("name", "Mary Somerville", "email", "mary-" + run + "@example.com"));
var first = api("POST", "/records", request, key);
var retry = api("POST", "/records", request, key); // e.g. after a timeout
System.out.println(first.get("id").equals(retry.get("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/java/Crm.java. Set the three environment variables and run:
java Crm.javaIt 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.