# Download WhatsApp media before the URL expires

> Download inbound WhatsApp Cloud API media: media ID to URL to file, the 5-minute URL and 7-day ID limits, and code that streams to S3-compatible storage.

Published 2026-11-02. Z-API Omni team.

A WhatsApp Cloud API media URL works for 5 minutes, and only with your access token in the `Authorization` header. Download inbound media as soon as the webhook arrives. Exchange the media ID for a fresh URL with `GET /MEDIA_ID`, download it with `Authorization: Bearer ACCESS_TOKEN`, and write the bytes to your own storage. After 7 days the media ID itself stops working, and you can no longer download the file.

## The two-step flow

An inbound image, audio, video, document or sticker webhook carries a media object with an `id`, a `mime_type` and a `sha256` ([image messages webhook](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/image)). It may also carry a `url`. Meta says the property has been rolling out "gradually over several weeks, starting November 12, 2025", and "may not be available to you immediately" (same page, accessed 2026-11-02). Until it reaches your app, the `id` is the field to build on.

Step one exchanges the ID for a URL ([Media guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media)):

```bash
curl 'https://graph.facebook.com/v26.0/MEDIA_ID?phone_number_id=PHONE_NUMBER_ID' \
  -H 'Authorization: Bearer ACCESS_TOKEN'
```

The response carries `url`, `mime_type`, `sha256`, `file_size` and `id`. The `phone_number_id` parameter is optional. When you include it, Meta processes the request only if the ID matches the business number the media belongs to. On a server that handles several numbers, that turns a mix-up into an error you can see.

Step two downloads the file from that URL with the same token:

```bash
curl 'MEDIA_URL' \
  -H 'Authorization: Bearer ACCESS_TOKEN' \
  -o 'photo.jpg'
```

The response body is the file, and the `Content-Type` header gives its MIME type.

## How long each piece lives

| Item | Lifetime per Meta (accessed 2026-11-02) |
| --- | --- |
| Media URL from `GET /MEDIA_ID` or the webhook | 5 minutes |
| Media ID received in a webhook | 7 days |
| Media ID returned by your own upload | 30 days |

All three rows come from the [Media guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media). URLs "expire after 5 minutes", and then you query the ID again for a new one. The download section adds that a media ID received via webhook "will only be available to download for 7 days".

The 5-minute limit shapes the architecture. If your webhook handler puts the event on a queue and a worker picks it up ten minutes later, a URL stored with the event is dead. Store the media ID and the business phone number ID. Let the worker call `GET /MEDIA_ID` right before it downloads.

## Why the download fails without the token

Media URLs look like ordinary HTTPS links, so it is tempting to open one in a browser or fetch it with a bare `curl`. Meta's guide rules that out: "Include your access token in the request. If you omit your token, the request will fail" ([Media guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media)). Image tags and browser tabs send no token, so they fail the same way. Don't hand the URL to a browser or a third-party tool. Download it on the server and serve your own copy.

For failures, the Media guide gives an order. A failed download returns `404 Not Found`. Get a new media URL and try again; if that fails too, renew the access token and retry. Both causes surface as the same 404, so script both recovery steps.

## Stream to S3-compatible storage

The function below fetches the URL, streams the download straight into a bucket without writing it to disk, and checks the SHA-256 on the way through. It runs on Python 3.9. The Meta calls use the standard library. The upload needs one package, `pip install boto3`, and boto3 prints a deprecation warning on Python 3.9. Set `S3_ENDPOINT_URL` to point it at MinIO, Cloudflare R2, DigitalOcean Spaces or another S3-compatible service, and leave it unset for AWS.

```python
import base64
import hashlib
import json
import os
import urllib.request

import boto3

GRAPH = "https://graph.facebook.com/v26.0"
TOKEN = os.environ["WHATSAPP_TOKEN"]
BUCKET = os.environ["MEDIA_BUCKET"]

s3 = boto3.client("s3", endpoint_url=os.environ.get("S3_ENDPOINT_URL"))  # None means AWS

def get(url):
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {TOKEN}"})
    return urllib.request.urlopen(req, timeout=30)

class HashingReader:
    """Wraps the HTTP response so the SHA-256 is computed while the file streams."""

    def __init__(self, raw):
        self.raw, self.sha = raw, hashlib.sha256()

    def read(self, size=-1):
        chunk = self.raw.read(size)
        self.sha.update(chunk)
        return chunk

def save_media(media_id, phone_number_id):
    # Step 1: exchange the media ID for a URL that lives for 5 minutes.
    with get(f"{GRAPH}/{media_id}?phone_number_id={phone_number_id}") as r:
        meta = json.load(r)

    # Step 2: download with the same bearer token and stream into the bucket.
    key = f"whatsapp/{phone_number_id}/{media_id}"
    with get(meta["url"]) as r:
        body = HashingReader(r)
        s3.upload_fileobj(body, BUCKET, key, ExtraArgs={"ContentType": meta["mime_type"]})

    digest = body.sha.digest()
    if meta.get("sha256") not in (digest.hex(), base64.b64encode(digest).decode()):
        s3.delete_object(Bucket=BUCKET, Key=key)
        raise ValueError(f"sha256 mismatch for media {media_id}")
    return key
```

The hash check accepts hex or base64 because Meta's webhook example shows a base64 value and the Media guide does not specify an encoding. The object key uses the media ID, so a retried webhook overwrites the same object instead of creating a second one. Save the returned key on the message row, then hand your agents or your CRM your own URL. Call `save_media` from a worker and answer the webhook with 200 first, for the reasons in [Duplicate WhatsApp webhooks in n8n](/academy/articles/n8n-duplicate-webhooks-idempotency/).

## The same flow in n8n

The WhatsApp Business Cloud node in n8n has a Media resource with Upload, Download and Delete operations ([WhatsApp Business Cloud node](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.whatsapp/)). If you prefer to see each call, build it with two HTTP Request nodes:

1. HTTP Request, method GET, URL `https://graph.facebook.com/v26.0/{{ $json.body.entry[0].changes[0].value.messages[0].image.id }}`. Under Authentication choose Generic Credential Type, then Header Auth, with name `Authorization` and value `Bearer ACCESS_TOKEN`.
2. HTTP Request, method GET, URL `{{ $json.url }}`, same credential. Under Options, set Response Format to File and Put Output in Field to `data` ([HTTP Request node](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.httprequest/)).
3. S3 node, File > Upload, reading the binary field `data`. The S3 node targets non-AWS services such as MinIO, Wasabi and DigitalOcean Spaces; AWS has its own node ([S3 node](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.s3/)).

Change `image` in the step 1 path to `audio`, `video`, `document` or `sticker` to match the message type, or read the type from `messages[0].type` first. Keep steps 1 and 2 back to back. A Wait node between them, or a manual re-run of step 2 an hour later, hits the 5-minute limit.

## Media larger than Meta will deliver

When a customer sends a file over 100MB, you get no file. Meta sends a webhook with error code `131052` instead and suggests telling the customer the file is too large ([Media guide](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media)). Type and size limits for sending are in [WhatsApp media messages: supported types and size limits](/academy/articles/whatsapp-media-messages-supported-types-size-limits/).

*Z-API Omni team*
