Upload a file to the WhatsApp Cloud API with a multipart POST to /<PHONE_NUMBER_ID>/media, and Meta returns a media ID. You send that ID in the message’s media object, for example image.id, instead of a public URL. Meta keeps an uploaded ID valid for 30 days, so one upload can serve every send in that period.
The upload call
The endpoint takes multipart/form-data with the file, its MIME type and messaging_product set to whatsapp (Meta media guide, accessed 2026-11-04). This request follows Meta’s example, with placeholders for the number ID and token.
curl 'https://graph.facebook.com/v26.0/PHONE_NUMBER_ID/media' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-F 'messaging_product=whatsapp' \
-F 'file=@/media/template_assets/black_friday_2025.mp4;type=video/mp4'
The response carries only the new ID.
{
"id": "1037543291543636"
}
Meta’s pages disagree on one field. The guide’s parameter table marks file, type and messaging_product as required. Its curl samples put the MIME type on the file part (;type=video/mp4) and send no separate type field. The API reference lists only file and messaging_product, and marks neither as required (Meta media upload reference, accessed 2026-11-04). The script below sends both forms, a type form field and a MIME type on the file part, so it fits either reading.
For the token, Meta points to App Dashboard > WhatsApp > API Setup. Solution Partners need a token with the whatsapp_business_messaging permission. Cloud API access tokens covers the token types to use in production.
Types and size limits
Meta caps images at 5 MB, video and audio at 16 MB, and documents at 100 MB. Images over 4,096 pixels on an edge are rejected. The full format list, stickers included, is in WhatsApp media types and size limits.
Meta calls a “mismatched MIME type (131053)” a common error. Its advice is to check that the file extension matches the actual file type before you upload.
Upload and send from Python
This script uploads a file, sends it as an image by ID, reads the media URL and deletes the file. Meta publishes no Python upload sample, so this code is built from the curl calls and parameter tables. It needs Python 3.9 or later and requests.
# whatsapp_media.py
import mimetypes
import os
import sys
import requests
TOKEN = os.environ["WHATSAPP_TOKEN"]
PHONE_NUMBER_ID = os.environ["PHONE_NUMBER_ID"]
GRAPH_VERSION = os.environ.get("GRAPH_VERSION", "v26.0")
BASE = f"https://graph.facebook.com/{GRAPH_VERSION}"
AUTH = {"Authorization": f"Bearer {TOKEN}"}
class WhatsAppError(Exception):
def __init__(self, status, error):
self.status = status
self.error = error or {}
self.code = self.error.get("code")
super().__init__(f"HTTP {status}, code {self.code}: {self.error.get('message')}")
def check(r):
try:
data = r.json()
except ValueError: # a non-JSON error page
r.raise_for_status()
raise
if not r.ok or "error" in data:
raise WhatsAppError(r.status_code, data.get("error"))
return data
def upload(path, mime=None):
mime = mime or mimetypes.guess_type(path)[0]
if not mime:
raise ValueError(f"no MIME type for {path}, pass one after the file name")
with open(path, "rb") as f:
r = requests.post(
f"{BASE}/{PHONE_NUMBER_ID}/media",
headers=AUTH,
data={"messaging_product": "whatsapp", "type": mime},
files={"file": (os.path.basename(path), f, mime)},
timeout=120,
)
return check(r)["id"]
def send_image(to, media_id, caption=None):
image = {"id": media_id}
if caption:
image["caption"] = caption
payload = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": to,
"type": "image",
"image": image,
}
r = requests.post(
f"{BASE}/{PHONE_NUMBER_ID}/messages", headers=AUTH, json=payload, timeout=10
)
return check(r)["messages"][0]["id"]
def media_info(media_id):
r = requests.get(
f"{BASE}/{media_id}",
headers=AUTH,
params={"phone_number_id": PHONE_NUMBER_ID},
timeout=10,
)
return check(r)
def delete_media(media_id):
r = requests.delete(
f"{BASE}/{media_id}",
headers=AUTH,
params={"phone_number_id": PHONE_NUMBER_ID},
timeout=10,
)
return check(r).get("success") is True
USAGE = (
"usage: whatsapp_media.py upload FILE [MIME] | send TO MEDIA_ID [CAPTION]"
" | info MEDIA_ID | delete MEDIA_ID"
)
if __name__ == "__main__":
args = sys.argv[1:]
if len(args) < 2 or (args[0] == "send" and len(args) < 3):
sys.exit(USAGE)
try:
if args[0] == "upload":
print("media id:", upload(args[1], args[2] if len(args) > 2 else None))
elif args[0] == "send":
caption = args[3] if len(args) > 3 else None
print("accepted:", send_image(args[1], args[2], caption))
elif args[0] == "info":
info = media_info(args[1])
print(info.get("mime_type"), info.get("file_size"), "bytes")
print("sha256:", info.get("sha256"))
print("url, valid for 5 minutes:", info.get("url"))
elif args[0] == "delete":
print("deleted:", delete_media(args[1]))
else:
sys.exit(USAGE)
except WhatsAppError as e:
print(e, file=sys.stderr)
if e.code == 131053:
print("The MIME type does not match the file content.", file=sys.stderr)
sys.exit(1)
Run it with your token and phone number ID in the environment.
pip install requests
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
python whatsapp_media.py upload ./photo.jpg
python whatsapp_media.py send +16505551234 MEDIA_ID "New stock arrived today"
python whatsapp_media.py info MEDIA_ID
python whatsapp_media.py delete MEDIA_ID
mimetypes guesses from the extension, so a renamed file gets the wrong type. Pass the MIME type as the third argument when the guess is wrong or empty. send posts an image, so use it with image uploads only. The send step goes through only inside a customer service window, the 24 hours after the user last wrote to you. Outside it, Meta accepts only templates (error 131047). Send a WhatsApp message with Python adds retries for rate-limit codes.
The image page caps a caption at 1024 characters (Meta image messages, accessed 2026-11-04). The script doesn’t check the length, so trim long captions before you call it.
How long files, IDs and URLs last
| Item | Lifetime | Meta’s wording |
|---|---|---|
| Uploaded file | 30 days | “persist for 30 days, unless they are deleted earlier” |
| Media ID from your upload | 30 days | “Media IDs returned by the API expire after 30 days” |
| Media ID in an inbound webhook | 7 days | “Media IDs in webhooks expire after 7 days” |
Media URL from GET /<MEDIA_ID> |
5 minutes | “after which you must query the ID again to get a new URL” |
Store the upload time next to each ID and upload again before day 30. The media guide states no upload quota per number.
Meta also doesn’t say whether an ID uploaded on one phone number can be sent from another number in the same account. Until you’ve tested it on your own numbers, upload once per sending number.
Retrieve and delete media
GET /<MEDIA_ID> returns url, mime_type, sha256, file_size and id. The optional phone_number_id query parameter makes Meta process the request only if that number matches the one the media was uploaded on. The script always sends it.
The URL needs your token in the Authorization header, and it works for five minutes. If a download returns 404 Not Found, Meta says to fetch a new URL and try again. If that also fails, renew the access token. The full download flow, with inbound media, is in media download URL expired.
DELETE /<MEDIA_ID> removes the file before its 30 days are up and returns {"success": true}. Meta’s guide doesn’t say what a later send of a deleted ID returns.
Send by ID or by link
Meta recommends the ID. The image page labels link as “Only if using hosted media (not recommended)” and says “For better performance, we recommend using id”. The template media page sets a condition for links (Meta template media, accessed 2026-11-04). The asset “must be on a publicly accessible server or the message will fail to send.”
Links also bring caching. Meta’s send guide says the Cloud API “internally caches the asset for 10 minutes” (Meta send messages, accessed 2026-11-04). The cached copy is reused when a later payload carries the same link. If you replace the file behind a URL, append a random query string to force a fresh fetch.
Meta’s request syntax for image messages puts HTML comments inside the JSON, so it doesn’t parse. This is the body of Meta’s example send by ID instead, taken out of its curl call, with the caption text changed.
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "+16505551234",
"type": "image",
"image": {
"id": "1479537139650973",
"caption": "New stock arrived today"
}
}
The Resumable Upload API is for template headers
The Resumable Upload API creates the header_handle for templates with a media header. Meta’s template media page says that to create a template with a media header, “you must upload your media file using the Resumable Upload API”. The returned handle becomes the value of header_handle.
The flow lives on a general Graph API page that doesn’t mention WhatsApp (Meta Resumable Upload API, accessed 2026-11-04). You open a session with POST /<APP_ID>/uploads and the file name, length and type. Then you post the bytes to upload:<UPLOAD_SESSION_ID> with a file_offset header, and get back the handle in h. That page uses Authorization: OAuth with a user access token and accepts PDF, JPEG, PNG and MP4.
Meta doesn’t document whether a /media ID can stand in for header_handle. When you send an approved template, its header takes a media ID or a link, as any other message does. Template creation is covered in create WhatsApp message templates through the API. The same handle flow sets a profile photo in the business profile API.
Z-API Omni team