> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Media & Avatar — Flutter API handoff

**Source status:** Source-reviewed against GitLab `main`, 2026-11-22. This document covers **5/5 Flutter Media routes**. Examples are illustrative contracts, not captured staging responses. **Base URL:** `/api/v1`. Successful JSON responses use `{ "data": ... }`; file-serving and 204 responses do not.

## Route matrix

| Method | Path | Auth | Throttle | Success | Purpose |
|---|---|---|---|---|---|
| POST | `/media` | Sanctum bearer | 30/min | 201 | Upload temporary file |
| GET | `/media/{reference}/file` | Valid URL signature | 300/min | 200 binary | Fetch private media bytes |
| PUT | `/me/avatar` | Sanctum bearer | No route-specific limit | 200 | Attach previously uploaded reference |
| POST | `/me/avatar` | Sanctum bearer | 30/min | 201 | Upload and attach avatar in one call |
| DELETE | `/me/avatar` | Sanctum bearer | No route-specific limit | 204 | Remove avatar |

Source: [`Routes/api.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Media/Routes/api.php).

## 1. `POST /api/v1/media` — temporary upload

`Content-Type: multipart/form-data`; `Authorization: Bearer <token>`.

| Request field | Type | Required | Server validation |
|---|---|---|---|
| `file` | multipart binary file | Yes | Laravel `file`; `max` = `media.max_upload_kb` (default 10240 KiB) |

The uploader independently inspects actual bytes: file must be nonempty, within configured maximum, not contain executable code, and have an allowed **detected** MIME. Default MIME allowlist: `image/jpeg`, `image/png`, `image/webp`, `image/gif`, `application/pdf`. Do **not** trust filename extension or client-supplied MIME. The reference is stored as **temporary**, not yet attached to an entity.

**201 response — illustrative:**

```json
{"data":{"reference":"med_0123456789abcdef0123456789abcdef","mime":"image/jpeg","size":84531,"url":"https://api.example.com/api/v1/media/med_0123456789abcdef0123456789abcdef/file?expires=...&signature=..."}}
```

| Response path | Type | Meaning |
|---|---|---|
| `data.reference` | string | Opaque `med_` plus 32 lowercase hex characters; save to attach to a supported slot |
| `data.mime` | string | MIME detected by server inspection |
| `data.size` | integer | File size in bytes |
| `data.url` | string | Signed media retrieval URL; use unchanged, including query string |

**Error handling:** `401` no/invalid token; `422` missing/non-file/too-large form input; business upload rejection for empty, disallowed type, executable content or byte limit (inspect `error.code`); `429` throttle. A successful upload **does not** update the user's avatar. Temporary unattached media is subject to cleanup (default temporary TTL 24 hours).

## 2. `GET /api/v1/media/{reference}/file` — signed image/file

| Request component | Type | Required | Rule |
|---|---|---|---|
| `reference` | path string | Yes | Route regex `med_[a-f0-9]{32}` |
| `expires` / `signature` | URL query values | Yes for signed URL | Generated by backend; do not generate client-side |
| Bearer token | header | No | Signature, not session, authorizes file read |

**200 response:** binary bytes (`BinaryFileResponse`), **not JSON**. Headers include detected `Content-Type`, `Content-Disposition: inline; filename="..."`, and `Cache-Control: private, max-age=3600`. The server looks up the reference for serving and reads from private media storage.

**Errors:** invalid/expired/missing signature rejected by Laravel signed middleware (commonly `403`); unknown/not-servable reference raises `MediaNotFound`; `429` after 300/min. Flutter should pass the **entire URL** from the API to its image loader, and refresh the signed URL through the owning API when it expires. Do not cache a signed URL indefinitely.

## 3. `PUT /api/v1/me/avatar` — attach uploaded reference

`Content-Type: application/json`; Sanctum bearer.

| Request field | Type | Required | Validation |
|---|---|---|---|
| `reference` | string | Yes | Max 40 characters; subsequent synchronizer verifies reference and slot eligibility |

```json
{"reference":"med_0123456789abcdef0123456789abcdef"}
```

**200 response:**

```json
{"data":{"avatar_url":"https://api.example.com/api/v1/media/med_0123456789abcdef0123456789abcdef/file?expires=...&signature=..."}}
```

| Response path | Type | Meaning |
|---|---|---|
| `data.avatar_url` | string or null | Current user's signed avatar URL (null if no avatar, depending on avatar provider) |

The synchronizer attaches to `OwnerRef('user', current_user_id)` in the `avatar` slot. Client must not send `user_id`, `owner_type` or `slot`: backend derives them. A reference must be accepted by the slot policy and ownership checks; upload success alone does not guarantee attachment success.

## 4. `POST /api/v1/me/avatar` — upload and attach in one call

`Content-Type: multipart/form-data`; Sanctum bearer.

| Request field | Type | Required | Validation |
|---|---|---|---|
| `avatar` | multipart binary file | Yes | Laravel `file`; max configured upload KB (default 10240 KiB); uploader's detected-MIME/security checks also apply |

**201 response:**

```json
{"data":{"avatar_url":"https://api.example.com/api/v1/media/med_0123456789abcdef0123456789abcdef/file?expires=...&signature=..."}}
```

| Response path | Type | Meaning |
|---|---|---|
| `data.avatar_url` | string or null | Signed URL of the attached avatar |

This call uploads a temporary reference internally and immediately synchronizes the `avatar` slot. It **does not return** `reference`, `mime` or `size`. Use this for the simplest profile-photo UX. The slot may enforce stricter image requirements than the global upload allowlist; a PDF passing the global uploader is not a promise that it is a valid avatar.

## 5. `DELETE /api/v1/me/avatar` — remove avatar

No body. Sanctum bearer. **204 No Content**: no JSON `data` object; do not attempt to decode a response body. The backend synchronizes the user's avatar slot to an empty reference list. Refresh `GET /me` or local avatar state after success.

## Flutter implementation flow

1. For profile avatar replacement, prefer `POST /me/avatar` with multipart field **`avatar`**. Use `PUT /me/avatar` only if an earlier `POST /media` returned a reference.
2. Show loading while uploading; on success update the UI from `data.avatar_url`. Do not derive image URLs from `reference` or manually append signature parameters.
3. Keep the selected image's bytes within the configured limit. For avatar UX, prefer JPEG/PNG/WebP and let the backend enforce final slot rules.
4. For removal, call `DELETE /me/avatar`, treat `204` as success and clear the cached avatar; refetch profile if needed.
5. Handle `401` with sign-in/token refresh flow, `422` with field validation, `429` with a retry delay, and business errors using the server error code/message. No staging-specific behavior is asserted here.
6. Signed URLs are private access credentials: avoid logging or sharing full signed query strings. Image loading must not require an Authorization header for the signed media route.

## Source references and verification boundary

- [`MediaController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Media/Interfaces/Http/Controllers/MediaController.php) — upload and binary serving.
- [`AvatarController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Media/Interfaces/Http/Controllers/AvatarController.php) — attach, one-shot upload, delete.
- [`MediaUploader.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Media/Application/MediaUploader.php) — actual upload result fields, MIME and safety checks.
- [`Config/media.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Media/Config/media.php) — configurable defaults, signed URL TTL, cleanup TTL.

**Not performed:** live Staging calls, signed URL expiry test, actual avatar-slot acceptance test, and on-device image rendering. Those require environment access and must not be marked passed from source inspection alone.
