# API v3 reference

Base URL: `https://links.t-api.de/v3`. V3 is the recommended version for new integrations; [v2](./api-v2.md) remains supported. The maintained implementation roadmap is [`.plans/api/v3.md`](../.plans/api/v3.md). The machine-readable contract is [OpenAPI 3.1](./openapi-v3.json); CI validates it and tests route coverage and executable examples.

Send `Authorization: Bearer tl_YOUR_KEY` and JSON bodies. Session and SSO Bearer tokens are also accepted. New v3 keys default to `links:read`, `links:write`, `domains:read`, `qr:read`. Existing v3 keys retain their previous access through explicit account-wide grants added by the scope migration. Scoped v3 keys cannot be used on v1/v2 endpoints.

## Discover identity and defaults

```sh
curl https://links.t-api.de/v3/me \
  -H 'Authorization: Bearer tl_YOUR_KEY'
```

`data.permissions.granted` lists credential permissions; `effective` also accounts for the current role. An empty permission list still permits `/me`, including account ID, role, plan, permission diagnostics, defaults and limits. Profile name is included only with `user:info`; email only with `user:email`. These independent read permissions do not allow profile updates and are excluded from all presets. `data.defaults.domain` is the effective hostname and `domain_source` is `api_key`, `account`, `fallback`, or null when no usable domain exists. Existing `default_domain` and key domain objects remain available.

## Create a link

```sh
curl https://links.t-api.de/v3/links \
  -H 'Authorization: Bearer tl_YOUR_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://example.com/article","domain":"href.nz","slug":"article-example"}'
```

Requires `links:write` or `user:links:write`. Omit `domain` to select the usable key preference, then account default, then public fallback (normally `href.nz`). Explicit unavailable/invalid domains return 422; they never silently fall back. Hostnames are normalized for case/trailing dot. URLs, ports and paths are not domain selectors. Creation returns 201, a Location header and a link under `data`, including `destination_url`, `short_url`, `slug` and `domain.hostname`.

`GET /domains` requires `domains:read` and returns `data.domains[]`. `GET /links` requires `links:read` or `user:links:read`, defaults to the credential’s permitted links, and returns `data.links[]` plus `data.pagination`. It supports `q`, `tag`, `domain`, `status`, `page`, `per_page` (default 25, maximum 100). Admin cross-account operations additionally require `admin:links` and current admin role; collection access requires explicit `scope=all`.

## Routes and permissions

| Routes | Permission |
| --- | --- |
| `GET /` | Public discovery |
| `GET /me` | Any authenticated credential; `user:info` adds name, `user:email` adds email |
| `GET /domains` | `domains:read` |
| `GET /links`, `/links/summary`, `/links/tags`, `/links/lookup`, `/links/{id}`, `/links/{id}/health`, `/links/{id}/targets` | `links:read` or `user:links:read` |
| `POST /links`, `POST /links/bulk`, `PATCH /links/bulk`, `PATCH/PUT /links/{id}`, `PUT /links/{id}/targets` | `links:write` or `user:links:write` |
| `DELETE /links/{id}` | `links:delete` or `user:links:delete` |
| `GET /links/{id}/analytics`, `/clicks`, `/clicks/summary` | `analytics:read` or `user:analytics:read` |
| `GET /links/{id}/qr` | `qr:read` or `user:qr:read` |
| `GET /api-keys`, `GET /api-keys/{id}` | `keys:read` |
| `POST /api-keys`, `PATCH/PUT/DELETE /api-keys/{id}` | `keys:write` |

Link deletion deactivates the link and returns 200. Key deletion revokes the key, keeps its links and returns empty 204. QR returns SVG by default; `format=png&size=300` selects PNG. Bulk accepts 1–50 links and returns indexed outcomes: 201 all successful, 207 mixed, 422 entirely failed. Bulk uses the same input validation, domain selection, plan checks, service and audit path as single creation. Each failed item has `index`, `status`, `code` and a field-to-messages `errors` object. An entirely failed valid batch retains its summary/items under `data` alongside the standard 422 error. Invalid outer batches return `data: null`. Unexpected item failures are reported internally and return a generic message.

## Token and account scopes

For API keys, base link grants apply only to links whose creating `api_key_id` matches the calling key. Dashboard links, session-created links and links created by another key are excluded. Changing a key’s label, preferred domain or dashboard visibility does not change this scope. Resource IDs cannot bypass it: out-of-scope detail, update, delete, QR and analytics requests return 404, before input validation. Lists and their pagination totals use the same scope.

| This key’s links | All links in the same account | Operation |
| --- | --- | --- |
| `links:read` | `user:links:read` | List and read link details |
| `links:write` | `user:links:write` | Create links and update permitted links |
| `links:delete` | `user:links:delete` | Deactivate permitted links |
| `analytics:read` | `user:analytics:read` | Read analytics, clicks and click summaries |
| `qr:read` | `user:qr:read` | Download QR codes |

Each `user:` link grant also authorizes its base operation, so you do not need to select both. Operations remain independent: `user:links:read` grants neither editing, QR codes nor visitor analytics. There are no wildcard grants: `user:*:*`, `all:*:*` and `self:*:*` are illustrative patterns, not accepted permission strings. Base names already express token scope; duplicate `self:` aliases would add ambiguity. Explicit grants avoid inheriting future operations. `user` in a permission means the **same account**, never the entire service. In contrast, `scope=all` is an administrator collection selector; it requires `admin:links` and a current administrator role. With an operation grant and a current administrator role, `admin:links` permits individual resources in any account, including dashboard links in the administrator’s own account. The default `scope=mine` still applies the token/account scope to collections. Session and SSO credentials retain first-party account access.

For an account-wide reporting integration, create a key with:

```json
{"name":"Account reports","permissions":["user:links:read","user:analytics:read"]}
```

A key can delegate only permission names explicitly present in its effective grants. An account grant authorizes its base operation at runtime, but does not implicitly add that base name for delegation. A token-scoped caller with `keys:write` cannot grant itself or another key account-wide access. Grant key management deliberately: it includes revocation of other keys in the same account.

### Existing keys and rollout

Migration `2026_11_11_000003_preserve_v3_account_link_permissions` preserves historical account-wide link access using its frozen legacy names. The subsequent `2026_11_11_000005_rename_v3_user_permissions` migration renames `links:all:read` → `user:links:read`, `links:all:write` → `user:links:write`, `links:all:delete` → `user:links:delete`, `analytics:all:read` → `user:analytics:read`, and `qr:all:read` → `user:qr:read`. No link operation is inferred by the rename. Existing v3 keys also receive `user:info` and `user:email` to preserve their previous `/me` fields, including keys that previously had an empty list. Legacy null permissions stay null; v1/v2 behavior is unchanged.

New v3 keys use only their selected grants and do not receive profile grants automatically. New empty lists remain diagnostic-only. The API and dashboard accept only the canonical names after deployment; update explicit permission payloads in provisioning clients. Inspect `/me` and remove account/profile grants that integrations no longer need. A replacement key does not inherit its predecessor's links.

Deploy code and run `php artisan migrate --force` in a maintenance window before accepting v3 requests or key changes. Replace all old workers before reopening traffic. Run migrations once, in order: do not rerun compatibility backfills against new keys. Rollback requires disabling v3 traffic and key issuance, rolling back migration 000005 with the corresponding previous code, and restarting workers. Its down migration restores old account names and removes profile grants because the previous code exposes those fields unconditionally. Rolling back further to unscoped code is unsafe while scoped keys remain usable. Keep a normal database backup.

## Manage a v3 key

Key management is always restricted to the caller's own account. To create one, an authorized credential can send:

```json
{"name":"Publishing integration","preset":"link_creator","preferred_domain":"href.nz"}
```

Available presets: `link_creator`, `read_only`, `analytics`, `account_read_only`. The first three cover only links created by the calling API key. `account_read_only` grants `user:links:read`, `domains:read`, `user:qr:read`. Alternatively use explicit `permissions: []` or a subset of the permission names in the table, including optional `admin:links`. A preset and explicit permissions cannot be combined. The raw `api_key` is returned once on creation and cannot be retrieved later. The caller must possess every permission it grants. A finite caller expiry also bounds the created key's expiry.

PATCH accepts name, explicit permissions/preset, `preferred_domain` (null clears), `show_on_dashboard` and `expires_at`. V3 management cannot update legacy keys, change versions, grant AI bypass, or update keys more powerful than the caller. Revocation takes effect on the next authentication. Child keys are independent; revoking their creator does not automatically revoke them.

## Response and operational behavior

JSON uses `{data, error, meta}`. Errors expose `error.code`, `message`, `fields` and `retry_after_seconds`. Missing permission returns 403 `insufficient_permission`; foreign resources return 404. Authentication failure returns 401 with a Bearer challenge. Quotas/throttles return 429 with Retry-After. Account limits remain shared across keys and dashboard activity; administrator role does not currently exempt plan quotas.

Every response carries `X-Request-ID`; JSON repeats it as `meta.request_id`. Authenticated responses are private/no-store. Single/bulk link creation supports optional idempotency keys; unkeyed POST retries can create duplicates. Link cursor pagination is opt-in; Problem Details remains planned. Browser CORS is opt-in: configure `API_V3_CORS_ALLOWED_ORIGINS` with explicit comma-separated origins. V3 uses Bearer tokens without credentialed cookies; its preflight accepts Authorization, JSON and Idempotency-Key. Location, Retry-After, X-Request-ID, Idempotency-Replayed and API version headers are exposed. The separate auth API retains its own cookie-based CORS configuration.

## Input validation and partial updates

Single and bulk creation accept `url` (legacy `destination_url`), hostname `domain` (legacy `domain_id`), slug, description, tags, social preview, password, protection/tracking booleans and UTM fields. Conflicting URL, domain or UTM aliases fail validation. Destination URLs must be absolute HTTP(S), at most 2048 characters. Passwords are 8–72 characters and never returned. Tags accept an array or legacy comma-separated text, with at most 10 lowercase slug tags of 1–30 characters. Booleans accept JSON true/false or compatibility 0/1; null is rejected for link state/protection/tracking booleans.

Use future RFC 3339 `expires_at` or positive `expires_in`, never both. Durations accept integer seconds or strings such as `7d`, `24h`, `30m`, with a maximum of 10 years (315360000 seconds). Duration months mean 30 days and years mean 365 days. Invalid durations fail instead of producing permanent links.

PATCH and compatibility PUT update supplied fields only. Omitted fields remain unchanged; null clears description, social preview fields, tags, expiry and password. Empty tags clear tags; `utm: null` clears all attribution, while `utm: {"source": null}` clears only source. `remove_password: true` remains accepted; setting and removing a password together fails. Setting `is_active` toggles redirects. Domain, slug and owner changes fail validation. Detail/update responses include targets and current protection/tracking flags; `password_protected` reports whether a password hash exists without exposing it.

Target updates replace the target collection: an empty list removes all, null/omission preserves it, and omitted existing IDs are removed. Existing target IDs must belong to the link and occur only once. At most 20 targets are allowed. Target validation and link changes complete in one database transaction.

## Query windows and tracked data

Link queries validate pagination, scope, status and search aliases. `domain` is a normalized hostname; use the explicitly named `domain_id` compatibility filter for IDs. Conflicting hostname/ID filters fail. Link lists and key lists order by creation timestamp and ID. Key lists always use 25 items per page and do not export all keys.

Analytics and click endpoints use an inclusive `from`/`to` window, defaulting to the last 30 days with a maximum span of 90 days. Reverse, invalid or oversized ranges fail with 422. Narrow the range for busy links. Existing click filters (`tag`, `user_identifier`, `has_user`, `has_params`) apply to both click listing and summary; target counts/shares use those same filters, including direct-click visibility. Click summary tag aggregation streams rows instead of materializing every click. QR validates format and integer size; size remains clamped to 100–1200.

Click access requires `analytics:read` for links created by the calling key, or `user:analytics:read` for any link in the same account. Other accounts’ links additionally require explicit current administrator capability. Clicks retain existing pseudonymous IP hashes, user agents, location, caller-provided identifiers and query parameters. These fields can identify visitors; grant analytics access deliberately and treat exports as sensitive. Encrypted/raw IP values are excluded. The click/key collections preserve the existing Laravel paginator shape: `data` is the item array directly, with pagination fields alongside `meta`.

## Limits and dashboard key setup

`GET /me` adds `limits.requests`, `limits.creation`, `limits.daily` and `capabilities`. Each bucket names its account scope, enforcement status, reason and limit; rolling buckets report `window_seconds: 60`, without invented remaining counters. Daily usage/remaining/reset come from the same account quota source used in creation and include the application timezone. Allowed clients are exempt from the request bucket only. Unlimited plans have null daily/creation limits, while request throttling, permissions and threat checks remain in effect. These values are snapshots and do not reserve quota; concurrent creation is not guaranteed atomic.

Dashboard key creation defaults to the latest active version (v3 after migration). Selecting v3 shows exact preset grants or an explicit custom selection (including empty). V3 settings allow permission editing. Creation and settings use labeled dashboard-themed checkboxes with scope descriptions, keyboard focus and screen-reader description associations. “Prepare v3 key” copies a legacy key's label/domain/visibility into a separate new-key form for review; generation creates a new secret and leaves the legacy key active. Version switching across the legacy/v3 boundary remains rejected. Test the new integration before revoking the old key. Administrator link grants remain ineffective without the current admin role.

## Inventory filters, ordering and cursors

`GET /links` keeps its page response by default. Add `sort=created_at|updated_at|slug` and `direction=asc|desc` (defaults: `created_at`, `desc`). Every order has an ID tie-breaker. New filters also apply to `/links/summary` and `/links/tags`:

| Filter | Meaning |
| --- | --- |
| `ids[]=ULID` | Between 1 and 100 distinct link IDs; inaccessible IDs are excluded |
| `api_key_id=ULID` or `none` | Link creation origin; `none` selects dashboard/session-created links |
| `password_protected`, `health_check_enabled`, `user_tracking_enabled` | Each accepts `0`, `1`, `true`, `false` |
| `created_after`, `created_before`, `updated_after`, `updated_before` | Inclusive date/time boundaries, normalized to application timezone; reversed pairs fail |

Origin and ID filters never broaden permissions. Existing search, domain, tag and status filters remain supported. Tags use exact JSON membership.

For large inventories, opt into cursor mode:

```sh
curl 'https://links.t-api.de/v3/links?pagination=cursor&per_page=25&sort=created_at&direction=desc' \
  -H 'Authorization: Bearer tl_YOUR_KEY'
```

The response keeps `data.links` and returns `data.pagination` with `mode: "cursor"`, `per_page`, `has_more`, `next_cursor`, `previous_cursor`, `next_url` and `previous_url`. Follow the provided URLs. Cursor mode omits page numbers and totals, cannot combine with `page`, and supports immutable `created_at` or `slug` sorting; `updated_at` is page-only. If a legacy inventory has null creation timestamps, created_at cursor mode returns a `sort` validation error; use `sort=slug` or page mode to include those links. Tokens are authenticated, expire after 24 hours, and bind to the credential, effective permissions and query. Keep filters, sorting and page size unchanged. Tampering, expiry or context changes return 422 with a `cursor` field error; start a new traversal. Cursors provide stable ordering, not a database snapshot: concurrent deletions and changes to filter membership can change results.

## Summaries, tags and address lookup

These endpoints require `links:read` or `user:links:read` and apply the same token/account scope as link lists, including optional administrator `scope=all`:

- `GET /links/summary`: filtered inventory counts under `data`: `total`, `active`, `inactive`, `expired`, `password_protected`, `health_check_enabled`. `active` means currently redirectable; inactive and expired can overlap. These are inventory counts, not analytics or quota usage.
- `GET /links/tags?limit=50`: `data.tags[]` entries contain `tag` and `links_count`, ordered by count descending, then tag ascending. `limit` is 1–100. Counts reflect the filtered inventory, count each tag once per link, and exclude removed/inaccessible links. Aggregation scans at most 10,000 tagged links; larger inventories return 422 with a `filters` error, so narrow the date/domain/other filters. No partial counts are returned.
- `GET /links/lookup?domain=href.nz&slug=example`: the normal link-detail representation, including targets. Hostnames normalize case/trailing dots; slugs match exactly. Unknown or inaccessible addresses return 404. Use `scope=all` only with explicit current administrator capability for cross-account lookup.

## Health status and targeting rules

`GET /links/{id}/health` requires link read permission. It returns stored `link_id`, `enabled`, `status` (`healthy`, `degraded`, `unreachable` or null), `status_code`, `response_time_ms` and `checked_at`. Results may be stale or absent. This endpoint does not probe destinations and does not expose internal diagnostic errors. Enable or disable scheduled checking with the existing `health_check_enabled` link update field.

`GET /links/{id}/targets` requires link read permission and returns `data.targets[]`. `PUT /links/{id}/targets` requires link write permission and replaces the collection, returning the updated link representation:

```json
{"targets":[{"destination_url":"https://example.com/de","label":"Germany","country_codes":["DE"],"weight":100,"is_active":true}]}
```

Only `targets` is accepted by this endpoint. The collection must be present and contain at most 20 entries; `[]` clears it, while null/omission fails. Supply an existing target `id` to update it while retaining its identity and analytics. Omitted IDs are removed; duplicate or foreign IDs fail. Validation, changes and cache invalidation use the same transactional service as PATCH targeting. Scope is checked before validation. Base/account grants retain their existing meanings.

## Bulk link updates

`PATCH /links/bulk` requires `links:write` or `user:links:write`. Send a list of 1–50 objects, each containing `id` plus the normal PATCH fields:

```json
{"links":[{"id":"01ARZ3NDEKTSV4RRFFQ69G5FAV","description":"Spring campaign","tags":["spring"],"is_active":true}]}
```

Each item independently follows normal scope, normalization, URL safety, validation, target transactions, audit and cache invalidation. An inaccessible ID returns an item `not_found` error before validating its update fields. Subsequent occurrences of a duplicate ID fail validation. Successful items remain committed if another item fails; this is not a batch transaction. There is no new permanent-delete or ownership reassignment operation.

Responses retain the bulk `data.summary` and indexed `data.items` shape. Updated items use `status: "updated"` and a link under `data`; failures use `status: "failed"`, `code` and field-to-messages `errors`. Status is 200 when all succeed, 207 for mixed outcomes, or 422 when all fail. Invalid outer arrays return the normal validation envelope. Review per-item results before retrying failed updates.

## Idempotent single and bulk creation

Use an optional `Idempotency-Key` on `POST /links` and `POST /links/bulk` to retry a creation without duplicating its links:

```sh
curl https://links.t-api.de/v3/links \
  -H 'Authorization: Bearer tl_YOUR_KEY' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: publishing-job-2026-001' \
  -d '{"url":"https://example.com/article","expires_in":"7d"}'
```

Choose a fresh key for each logical operation. It must contain 1–128 ASCII letters, digits, dots, underscores, colons or dashes. Keyed requests require a valid JSON object body of at most 1 MiB. Requests without the header keep their existing behavior. This feature applies only to the two creation routes; it does not add retry guarantees to key creation or bulk updates.

- Retention is 24 hours from the original reservation. Within that window, the same account, Bearer credential, route and key replay the original status, operation data and Location. `Idempotency-Replayed` is `false` for original execution and `true` for replay. Request IDs and envelope timestamps are freshly generated. Replay is a historical operation result, not a fresh read of a subsequently edited/deactivated link.
- Object key order and JSON whitespace are ignored. Array order and value types remain significant; swapping bulk items is a different request. Aliases, explicit defaults and duration strings are not normalized into equivalent requests: retry the same payload and query parameters. An `expires_in` retry returns the original expiry instead of extending it.
- A different fingerprint returns 409 `idempotency_conflict`. An identical request still running returns 409 `idempotency_in_progress` with `Retry-After: 1`; this is a retry hint, not a guarantee of completion in one second.
- Authentication, current permissions and account request throttling run before replay. Revoked/expired keys and missing grants still fail. A different credential or route has an independent namespace, even on the same account.
- A database uniqueness constraint reserves the operation. Link changes and the encrypted replay outcome commit in the same database transaction. Bulk creation also isolates each item in its own nested transaction: failed items do not leave partial links. Mixed (207) and entirely failed valid bulk (422) outcomes are retained exactly. Correcting a cached failed bulk requires a new key; reusing the old key with changed items returns 409.
- Single validation failures, malformed outer batches and server failures are not retained. Their database writes roll back and the pending reservation is released; a corrected request may reuse that key. Throttle attempts and external service side effects are not database transactions and are not refunded by rollback.

Deploy migration `2026_11_11_000004_create_api_idempotency_requests` before enabling this code. The scheduler runs `api:prune-idempotency` hourly; operators can invoke it manually. Expired records, including abandoned pending reservations, are deleted; expired requests can execute again. Never treat a key as permanent deduplication. Keep normal database backups and `APP_KEY` stable over the retry window: rotating it changes matching and invalidates encrypted cursor tokens. Test locking/uniqueness on the production database engine before a concurrency-sensitive rollout; the repository tests use SQLite and exercise deterministic overlapping requests. This feature does not implement durable quota reservations across different operations or guarantee exactly-once effects in external services.
