Media API
Upload media files once and reuse them across multiple messages using media IDs. Manage media lifecycles with upload, download, metadata retrieval, and deletion capabilities.
Official Documentation: WhatsApp Media API
Overview
The Media API enables efficient media management for WhatsApp Business messaging:
- Upload Media: Upload images, videos, audio, and documents
- Retrieve Metadata: Get media information including URLs, MIME types, and file sizes
- Download Media: Download media files from temporary URLs
- Delete Media: Remove uploaded media to free up storage
Endpoints
POST /{PHONE_NUMBER_ID}/mediaGET /{MEDIA_ID}DELETE /{MEDIA_ID}GET {MEDIA_URL}Important Notes
Quick Start
import WhatsApp from 'meta-cloud-api';
const client = new WhatsApp({ accessToken: process.env.CLOUD_API_ACCESS_TOKEN!, phoneNumberId: Number(process.env.WA_PHONE_NUMBER_ID), businessAcctId: process.env.WA_BUSINESS_ACCOUNT_ID,});
// Upload a fileconst file = new File([Buffer.from('hello')], 'note.txt', { type: 'text/plain'});const upload = await client.media.uploadMedia(file);
// Get media infoconst mediaInfo = await client.media.getMediaById(upload.id);
// Download mediaconst blob = await client.media.downloadMedia(mediaInfo.url);
// Delete mediaawait client.media.deleteMedia(upload.id);Upload Media
Upload media files to WhatsApp for use in messages.
Upload from File Object
// Upload an imageconst imageFile = new File( [await fetch('https://example.com/image.jpg').then(r => r.blob())], 'photo.jpg', { type: 'image/jpeg' });
const result = await client.media.uploadMedia(imageFile);console.log('Media ID:', result.id); // Use this ID in messagesUpload from Buffer
import fs from 'fs';
// Read file from diskconst buffer = fs.readFileSync('/path/to/video.mp4');
// Create File objectconst videoFile = new File([buffer], 'video.mp4', { type: 'video/mp4'});
const result = await client.media.uploadMedia(videoFile);Upload Different Media Types
// Audio fileconst audioFile = new File([audioBuffer], 'voice.ogg', { type: 'audio/ogg; codecs=opus'});await client.media.uploadMedia(audioFile);
// Documentconst docFile = new File([pdfBuffer], 'invoice.pdf', { type: 'application/pdf'});await client.media.uploadMedia(docFile);
// Sticker (WebP format)const stickerFile = new File([webpBuffer], 'sticker.webp', { type: 'image/webp'});await client.media.uploadMedia(stickerFile);Get Media Information
Retrieve metadata about uploaded media files.
const mediaInfo = await client.media.getMediaById('MEDIA_ID');
console.log(mediaInfo);// {// id: 'MEDIA_ID',// url: 'https://lookaside.fbsbx.com/...',// mime_type: 'image/jpeg',// sha256: 'abc123...',// file_size: 123456,// messaging_product: 'whatsapp'// }Download Media
Download media files using temporary URLs.
// Get media info first to retrieve URLconst mediaInfo = await client.media.getMediaById('MEDIA_ID');
// Download the media fileconst blob = await client.media.downloadMedia(mediaInfo.url);
// Save to disk (Node.js)import fs from 'fs';const buffer = Buffer.from(await blob.arrayBuffer());fs.writeFileSync('downloaded_media.jpg', buffer);
// Use in browserconst url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;link.download = 'media.jpg';link.click();Download from Webhook Messages
// When receiving a media message via webhookconst incomingMessage = webhookEvent.entry[0].changes[0].value.messages[0];
if (incomingMessage.type === 'image') { const mediaId = incomingMessage.image.id;
// Get media URL const mediaInfo = await client.media.getMediaById(mediaId);
// Download the image const blob = await client.media.downloadMedia(mediaInfo.url);
// Process the image...}Delete Media
Remove uploaded media files to free up storage space.
// Delete by media IDawait client.media.deleteMedia('MEDIA_ID');
// Delete after sending messageconst upload = await client.media.uploadMedia(file);
await client.messages.image({ to: '15551234567', image: { id: upload.id },});
// Clean up after sendingawait client.media.deleteMedia(upload.id);Response Formats
Upload Response
{ id: 'MEDIA_ID'}Media Info Response
{ id: 'MEDIA_ID', url: 'https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=...', mime_type: 'image/jpeg', sha256: 'abc123...', file_size: 123456, messaging_product: 'whatsapp'}Delete Response
{ success: true}Error Handling
try { const result = await client.media.uploadMedia(file);} catch (error) { if (error.response) { const { code, message } = error.response.data.error;
switch (code) { case 131031: console.error('Media upload failed: File too large'); break; case 131042: console.error('Media upload failed: Invalid file type'); break; case 131051: console.error('Media upload failed: Corrupted file'); break; default: console.error(`Error ${code}: ${message}`); } } else { console.error('Network error:', error.message); }}Best Practices
-
Reuse Media IDs: Upload media once and reuse the ID across multiple messages
const upload = await client.media.uploadMedia(file);// Send to multiple recipientsawait client.messages.image({ to: '1111', image: { id: upload.id } });await client.messages.image({ to: '2222', image: { id: upload.id } });await client.messages.image({ to: '3333', image: { id: upload.id } }); -
Validate Before Upload: Check file size and type before uploading
const MAX_SIZES = {'image': 5 * 1024 * 1024, // 5 MB'video': 16 * 1024 * 1024, // 16 MB'audio': 16 * 1024 * 1024, // 16 MB'document': 100 * 1024 * 1024 // 100 MB};if (file.size > MAX_SIZES['image']) {throw new Error('File too large');} -
Handle Temporary URLs: Download media immediately as URLs expire
const mediaInfo = await client.media.getMediaById(mediaId);// Download immediately - URL expires soonconst blob = await client.media.downloadMedia(mediaInfo.url); -
Clean Up Unused Media: Delete media files you no longer need
// Delete media after it's no longer neededawait client.media.deleteMedia(mediaId);
Supported Media Types
Images
- JPEG (
.jpg,.jpeg) - PNG (
.png) - WebP (
.webp) - for stickers
Videos
- MP4 (
.mp4) - 3GPP (
.3gp)
Audio
- AAC (
.aac) - MP3 (
.mp3) - AMR (
.amr) - OGG (
.ogg, must use Opus codec)
Documents
- PDF (
.pdf) - Microsoft Office files (
.doc,.docx,.xls,.xlsx,.ppt,.pptx) - Text files (
.txt)
Related Documentation
- Messages API - Send media messages using uploaded media IDs
- Webhooks - Receive and download incoming media
- Interactive Messages - Add media to interactive messages
Source Code
View the source code on GitHub: MediaApi.ts