> ## Documentation Index
> Fetch the complete documentation index at: https://docs.routa.chat/llms.txt
> Use this file to discover all available pages before exploring further.

# Media

> Upload a file to Routa with media.upload(), from bytes or a URL, and retrieve the media object with media.retrieve().

`routa.media` stores a file in Routa and retrieves the media object. For the concept, the accepted types and the limits, see [Media](https://docs.routa.chat/en/concepts/media.md).

| Method | Endpoint | Scope |
| - | - | - |
| `upload(params)` | [`POST /v1/media`](https://docs.routa.chat/en/api-reference/endpoint/media/upload) | `media:write` |
| `retrieve(id)` | [`GET /v1/media/{id}`](https://docs.routa.chat/en/api-reference/endpoint/media/retrieve) | `media:read` |

> [!NOTE]
>
> `media.upload()` exists from version 0.3.0. The **sample** of a template header, used to create the template, does not go through here: use [`templates.uploadMedia()`](https://docs.routa.chat/en/sdk/templates#image-video-or-document-header). The file each template send carries does.

## `upload`

There are two modes, and you use exactly one of them. The two form a type union: mixing them, or passing `file` without `contentType`, does not compile.

### Upload the bytes

```ts theme={null}
import { readFile } from 'node:fs/promises'

const media = await routa.media.upload({
  file: await readFile('./photo.png'), // a Uint8Array (a Buffer is one) or a Blob
  contentType: 'image/png',
})

console.log(media.id, media.status) // "med_...", "ready"
```

The SDK sends the bytes as the request body, with no JSON or *multipart*.

* `contentType` is sent as the `Content-Type` of the request, and that is how the API finds out the type. The SDK does **not** read it from the `type` of a `Blob`.
* It must be exactly one of the accepted types, with no parameters such as `; charset=...`.
* The first bytes of the file must match the type. A PNG declared as `image/jpeg` is refused.
* Do not pass `application/json` as `contentType`: the API reads it as URL mode and responds `media_source_url_invalid`.

### Ask Routa to download a URL

```ts theme={null}
const media = await routa.media.upload({
  sourceUrl: 'https://example.com/photo.png',
})
```

Routa downloads a public `http` or `https` URL and stores the file. The SDK sends it as JSON, in `{ "source_url": ... }`.

### The result

The upload is synchronous: when it finishes, the `Media` already has `status: 'ready'` and a signed `url`, valid for 15 minutes. `retrieve()` issues a new URL.

Keep the `id`. From 0.5.0, `messages.send()` accepts it as the [media header of a template](https://docs.routa.chat/en/sdk/messages.md#send-a-template), in `headerParameter.mediaId`. No method sends a media message yet: see [what the SDK does not support yet](https://docs.routa.chat/en/sdk/overview.md#not-supported-yet).

## `retrieve`

```ts theme={null}
import { toMediaId } from '@routa-chat/sdk'

const media = await routa.media.retrieve(toMediaId('med_...'))

if (media.status === 'ready' && media.url) {
  const file = await fetch(media.url)
}
```

| Field | Type | Description |
| - | - | - |
| `id` | `MediaId` | ID (`med_...`). |
| `contentType` | `string` | File type. |
| `status` | `'pending' \| 'ready' \| 'unavailable'` | `ready` when a signed URL can be issued. |
| `url` | `string \| null` | Fresh signed URL. Only filled in when the status is `ready`. |

## Errors

The SDK **does not check** the size or the type of the file. The API decides, and a rule copied into the SDK would go stale. A refused upload throws:

| Error | `code` | When |
| - | - | - |
| `RoutaInvalidRequestError` (`422`) | `media_content_type_rejected` | The `contentType` is not an accepted type, or the first bytes do not match it. |
| `RoutaInvalidRequestError` (`422`) | `media_size_limit_exceeded` | The file is over the limit of its type. |
| `RoutaInvalidRequestError` (`422`) | `media_source_url_invalid` | The `sourceUrl` is empty or is not a usable URL. |
| `RoutaInvalidRequestError` (`422`) | `media_source_blocked` | The `sourceUrl` points to an address Routa refuses to download, such as a private network. |
| `RoutaInvalidRequestError` (`422`) | `media_source_unreachable` | Routa could not download the `sourceUrl`. |
| Base `RoutaApiError` (`413`) | `payload_too_large` | The body is over 100 MiB. It is not retried. |
| `RoutaInvalidRequestError` (`403`) | `insufficient_scope` | The key lacks `media:write`. |

None of these errors sets `param`. The `413` arrives as a base `RoutaApiError` because the SDK has no subclass for it.

```ts theme={null}
import { RoutaApiError, RoutaInvalidRequestError } from '@routa-chat/sdk'

try {
  await routa.media.upload({ file: bytes, contentType: 'image/png' })
} catch (error) {
  if (error instanceof RoutaInvalidRequestError && error.code === 'media_size_limit_exceeded') {
    console.error('File too large for this type.')
  } else if (error instanceof RoutaApiError && error.statusCode === 413) {
    console.error('Body over 100 MiB.')
  } else {
    throw error
  }
}
```

## Not idempotent

`POST /v1/media` does not read `Idempotency-Key`, so the SDK does not send one. The client still retries a network failure or a `5xx`. If the first attempt had already stored the file and only the response was lost, the retry stores a second copy, with another `id`.

> [!WARNING]
>
> Set `maxRetries: 0` on the client if a duplicate copy matters more to you than resilience to an unstable connection. See [Configuration](https://docs.routa.chat/en/sdk/configuration.md#idempotency).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.