# danable API reference Base URL: `http://localhost:8000/api/v1` (prefix from `config.yaml` `app.api_prefix`). Interactive docs: `http://localhost:8000/docs`. ## Conventions - Auth: `Authorization: Bearer ` on every endpoint except those marked Public. `GET /auth/login` with wrong credentials returns 401 and the frontend redirects to `/login`. - Tracing headers (optional in, always out): send `X-Session-ID` (one ID per browser visit; server mints one if absent) and optionally `X-User-Id`. Responses echo `X-Session-ID` and a per-request `X-Trace-ID`. - Errors are JSON `{ detail: string }`. Common codes: `400` bad input, `401` missing/invalid token, `404` unknown id, `409` slug/email conflict, `422` validation, `503` R2 not configured (`.env` keys missing). - Enums: `taskType`: `classification | object_detection | segmentation`; image `status`: `unassigned | in_progress | pending_review | completed`; shape `type`: `bbox | polygon | point`. ## System (Public) | Method | Path | Description | |---|---|---| | GET | `/health` | Liveness incl. DB check, `{ ok: true }` | | GET | `/metrics` | Phase-1 traffic counters per route | | GET | `/storage/usage` | Real bucket `{ bytes, objects, quota_bytes }` (10-min cache) | | GET | `/` (root, no prefix) | Name, docs and health links | | POST | `/admin/init-db` | Create tables, seed dev admin. Dev-only | | POST | `/admin/backfill-thumbnails?limit=100` | Mint missing thumbs. Dev-only | ## Auth (Public) `POST /auth/login` — body `{ email, password }` — returns: ```json { "user": { "id": "...", "name": "Admin", "email": "admin@danable.local", "avatarInitials": "A", "avatarColor": "#3B82F6", "role": "admin", "status": "active", "isOnline": true, "lastActive": "..." }, "accessToken": "", "refreshToken": "" } ``` `GET /auth/me` (auth) — current user in the same shape. ## Users (auth) | Method | Path | Body | Description | |---|---|---|---| | GET | `/users` | — | All users `{ id, email, name, role, status, assignedProjectIds }` | | POST | `/users` | `{ email, role, projectIds? }` | Invite (unusable password until set), `201` | | PATCH | `/users/{id}` | `{ role?, status?, projectIds? }` | Role / suspend / project assignment | Roles: `admin | manager | annotator | reviewer`. Status: `active | invited | suspended` (suspended tokens are rejected). ## Projects (auth) | Method | Path | Description | |---|---|---| | GET | `/projects` | Full project cards: `stats`, `classes`, `members`, `thumbnailUrl` | | POST | `/projects` | `{ name, slug, description?, taskType }`, `201` | | GET | `/projects/{id}` | Detail (same card shape) | | PATCH | `/projects/{id}` | `{ name?, slug?, description?, task_type?, status? }` | | DELETE | `/projects/{id}` | Cascades images, annotations, classes, exports, AI and action rows | | POST | `/projects/{id}/classes` | `{ name, color?, shortcutKey? }`, `201` | | PUT | `/projects/{id}/classes` | Bulk replace `[{ id?, name, color }]` (matches LabelsTab semantics) | `stats` example: `{ totalImages, unassigned, inProgress, pendingReview, completed, totalObjects }`. `members` are users assigned to the project with per-member `assignedCount`. ## Images (auth) Direct-to-R2 upload keeps bytes and bandwidth off the API: 1. `POST /projects/{id}/images/presign` `{ fileName, contentType }` → `{ putUrl, r2Key }` (900s TTL). 2. `PUT ` with the file bytes (`Content-Type` must match). 3. `POST /projects/{id}/images` `{ fileName, r2Key, width?, height? }` → `201 { id, r2Key, url }`. Confirm verifies the object exists, writes the metadata row and mints 512px + 128px thumbnails (fail-open). `GET /projects/{id}/images` is paginated — never the whole dataset: ```text GET /projects/{id}/images?status=all&search=img_&assignee=all&limit=50&offset=0 → { "items": [ ... ], "total": 1000 } ``` `limit` clamps to 1..200 (config `max_page_size`). Item fields: `id`, `projectId`, `fileName`, `url`, `thumbnailUrl` (512px), `thumbnailSmallUrl` (128px, falls back up the chain), `width/height`, `status`, `objectCount`, `assignedTo/assignedToName`, `reviewerName`, `classificationLabelId`, `flags`. `PATCH /projects/{id}/images/{imageId}?status=completed` — status transition. `POST /projects/{id}/images/batch-presign` — one call for ≤200 files: `[{ fileName, contentType }]` → `[{ fileName, putUrl, r2Key }]` (keys carry unique tmp ids, so duplicate filenames never collide). `GET /projects/{id}/images/by-id/{imageId}` — `{ offset, total }` in list order (deterministic `created_at DESC, id DESC`); backs `?imageId=` deep links into thousand-image datasets. ## Resumable multipart uploads (files ~100MB and up) Small files keep the single-PUT presign path. Big single files (GB zips, TIFF, video) go multipart, straight to R2: 1. `POST /projects/{id}/uploads/multipart` `{ fileName, contentType }` → `{ key, uploadId, partSize: 8388608 }`. 2. `POST .../uploads/multipart/parts` `{ key, uploadId, numbers: [1..N] }` → `{ urls: { "1": "...", ... } }` (1h TTL each). 3. PUT every part (parallel, per-part retry; store ETags client-side — the upload resumes after network drops instead of restarting). 4. `POST .../uploads/multipart/complete` `{ key, uploadId, parts: [{ ETag, PartNumber }] }` → `{ key, etag }`. 5. `POST .../uploads/multipart/abort` to cancel and free the upload. ETag response headers are exposed via the bucket CORS policy, which the frontend needs to read them. ## Server-side dataset imports (GB-scale zips) `POST /projects/{id}/imports/local-zip` `{ path }` (absolute server path) or `POST /projects/{id}/imports/r2-zip` `{ r2_key }` (zip already uploaded, e.g. via multipart) → `202 { id, status: queued, ... }`. The worker streams the archive (one image in RAM at a time), uploads originals + 512/128px thumbs concurrently, commits DB rows in batches, then bulk-upserts COCO annotations. Re-running skips files already present. `GET /projects/{id}/imports` and `GET /projects/{id}/imports/{jobId}` poll `{ status, total_files, done_files, saved_annotations, error }`. ## Annotations (auth) `GET /projects/{pid}/images/{iid}/annotation` — one row per image: ```json { "imageId": "...", "projectId": "...", "classificationLabelId": "cls-1", "flags": { "blurryOrUncertain": false, "needsRecheck": false }, "shapes": [{ "id": "s1", "index": 1, "type": "bbox", "labelId": "cls-1", "labelName": "car", "color": "#ff0000", "visible": true, "bbox": { "x": 10, "y": 20, "width": 100, "height": 80 } }] } ``` `PUT /projects/{id}/annotations/batch` with `{ [imageId]: { classificationLabelId?, flags?, shapes[] } }` upserts up to 500 images in one commit (COCO/YOLO import path) → `{ saved, missing: [...] }`. `PUT` same path with `{ classificationLabelId?, flags?, shapes[] }` upserts (one row per image, 404 when the image does not exist) and syncs `object_count` / flags onto the image row. Also emits an `annotation.save` action event. Polygon shapes use `points: [{x, y}]`, points use `point`. ## Events and activities `POST /events` (Public, `202`) — client-side actions the backend never sees: ```json { "session_id": "…", "events": [ { "action": "image.status", "project_id": "…", "image_id": "…", "payload": { "from": "a", "to": "b" } } ] } ``` `session_id` is required; max 200 events/call. Enqueued to Redis and drained into `action_events` (requeued on DB failure, never lost, never blocks). `GET /activities?limit=30` (auth) — human feed derived from that table: `[{ id, timestamp, userName, actionText, projectId }]`. ## Worked example (curl) ```bash B=http://localhost:8000/api/v1 curl -s -X POST $B/admin/init-db TOK=$(curl -s -X POST $B/auth/login -H 'Content-Type: application/json' \ -d '{"email":"admin@danable.local","password":"Admin123!"}' \ | python3 -c "import sys,json; print(json.load(sys.stdin)['accessToken'])") H="Authorization: Bearer $TOK" PID=$(curl -s -X POST $B/projects -H "$H" -H 'Content-Type: application/json' \ -d '{"name":"Pho Co","slug":"pho-co","description":"e2e","taskType":"classification"}' \ | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") # upload one image PRE=$(curl -s -X POST $B/projects/$PID/images/presign -H "$H" \ -H 'Content-Type: application/json' -d '{"fileName":"s.jpg","contentType":"image/jpeg"}') PUTURL=$(echo "$PRE" | python3 -c "import sys,json; print(json.load(sys.stdin)['putUrl'])") R2KEY=$(echo "$PRE" | python3 -c "import sys,json; print(json.load(sys.stdin)['r2Key'])") curl -s -o /dev/null -w "%{http_code}\n" -X PUT -H 'Content-Type: image/jpeg' \ --data-binary @photo.jpg "$PUTURL" IID=$(curl -s -X POST $B/projects/$PID/images -H "$H" -H 'Content-Type: application/json' \ -d "{\"fileName\":\"s.jpg\",\"r2Key\":\"$R2KEY\",\"width\":1280,\"height\":720}" \ | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") # classify + complete curl -s -X PUT $B/projects/$PID/images/$IID/annotation -H "$H" \ -H 'Content-Type: application/json' -d '{"shapes":[],"flags":{}}' curl -s -X PATCH "$B/projects/$PID/images/$IID?status=completed" -H "$H" ```