# Specimen API guide

Use a personal access token to work with your FossilVault collection from a script, an agent, or a server-side integration. You can list your specimens and read each one in full, with its taxonomy, measurements, notes, and images. With the optional write permission, you can also add specimens and add images to them.

API **v1** · Guide **1.0.1** · Updated **2026-11-27**

[OpenAPI 3.1 (JSON)](./openapi.json) · [Plain Markdown](./guide.md)

## Overview

The base URL is `https://api.fossilvault.app/v1`. Every endpoint requires HTTPS and returns JSON. Your token decides which collection you work with. Reads include private, public, and disposed specimens (sold, traded, gifted, or lost).

| Operation | Path | Use it to |
| --- | --- | --- |
| List specimens | `GET /v1/specimens` | Read one page of compact summaries. |
| Get a specimen | `GET /v1/specimens/{specimenId}` | Read one of your specimens by the ID a list returned. |
| Create a specimen | `POST /v1/specimens` | Add one private specimen without images. Needs `specimens:write`. |
| Add an image | `POST /v1/specimens/{specimenId}/images` | Add one image to one of your specimens. Needs `specimens:write`. |

Updates, image removal, and deletes are not available through the API. The [OpenAPI document](./openapi.json) describes every field, nested type, and enum, with examples for all four specimen categories.

## Authentication

### Create a token

Create a token in the FossilVault app for iOS or Android under **Settings → Account → API Tokens**, signed in with a registered account. Free accounts can create one. The screen appears only in app releases that include token management.

Name the token for its integration, choose its permissions and lifetime, then copy the token before you close the creation screen.

### Permissions

| Permission | Grants |
| --- | --- |
| `specimens:read` | Required. Read summaries and specimen records, including notes, locality, and image URLs. |
| `specimens:read:financial` | Optional, off by default. Adds the financial fields to specimen records. Lists are the same with or without it. |
| `specimens:write` | Optional, off by default. Create specimens and add images to any of your specimens. Never edits or deletes existing data. |

> **Note:** Write permission needs an app release that requests `specimens:write`. Earlier releases request an older `specimens:create` permission, which the API rejects, so the token is not created. A token created with `specimens:create` before 2026-11-23 returns `401` on every request; create a new one.

### Token lifetime and limits

- A token lasts 3 (the default), 6, or 12 calendar months.
- The Free plan allows one active token. Pro, Max, and Lifetime allow five.
- A token’s name, permissions, and expiration are fixed when you create it.
- To rotate a token, create the replacement, then revoke the old one. If you are at your plan’s token limit, revoke a token first.

### Send the token

Send `Authorization: Bearer <token>` on every request.

- Keep the token in a server-side secret store or in a file only you can read.
- Keep it out of URLs, browser code, verbose HTTP traces, logs, and agent transcripts.
- Send requests directly to the API with redirects disabled.
- Send no other credentials. A request that also carries a `Cookie` or `X-Firebase-AppCheck` header is rejected with `401`.
- Use HTTPS. A plain HTTP request is rejected with `400`.

The API supports neither cross-origin browser requests nor conditional GET.

### Revoke a token

Revoke a token in the app under **Settings → Account → API Tokens**. Revocation blocks every later request with that token. Signing out, resetting your password, or ending a login session does not revoke your tokens, so revoke a lost token explicitly.

> **Warning:** An image URL the API has already returned can keep working after the token expires or is revoked. Protect exported records and image URLs as carefully as the token.

## First request

Save the token once, in a file only you can read. Run this, paste the token, press Return, then press Ctrl-D:

```sh Save the token
mkdir -p "$HOME/.config/fossilvault"
(umask 077 && cat > "$HOME/.config/fossilvault/token")
```

Then run this in a shell with curl and jq. It defines an `fv_auth` helper that passes the token to curl through standard input, so the token never appears in the command line. The request asks for one summary.

```sh List one specimen
export FV_TOKEN_FILE="$HOME/.config/fossilvault/token"
fv_auth() {
  printf 'Authorization: Bearer %s\n' "$(cat "$FV_TOKEN_FILE")"
}
fv_auth | curl --silent --show-error --fail-with-body --header @- \
  'https://api.fossilvault.app/v1/specimens?limit=1' \
  | jq 'if has("specimens") then (.specimens | length) else error(.code) end'
```

It prints `1`, or `0` if your collection is empty. On an error, jq reports the error `code`, such as `unauthorized`.

## List specimens

`GET /v1/specimens`

| Query parameter | Type | Behavior |
| --- | --- | --- |
| `limit` | Optional integer | 1–100, default 50. Send decimal digits without leading zeros. |
| `cursor` | Optional string | The `nextCursor` of the previous page. Omit it on the first request. |

Send each parameter at most once. Any other parameter, including filters and sort options, returns `400 invalid_request`. Errors follow the [common errors](#errors-and-retries), and every page counts against the [rate limits](#rate-limits).

Every summary has `id`, `createdAt`, and `category`. It may also have your `catalogNumber` and `specimenName`, the custom name you gave the specimen. Fossils have `fossils`. Materials (minerals, gemstones, and rocks) use the categories `mineral`, `gemstone`, and `rock`, with an optional `materialName`. A final page with one fossil and one mineral might look like this:

```json Response body
{
  "specimens": [
    {
      "id": "example-4-fossil",
      "createdAt": "2026-01-02T03:04:05.123456789Z",
      "category": "fossil",
      "catalogNumber": "FV-42",
      "fossils": [
        {
          "scientificName": "Otodus sp.",
          "descriptiveName": "Shark tooth"
        }
      ]
    },
    {
      "id": "example-3-mineral",
      "createdAt": "2026-01-01T10:00:00Z",
      "category": "mineral",
      "specimenName": "Arkansas cathedral cluster",
      "materialName": "Quartz"
    }
  ],
  "nextCursor": null,
  "hasMore": false
}
```

Fossil summaries keep the order of `fossils`. Each entry can have a `scientificName` and a `descriptiveName` you assigned; both are optional, so an unidentified, unnamed fossil is `{}`. The scientific name follows the FossilVault app: a species with its genus (`Otodus megalodon`), a genus alone with `sp.` (`Otodus sp.`), otherwise the most specific named rank. Names containing “unknown” are omitted. Lists always include descriptive names. Fossil IDs and the full taxonomy are only in the [specimen record](#get-a-specimen).

## Pagination

Results are sorted by `createdAt`, then by specimen ID, both descending. Continue while `nextCursor` has a value. The last page has `hasMore: false` and `nextCursor: null`. An empty collection returns an empty `specimens` array.

- A page can hold fewer items than `limit`, because responses are limited to 2 MiB. That alone does not mean it is the last page.
- Send the cursor back exactly as you received it, URL-encoded as a query value.
- Use the same `limit` on every page: a cursor works only with the page size it was issued for.
- A cursor lasts 24 hours. Another valid token for the same account can continue with it.
- On `400 invalid_cursor`, start again without a cursor.
- For an export, deduplicate by specimen ID. New records can appear ahead of your cursor, and changing a record’s date can move it between pages.

> **Note:** Records without a creation date are left out of lists, so an export through the API does not include them.

This Node.js 22 example counts your specimens without logging any records. Save it as `count.mjs`, set `FV_TOKEN_FILE` as in the [first request](#first-request), and run `node count.mjs`. It stops on a failed request and reports the server’s retry delay when there is one.

```js Count specimens
import { readFile } from "node:fs/promises";

const token = (await readFile(process.env.FV_TOKEN_FILE, "utf8")).trim();
let cursor = null;
let count = 0;
do {
  const url = new URL("https://api.fossilvault.app/v1/specimens");
  url.searchParams.set("limit", "50");
  if (cursor) url.searchParams.set("cursor", cursor);
  const response = await fetch(url, {
    headers: { Authorization: `Bearer ${token}` },
    redirect: "error",
    signal: AbortSignal.timeout(35_000),
  });
  if (!response.ok) {
    const delay = response.headers.get("Retry-After");
    throw new Error(`HTTP ${response.status}${delay ? `; retry after ${delay}s` : ""}`);
  }
  const page = await response.json();
  count += page.specimens.length;
  cursor = page.nextCursor;
} while (cursor !== null);
console.log(count);
```

The 35-second timeout leaves room above the server’s own 30-second limit for the database work behind a request.

## Get a specimen

`GET /v1/specimens/{specimenId}`

Use the exact `id` from a summary, encoded once as a single URL path segment. The ID is case-sensitive and 1–150 characters long. It cannot contain slashes, backslashes, or control characters, and cannot be exactly `.` or `..`. Your `catalogNumber`, fossil IDs, and public share links are not specimen IDs and do not work in this path. The request takes no query parameters, and the response is limited to 1 MiB. A missing specimen and a specimen in another account both return `404 not_found`. Other errors follow the [common errors](#errors-and-retries), and every read counts against the [rate limits](#rate-limits).

Fossils in a specimen record include each `descriptiveName` only if you ask for it: send the header `X-FossilVault-Features: descriptive-name`. Without it, `descriptiveName` is left out. The header has no effect on lists, which always include descriptive names.

Using the `fv_auth` helper from the [first request](#first-request), replace the example ID with one from your list. This request asks for descriptive names and prints the category.

```sh Get one specimen
specimen_id='example-4-fossil'
encoded_id=$(jq -rn --arg id "$specimen_id" '$id | @uri')
fv_auth | curl --silent --show-error --fail-with-body --header @- \
  --header 'X-FossilVault-Features: descriptive-name' \
  "https://api.fossilvault.app/v1/specimens/$encoded_id" \
  | jq 'if has("specimen") then .specimen.category else error(.code) end'
```

This is the record for the fossil above, with descriptive names:

```json Response body
{
  "specimen": {
    "id": "example-4-fossil",
    "category": "fossil",
    "createdAt": "2026-01-02T03:04:05.123456789Z",
    "catalogNumber": "FV-42",
    "fossils": [
      {
        "id": "fossil-example-4-fossil",
        "scientificName": "Otodus sp.",
        "descriptiveName": "Shark tooth",
        "taxonomy": {
          "genus": { "name": "Otodus", "author": "Glikman 1964" }
        },
        "element": "tooth",
        "dimensions": { "length": 24, "unit": "mm" }
      }
    ],
    "geology": { "era": "cenozoic", "period": "neogene", "formation": "Bone Valley" },
    "locality": { "name": "Peace River", "country": "US" },
    "collectedDate": "2020-03",
    "acquisition": { "method": "found" },
    "tags": ["sharks"],
    "isFavorite": false,
    "isPublic": false,
    "images": [
      { "id": "img_3b1f…", "url": "https://…" }
    ]
  }
}
```

Every record has `id`, `category`, `createdAt`, `tags`, `isFavorite`, `isPublic`, and `images`; empty arrays and `false` are valid values. Every other field or group is absent when the specimen has no value for it. Older records are reported in the same shapes. Enums are open: see [Compatibility](#compatibility).

### Identity and names

| Field | Meaning |
| --- | --- |
| `id` | The specimen ID. |
| `category` | `fossil`, `mineral`, `gemstone`, or `rock`. |
| `createdAt` | RFC 3339 UTC timestamp, with the stored fractional seconds. |
| `catalogNumber` | Your catalog or inventory number. Not the specimen ID. |
| `specimenName` | The custom name you gave the specimen, on any category: trimmed plain text of 1–120 UTF-16 code units. Show it as text, never as markup. |
| `tags` | Your tags, as an array of strings. |
| `isFavorite`, `isPublic` | Whether the specimen is a favorite, and whether it is published. |
| `shareUrl` | The specimen’s stored share link, when it has one. |

When `specimenName` is present, it is the specimen’s name in the app; the fossil names or `material.name` describe what it is.

### Fossils and taxonomy

| Field | Meaning |
| --- | --- |
| `fossils[]` | Fossils only, in presentation order. |
| `fossils[].id` | Opaque, read-only fossil ID. Not a specimen ID. |
| `fossils[].scientificName` | Derived from the taxonomy, as in lists. Absent when unknown. |
| `fossils[].descriptiveName` | Your descriptive name. Only with `X-FossilVault-Features: descriptive-name`. |
| `fossils[].taxonomy` | Keyed by rank name. Each rank is `{name, author?}`. `{}` means unidentified. |
| `fossils[].element`, `.dimensions`, `.notes` | The fossil’s element (such as `tooth`), size, and notes, when recorded. |

Taxonomy ranks are `kingdom`, `phylum`, `subphylum`, `class`, `subclass`, `superorder`, `order`, `infraorder`, `suborder`, `superfamily`, `family`, `subfamily`, `genus`, `subgenus`, and `species`.

### Material and form

| Field | Meaning |
| --- | --- |
| `material` | Minerals, gemstones, and rocks only. `name` is the mineral, rock, or gemstone name. Shared mineral properties such as `variety`, `chemicalFormula`, and `mohsHardness` sit beside it. |
| `material.rock` | Rock properties, such as `type`, `grainSize`, and `texture`. |
| `material.gemstone` | Gemstone properties, such as `cut`, `clarity`, and `treatment`, with a lab `report` of `{lab, number, date, origin}`. |
| `form` | Minerals, gemstones, and rocks only. A lowercase preset token, or free text of up to 120 UTF-16 code units. |

Form tokens are `rough`, `crystal`, `cluster`, `point`, `geode`, `matrix`, `tumbled`, `polished`, `slab`, `sphere`, `palm-stone`, `tower`, `freeform`, `carving`, `cabochon`, `faceted`, and `hand-sample`. Show a token you do not know as text. A fossil’s element is in each `fossils` entry; no specimen has a root `element`. Stored material values that no longer fit the category are still returned.

### Measurements

| Field | Meaning |
| --- | --- |
| `dimensions` | Minerals, gemstones, and rocks only. `{length?, width?, height?, unit}` with at least one positive side. Fossil sizes are in each `fossils` entry, in the same shape. |
| `matrixDimensions` | The size of the matrix, in the same shape. |
| `mass` | `{value, unit}`. Gemstones report `ct`. |

Length units are `mm`, `cm`, `in`, and `ft`; a size recorded without a unit reads as `mm`. Mass units are `g`, `kg`, `lb`, and `ct`.

### Geology and locality

| Field | Meaning |
| --- | --- |
| `geology` | `{era, period, epoch, age, formation}`. `era`, `period`, `epoch`, and `age` are tokens such as `cenozoic`, `neogene`, and `miocene`. `formation` is text. |
| `geology.age` | The geologic age name, not how old the specimen is. |
| `locality` | `{name, country, coordinates}`. |
| `locality.coordinates` | `{latitude, longitude, uncertaintyMeters?}`. No `uncertaintyMeters` means an exact point. |

### Dates, acquisition, and disposition

| Field | Meaning |
| --- | --- |
| `collectedDate` | ISO 8601 with only the recorded parts: `"2023"`, `"2023-05"`, or `"2023-05-14"`. |
| `acquisition` | `{date, method, source, price}`. `date` has the same format as `collectedDate`. `price` is a [financial field](#financial-fields). |
| `acquisition.method` | `found`, `gifted`, `purchased`, or `traded`. |
| `disposition` | Present when the specimen has left your collection: `{status, date, recipient, price, notes, images}`. |
| `disposition.status` | `sold`, `traded`, `gifted`, or `lost`. |
| `disposition.date` | A timestamp whose time of day carries no meaning. Format it in your time zone to get the day the app shows. |
| `disposition.images` | Entries contain only `url`. |

### Notes, condition, and storage

| Field | Meaning |
| --- | --- |
| `notes` | Your notes on the specimen, as text. |
| `condition` | The specimen’s condition, as text. |
| `storage` | Where you keep it: `{room, cabinet, drawer}`, each as text. |

### Image fields

Each `images` entry has a `url` and, for an image with a storage path, a stable `id`. The `id` is the same one an [image upload](#add-an-image) returns. Fetch the image from `url` without sending your API token.

### Financial fields

With `specimens:read:financial`, a record also has `acquisition.price`, `valuation`, and `disposition.price`, each `{amount, currency}`. A zero amount is valid.

- In `acquisition.price` and `valuation`, `currency` is a supported code, or `null` when the record has no currency or an unsupported one. The API never guesses a currency.
- In `disposition.price`, `currency` is always a supported code.
- Without the financial permission, these three fields are left out, and so is `acquisition` when nothing else remains in it.
- Notes are returned either way, including any amounts written in them.

## Create a specimen

`POST /v1/specimens`

Needs a token with `specimens:write`. Such a token can add records to your collection, including purchase prices and valuations. Each new specimen counts toward your plan’s specimen limit, and each create counts against the [rate limits](#rate-limits), including the daily write budget. A new specimen is private and has no images: [add images](#add-an-image) afterwards.

### Create headers

| Header | Value |
| --- | --- |
| `Content-Type` | `application/json`, optionally with `; charset=utf-8`. |
| `Idempotency-Key` | Required. A lowercase UUID, as `crypto.randomUUID()` returns. Use a new key for each new specimen. |
| `X-FossilVault-Features` | Optional. `descriptive-name` includes `fossils[].descriptiveName` in the response. |

### Create body rules

The body is a specimen record without the fields the server owns, at most 128 KiB. It accepts the fields described under [Get a specimen](#get-a-specimen), with these rules:

- `category` is required.
- A fossil needs `fossils`, with 1–64 entries. It cannot have `form`, root `dimensions`, or `material`.
- A mineral, gemstone, or rock needs `material.name`. It cannot have `fossils` or `matrixDimensions`.
- `material.rock` is only for rocks, and `material.gemstone` only for gemstones. A mass in `ct` is only for gemstones.
- Each taxonomy rank is `{name, author?}`. `fossils[].descriptiveName` is accepted.
- `specimenName` works on every category. It is trimmed, and a blank or `null` value is omitted. More than 120 UTF-16 code units after trimming is rejected, never truncated.
- `tags` are trimmed, lowercased, and deduplicated. At most 5 distinct tags may remain; each must be non-empty, at most 128 bytes in UTF-8, and free of `/` and control characters. The array may hold up to 20 entries before deduplication.
- `catalogNumber` must be unique in your collection, ignoring case. Two creates sent at the same moment with the same number can both succeed.
- `isFavorite`, `condition`, `notes`, `storage`, `acquisition` (including `price`), and `valuation` are accepted. `isFavorite` defaults to `false`.
- Unknown fields are rejected. So are the server-owned fields `id`, `createdAt`, `images`, `isPublic`, `shareUrl`, `disposition`, `fossils[].id`, and `fossils[].scientificName`.
- `listing` is rejected too: a specimen is offered in your Shop from the apps only.

### Create example

This Node.js 22 script creates one fossil and prints its new ID. It uses `FV_TOKEN_FILE` from the [first request](#first-request). Its `sendWrite` helper follows the retry rules for both writes ([create retries](#create-retries), [upload retries](#upload-retries)), and the [upload example](#upload-example) reuses it.

```js Create a fossil
import { readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";

const token = (await readFile(process.env.FV_TOKEN_FILE, "utf8")).trim();
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

// Sends one write; retries the identical request, key included, at most twice.
async function sendWrite(url, init, timeoutMs) {
  for (let attempt = 1; ; attempt++) {
    let response;
    try {
      response = await fetch(url, {
        ...init,
        redirect: "error",
        signal: AbortSignal.timeout(timeoutMs),
      });
    } catch (error) {
      if (attempt === 3) throw error; // timeout or lost connection: the outcome is unknown
      await sleep(2 ** attempt + Math.random());
      continue;
    }
    if (response.status === 201) return response.json();
    const { code } = await response.json().catch(() => ({}));
    const retryable =
      response.status === 202 ||
      response.status === 408 ||
      code === "operation_in_progress" ||
      (response.status >= 500 && code !== "recovery_required");
    if (!retryable || attempt === 3) throw new Error(`HTTP ${response.status} ${code ?? ""}`);
    await sleep(Number(response.headers.get("Retry-After")) || 2 ** attempt + Math.random());
  }
}

const { specimen } = await sendWrite(
  "https://api.fossilvault.app/v1/specimens",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      "Idempotency-Key": randomUUID(), // one key per specimen, reused by every retry
    },
    body: JSON.stringify({
      category: "fossil",
      catalogNumber: "FV-43",
      fossils: [
        {
          taxonomy: { genus: { name: "Otodus" }, species: { name: "megalodon" } },
          element: "tooth",
        },
      ],
      collectedDate: "2025-02",
      tags: ["sharks"],
    }),
  },
  35_000,
);
console.log(specimen.id);
```

### Create response

A `201` returns `{"specimen": …}` and a `Location` header with the specimen’s path. The specimen is filtered by the token’s permissions, as in a read.

Financial fields follow one extra rule. Without `specimens:read:financial`, the response includes `acquisition.price` and `valuation` only if your request sent them, and shows the values from your request. With the financial permission, it shows the stored values, as a read does.

### Create retries

**Retry with the same key and the same body.** If a create times out, returns a `5xx`, or its outcome is otherwise unknown, send it again with the same `Idempotency-Key` and an identical body. The retry either returns the specimen already created (`201` with `Idempotent-Replayed: true`) or creates it.

- Never generate a new key for a retry: that is how automations create duplicates.
- A key belongs to one token. A retry with a different token creates a second specimen.
- Only a successful create uses up a key. A rejected create stores nothing, so you can correct the body and send it again with the same key.
- Once a create with a key has succeeded, the same key with a different body returns `409 idempotency_conflict`.
- A replay returns the specimen as it is stored now.

### Create errors

These come in addition to the [common errors](#errors-and-retries).

| Response | Meaning | What to do |
| --- | --- | --- |
| `409 catalog_number_conflict` | Another specimen already uses that catalog number, ignoring case. | Use another number. |
| `409 idempotency_conflict` | This key already created a specimen from a different body. | Use a new key for a new specimen. |
| `409 specimen_limit_reached` | Your collection is at your plan’s specimen limit (Free: 50). | Do not retry until there is room. |
| `410 specimen_gone` | A replay whose specimen has been deleted since it was created. | Do not retry. |
| `413 payload_too_large` | The body is over 128 KiB. | Shorten the body. |
| `415 unsupported_media_type` | `Content-Type` is not `application/json`. | Send JSON with that type. |
| `422 validation_failed` | The body breaks a rule above. `errors` lists up to 20 `{pointer, code}` entries. | Fix the fields named by each pointer, then resend with the same key. |

Each `pointer` is a JSON Pointer into your body, such as `/specimenName`; an empty pointer means the whole body. Codes include `unrecognized_key`, `read_only`, `required`, `category_field`, `invalid_type`, `invalid_value`, and `too_long`, and new codes can be added. For example, `{"pointer": "/material/rock", "code": "category_field"}` means the field is not allowed for this category.

## Add an image

`POST /v1/specimens/{specimenId}/images`

Needs a token with `specimens:write`. It adds one image to any of your specimens, not only those the token created. Each upload counts against the [rate limits](#rate-limits), including the daily write budget it shares with creates.

> **Warning:** The image is stored exactly as you send it, with its EXIF data, GPS location, and orientation. An image added to a public specimen is published with it. Remove location data first if it should stay private.

### Upload headers

| Header | Value |
| --- | --- |
| `Content-Type` | Exactly `image/jpeg`, `image/png`, or `image/heic`, without parameters. |
| `Content-Length` | Required. The body size in bytes. |
| `Repr-Digest` | Required. The SHA-256 of the body: `sha-256=:<base64 digest>:`. |
| `Idempotency-Key` | Required. A lowercase UUID, new for each image. |

From a shell, `openssl dgst -sha256 -binary photo.jpg | base64` prints the base64 digest.

### Upload body and limits

Send the image bytes as the request body: JPEG, PNG, or HEIC with a `heic` or `heix` brand. Multipart, base64, and remote URLs are not accepted.

| Limit | Free | Pro, Lifetime | Max |
| --- | --- | --- | --- |
| Image size | 2 MiB | 6 MiB | 20 MiB |
| Images per specimen | 5 | 10 | 20 |

- Resize an image that is over your plan’s size limit before uploading. A declared size above 40 MiB is refused before admission and does not count against the rate limits.
- An image wider or taller than 32,768 pixels, or above 100 megapixels, is rejected with `422 image_invalid`.
- The whole body must arrive within 120 seconds of the start of the request.
- Length, digest, and format are checked before the image is stored, so a failed upload never becomes an image.
- Specimens that already have more images than the limit keep them, but cannot take another.

### Upload example

This continues the [create example](#create-example): it reuses `readFile`, `randomUUID`, `token`, `sendWrite`, and `specimen.id`. To add an image to an existing specimen, use its ID from a list instead. The 150-second timeout covers the 120-second body window plus the time to check and store the image.

```js Add an image
import { createHash } from "node:crypto";

const bytes = await readFile("photo.jpg");
const { image } = await sendWrite(
  `https://api.fossilvault.app/v1/specimens/${encodeURIComponent(specimen.id)}/images`,
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "image/jpeg",
      "Idempotency-Key": randomUUID(), // one key per image, reused by every retry
      "Repr-Digest": `sha-256=:${createHash("sha256").update(bytes).digest("base64")}:`,
    },
    body: bytes, // fetch sends Content-Length for a buffer
  },
  150_000,
);
console.log(image.id);
```

### Upload response

A `201` returns `{"specimenId": "…", "image": {"id": "img_…", "url": "https://…"}}` and a `Location` header with the specimen’s path. The image appears in the specimen’s `images` at once, with the same `id`; its thumbnail follows shortly after. The response does not contain the specimen: [read it](#get-a-specimen) if you need it.

A `202` means the image was verified but is not confirmed as attached yet. Its body is `{"specimenId": "…", "status": "operation_pending", "retryAfterSeconds": 60}`, with the same delay in `Retry-After`.

> **Warning:** If the FossilVault app has the specimen open while you upload, reload it in the app before you edit it there. Otherwise the app can save over the specimen and drop the new image.

### Upload retries

**Retry with the same key, headers, and bytes** after a timeout, a `202`, a `408`, a `409 operation_in_progress`, or a `5xx` other than `503 recovery_required`. Wait for `Retry-After` when the response has one.

- A retry returns the stored result (`201` with `Idempotent-Replayed: true`), resumes an interrupted upload, or reports one still pending. The `201` body is identical even after later edits.
- A new key would upload a second copy.
- A key allows three attempts.
- On a key’s first request, a refusal before the upload starts (`403`, `404`, `409 photo_limit_reached`, `409 public_gallery_unsupported`, `413`, `429`) stores nothing, so you can send the same key again.
- Once an upload has started, an error about its body is stored for the key. Correct the request and use a new key.

### Upload errors

These come in addition to the [common errors](#errors-and-retries).

| Response | Meaning | What to do |
| --- | --- | --- |
| `400 invalid_request` | Among other causes, the body length differs from `Content-Length`. | Correct the request; use a new key. |
| `408 request_timeout` | The body did not arrive within 120 seconds. `Retry-After` is 180 seconds. | Retry with the same key after the delay. |
| `409 idempotency_conflict` | The key was already used with a different specimen, body, type, size, or digest. | Use a new key for a new image. |
| `409 operation_in_progress` | Another attempt with this key is running, or its connection dropped. It clears within 3 minutes. | Retry with the same key after `Retry-After`. |
| `409 photo_limit_reached` | The specimen already has your plan’s number of images. | Do not retry. |
| `409 public_gallery_unsupported` | The specimen is public and its gallery cannot be published with the new image. | Do not retry unchanged. |
| `410 operation_expired` | An interrupted upload was abandoned after 24 hours. | Upload again with a new key. |
| `410 specimen_gone` | A replay whose specimen has been deleted since the upload. | Do not retry. |
| `411 length_required` | `Content-Length` is missing. | Send it. |
| `413 image_too_large` | The image is over your plan’s size limit or 40 MiB. `limitBytes` gives the limit applied. | Resize the image. |
| `415 unsupported_media_type` | `Content-Type` is not one of the three accepted types. | Send a supported type. |
| `422 image_digest_mismatch` | The body does not match `Repr-Digest`. | Recompute the digest; use a new key. |
| `422 image_invalid` | The body is not a valid image of the declared type, or exceeds the pixel limits. | Fix the image; use a new key. |
| `503 recovery_required` | The key has used its three attempts, or the upload cannot be completed automatically. | Upload again with a new key. |

## Rate limits

A request is *admitted* when it passes the checks made before your collection is read: the request line and headers, the token and its permission, and the remaining allowance. A request refused before that does not count. An admitted request counts whatever its outcome, including a missing specimen, a rejected create body, or a later server failure.

- **Allowance.** Every admitted request costs one against your account’s allowance, shared by all your tokens: list pages, specimen reads, creates, and image uploads. Today the allowance is 30 requests per rolling 60 seconds and 5,000 per UTC day. Limits may differ by plan in future, so read the `X-RateLimit-*` headers rather than assuming these numbers.
- **Write budget.** Creates and image uploads also share a daily write budget: 50 per UTC day on Free and 500 on other plans. Every admitted create or upload counts, including invalid ones. Replays of a completed write and idempotency conflicts do not. When the budget is spent, writes return `429 write_rate_limited` with `Retry-After` until the next UTC midnight; that response does not count against the allowance.

Keep only a few requests in flight at once: all of them draw on the same allowance.

| Response header | Meaning |
| --- | --- |
| `X-RateLimit-Minute-Limit`, `X-RateLimit-Minute-Remaining` | The rolling-minute allowance, and what remained when the request was admitted. |
| `X-RateLimit-Day-Limit`, `X-RateLimit-Day-Remaining` | The daily allowance, and what remained when the request was admitted. Concurrent requests can change these values at once. |
| `X-RateLimit-Day-Reset` | The next UTC midnight, as Unix seconds. |
| `Retry-After` | On `429`, the minimum number of seconds to wait before retrying. Also sent on some write responses; see [upload retries](#upload-retries). |

The `X-RateLimit-*` headers appear on every admitted request, including one that later fails.

## Errors and retries

Successful reads return `200 application/json`; creates and uploads return `201`. Every response has `Cache-Control: no-store, no-transform` and an `X-Request-Id`. An error has an `application/problem+json` body: read its HTTP status and `code`. If you need help, write to [support@fossilvault.app](mailto:support@fossilvault.app) and include the request ID.

```json Error body
{
  "type": "about:blank",
  "title": "Too Many Requests",
  "status": 429,
  "detail": "The request could not be completed.",
  "code": "rate_limited",
  "requestId": "00000000-0000-4000-8000-000000000001",
  "limitWindow": "minute"
}
```

These codes can come from any endpoint unless a row names the endpoints. [Create errors](#create-errors) and [upload errors](#upload-errors) list the codes specific to writes.

| Response | Meaning | What to do |
| --- | --- | --- |
| `400 invalid_request` | A malformed ID, parameter, header, or body. Also a body on a read, an `Authorization` header over 512 bytes, or a plain HTTP request. | Fix the request. |
| `400 invalid_cursor` | Lists only. The cursor is malformed, expired, or does not fit this request. | Start again without a cursor. |
| `400 invalid_idempotency_key` | Writes only. `Idempotency-Key` is missing or not a lowercase UUID. | Send a key from `crypto.randomUUID()`. |
| `400 invalid_digest` | Image uploads only. `Repr-Digest` is missing, malformed, or not SHA-256. | Send a SHA-256 digest. |
| `401 unauthorized` | The token is missing, malformed, unknown, expired, or revoked, or the request also sent another credential. | Get a valid token before retrying. |
| `403 account_unavailable` | The account is disabled, deleted, or was recreated. | Do not retry. |
| `403 api_access_disabled` | API access is switched off. | Do not retry unchanged. |
| `403 insufficient_scope` | Writes only. The token lacks `specimens:write`. This does not count against the rate limits. | Create a token with write permission. |
| `403 unsupported_account_protocol` | Writes only. Your account cannot accept writes through the API. This does not change on retry. | Contact support. |
| `403 writes_disabled` | Writes only. Writes are paused. Replays of completed writes still work. | Try again later. |
| `404 not_found` | Specimen paths only. The specimen does not exist or belongs to another account; both give the same response. | Check the ID against a list. |
| `405 method_not_allowed` | The method is not supported on this path. `Allow` lists the supported ones: `GET, POST` for the collection, `GET` for a specimen, `POST` for its images. | Use a listed method. |
| `414 uri_too_long` | The path and query exceed 8,192 bytes. | Shorten the request. |
| `429 edge_rate_limited` | Flood protection, applied before admission. No `limitWindow`; `Retry-After` is 60. | Wait for `Retry-After`, then slow down. |
| `429 rate_limited` | Your allowance is spent. `limitWindow` is `minute`, `day`, or `both`. | Wait for `Retry-After`, then retry a bounded number of times. |
| `429 write_rate_limited` | Writes only. Your daily write budget is spent. `limitWindow` is `day`. | Wait until the next UTC midnight. |
| `500 stored_data_invalid` | A stored record could not be returned. Other reads can still succeed. | Contact support with the request ID. |
| `503 dependency_unavailable` | A temporary failure. | Retry with bounded exponential backoff and jitter. For writes, keep the same key. |
| `503 policy_unavailable` | A temporary failure. | Retry the same way. |
| `503 unsupported_account_protocol` | Reads only. The account condition that writes report as `403 unsupported_account_protocol`. | Retry with bounded backoff; if it persists, contact support. |

Do not retry `400`, `401`, `403`, or `404` unchanged. Every response to an admitted request has already counted, so each retry is a new request against your allowance. Writes have their own retry rules: see [create retries](#create-retries) and [upload retries](#upload-retries).

## Compatibility

Read responses tolerantly:

- Ignore fields you do not know.
- Treat every enum in a response as open: category, units, currencies, statuses, geology, material types, and similar. Show or store an unknown value as text rather than failing. The OpenAPI document marks open enums with `x-extensible-enum`.
- Expect absent fields: optional fields and groups are left out when a specimen has no value, never filled in.

Requests are strict: unknown request fields are rejected.

Within v1, new optional fields, groups, and enum values can be added. Renames, removals, and changed meanings require a new major version.

## Version history

Newest first.

**Guide 1.0.1 · 2026-11-27.** Shop listings, contract revision `1.0.1`.

- [Create](#create-a-specimen) rejects a `listing` member with `read_only`. Shop placement is set in the apps only.
- Requests that worked before are unchanged.

**Guide 1.0.0 · 2026-11-23.** First public release, contract revision `1.0.0`.

- List specimens, read a specimen, create a specimen, and add an image, with the `specimens:read`, `specimens:read:financial`, and `specimens:write` permissions.

The [API documentation](https://fossilvault.app/docs/api/) always leads to the current guide.
