Services API Reference
Messages Service
- class whatsapp_sdk.services.messages.MessagesService(http_client, config, phone_number_id)[source]
Bases:
objectService for sending WhatsApp messages.
Handles all message types: text, media, location, contacts, interactive.
- __init__(http_client, config, phone_number_id)[source]
Initialize messages service.
- Parameters:
http_client (HTTPClient) – HTTP client for API requests
config (WhatsAppConfig) – WhatsApp configuration
phone_number_id (str) – WhatsApp Business phone number ID
- send_text(to, body=None, text=None, preview_url=False)[source]
Send a text message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
Examples
# Simple text response = messages.send_text(“+1234567890”, “Hello!”)
# With URL preview response = messages.send_text(
“+1234567890”, “Check out https://example.com”, preview_url=True
)
# Using TextMessage model msg = TextMessage(body=”Hello!”, preview_url=True) response = messages.send_text(“+1234567890”, text=msg)
- send_image(to, image, caption=None)[source]
Send an image message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
Examples
# Using media ID response = messages.send_image(“+1234567890”, “media_id_123”)
# Using URL with caption response = messages.send_image(
“+1234567890”, “https://example.com/image.jpg”, caption=”Look at this!”
)
# Using ImageMessage model img = ImageMessage(link=”https://example.com/pic.jpg”, caption=”Nice!”) response = messages.send_image(“+1234567890”, img)
- send_document(to, document, caption=None, filename=None)[source]
Send a document message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
- send_audio(to, audio)[source]
Send an audio message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
- send_video(to, video, caption=None)[source]
Send a video message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
- send_sticker(to, sticker)[source]
Send a sticker message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
- send_location(to, latitude, longitude, name=None, address=None)[source]
Send a location message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
Examples
# Basic location response = messages.send_location(
“+1234567890”, 37.4847, -122.1477
)
# With name and address response = messages.send_location(
“+1234567890”, 37.4847, -122.1477, name=”Meta Headquarters”, address=”1 Hacker Way, Menlo Park, CA”
)
- send_contact(to, contacts)[source]
Send contact information.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
Examples
# Using Contact model from whatsapp_sdk.models import Contact, Name, Phone
- contact = Contact(
- name=Name(
formatted_name=”John Doe”, first_name=”John”, last_name=”Doe”
), phones=[Phone(phone=”+1234567890”, type=”MOBILE”)]
) response = messages.send_contact(“+1234567890”, [contact])
- send_interactive(to, interactive)[source]
Send an interactive message with buttons or lists.
- Parameters:
to (str) – Recipient’s WhatsApp phone number
interactive (InteractiveMessage | Dict[str, Any]) – InteractiveMessage object or dict
- Returns:
MessageResponse with message ID and status
- Return type:
Examples
# Button message from whatsapp_sdk.models import (
InteractiveMessage, InteractiveBody, InteractiveAction, Button
)
- interactive = InteractiveMessage(
type=”button”, body=InteractiveBody(text=”Choose an option:”), action=InteractiveAction(
- buttons=[
Button(type=”reply”, reply={“id”: “1”, “title”: “Yes”}), Button(type=”reply”, reply={“id”: “2”, “title”: “No”})
]
)
) response = messages.send_interactive(“+1234567890”, interactive)
- mark_as_read(message_id, typing_indicator=False)[source]
Mark a message as read and optionally show typing indicator.
- Parameters:
- Returns:
MessageResponse confirming the action
- Return type:
Examples
# Mark as read only response = messages.mark_as_read(“wamid.xxx”)
# Mark as read and show typing indicator response = messages.mark_as_read(“wamid.xxx”, typing_indicator=True)
- send_typing_indicator(message_id)[source]
Send typing indicator without marking message as read.
Shows the typing indicator for up to 25 seconds or until a message is sent. Note: This also marks the message as read.
- Parameters:
message_id (str) – WhatsApp message ID to respond to
- Returns:
MessageResponse confirming the action
- Return type:
Example
# Show typing indicator while processing messages.send_typing_indicator(“wamid.xxx”) # Process message… messages.send_text(to, “Response ready!”)
Templates Service
- class whatsapp_sdk.services.templates.TemplatesService(http_client, config, phone_number_id)[source]
Bases:
objectService for managing WhatsApp message templates.
Handles template operations: send, create, list, get, delete, update.
- __init__(http_client, config, phone_number_id)[source]
Initialize templates service.
- Parameters:
http_client (HTTPClient) – HTTP client for API requests
config (WhatsAppConfig) – WhatsApp configuration
phone_number_id (str) – WhatsApp Business phone number ID
- send(to, template_name, language_code='en_US', components=None)[source]
Send a template message.
- Parameters:
- Returns:
MessageResponse with message ID and status
- Return type:
Examples
# Simple template without parameters response = templates.send(
to=”+1234567890”, template_name=”hello_world”, language_code=”en_US”
)
# Template with parameters from whatsapp_sdk.models import TemplateComponent, TemplateParameter
- components = [
- TemplateComponent(
type=”body”, parameters=[
TemplateParameter(type=”text”, text=”John”), TemplateParameter(type=”text”, text=”ABC123”)
]
)
]
- response = templates.send(
to=”+1234567890”, template_name=”order_confirmation”, language_code=”en_US”, components=components
)
# Template with header image components = [
- TemplateComponent(
type=”header”, parameters=[
- TemplateParameter(
type=”image”, image={“link”: “https://example.com/image.jpg”}
)
]
), TemplateComponent(
type=”body”, parameters=[
TemplateParameter(type=”text”, text=”John”)
]
)
]
- create(name, category, language, components, allow_category_change=True)[source]
Create a new message template.
- Parameters:
name (str) – Template name (must be unique)
category (str) – Template category (MARKETING, UTILITY, or AUTHENTICATION)
language (str) – Language code (e.g., en_US)
components (List[Dict[str, Any]]) – Template components (header, body, footer, buttons)
allow_category_change (bool) – Allow automatic category change if needed
- Returns:
TemplateResponse with template ID and status
- Return type:
Examples
# Create a simple template response = templates.create(
name=”welcome_message”, category=”MARKETING”, language=”en_US”, components=[
- {
“type”: “HEADER”, “format”: “TEXT”, “text”: “Welcome to {{1}}!”
}, {
“type”: “BODY”, “text”: “Hi {{1}}, thanks for joining {{2}}. We’re excited to have you!”
}, {
“type”: “FOOTER”, “text”: “Reply STOP to unsubscribe”
}
]
)
# Create template with buttons response = templates.create(
name=”appointment_reminder”, category=”UTILITY”, language=”en_US”, components=[
- {
“type”: “BODY”, “text”: “Your appointment is on {{1}} at {{2}}”
}, {
“type”: “BUTTONS”, “buttons”: [
- {
“type”: “QUICK_REPLY”, “text”: “Confirm”
}, {
“type”: “QUICK_REPLY”, “text”: “Reschedule”
}
]
}
]
)
- list(limit=None, after=None, fields=None)[source]
List all message templates.
- Parameters:
- Returns:
TemplateListResponse with list of templates
- Return type:
Example
# List all templates templates_list = templates.list()
# List with pagination templates_list = templates.list(limit=10)
# Get next page next_page = templates.list(after=templates_list.paging[“cursors”][“after”])
- get(template_id)[source]
Get details of a specific template.
- Parameters:
template_id (str) – Template ID
- Returns:
Template with full details
- Return type:
Example
template = templates.get(“12345678”)
- delete(template_name)[source]
Delete a message template.
- Parameters:
template_name (str) – Name of the template to delete
- Returns:
True if deletion was successful
- Return type:
Example
success = templates.delete(“old_template”)
- update(template_id, components)[source]
Update template components.
Note: Only certain template elements can be updated after creation.
- Parameters:
- Returns:
TemplateResponse with update status
- Return type:
Example
- response = templates.update(
template_id=”12345678”, components=[
- {
“type”: “BODY”, “text”: “Updated message text with {{1}} parameter”
}
]
)
Media Service
- class whatsapp_sdk.services.media.MediaService(http_client, config, phone_number_id)[source]
Bases:
objectService for managing WhatsApp media.
Handles media operations: upload, download, get URL, delete.
- __init__(http_client, config, phone_number_id)[source]
Initialize media service.
- Parameters:
http_client (HTTPClient) – HTTP client for API requests
config (WhatsAppConfig) – WhatsApp configuration
phone_number_id (str) – WhatsApp Business phone number ID
- upload(file_path, mime_type=None)[source]
Upload a media file from local path.
- Parameters:
- Returns:
MediaUploadResponse with media ID
- Raises:
WhatsAppMediaError – If file doesn’t exist or upload fails
- Return type:
Examples
# Upload an image response = media.upload(“/path/to/image.jpg”) media_id = response.id
# Upload with explicit MIME type response = media.upload(
“/path/to/document.pdf”, mime_type=”application/pdf”
)
- upload_from_bytes(file_bytes, mime_type, filename)[source]
Upload media from bytes in memory.
- Parameters:
- Returns:
MediaUploadResponse with media ID
- Return type:
Examples
# Upload from bytes with open(“image.jpg”, “rb”) as f:
file_bytes = f.read()
- response = media.upload_from_bytes(
file_bytes=file_bytes, mime_type=”image/jpeg”, filename=”photo.jpg”
)
# Upload generated content import io from PIL import Image
img = Image.new(‘RGB’, (100, 100), color=’red’) img_bytes = io.BytesIO() img.save(img_bytes, format=’JPEG’)
- response = media.upload_from_bytes(
file_bytes=img_bytes.getvalue(), mime_type=”image/jpeg”, filename=”generated.jpg”
)
- get_url(media_id)[source]
Get download URL for a media file.
- Parameters:
media_id (str) – WhatsApp media ID
- Returns:
Download URL (expires after 5 minutes)
- Return type:
Examples
# Get URL for downloading url = media.get_url(“media_id_123”)
# Use the URL to download import requests response = requests.get(url, headers={
“Authorization”: f”Bearer {access_token}”
}) content = response.content
- download(media_id)[source]
Download media file content.
Examples
# Download media content = media.download(“media_id_123”)
# Save to file with open(“downloaded_file.jpg”, “wb”) as f:
f.write(content)
Webhooks Service
- class whatsapp_sdk.services.webhooks.WebhooksService(config)[source]
Bases:
objectService for handling WhatsApp webhooks.
Handles webhook verification, signature validation, and event parsing.
- __init__(config)[source]
Initialize webhooks service.
- Parameters:
config (WhatsAppConfig) – WhatsApp configuration
- verify_token(token)[source]
Verify webhook token during setup.
- Parameters:
token (str) – Token received from webhook verification request
- Returns:
True if token is valid
- Return type:
Example
# In your webhook endpoint if webhooks.verify_token(request.args.get(“hub.verify_token”)):
return request.args.get(“hub.challenge”)
- verify_signature(signature, payload)[source]
Verify webhook signature for security.
- Parameters:
- Returns:
True if signature is valid
- Return type:
Example
# In your webhook endpoint signature = request.headers.get(“X-Hub-Signature-256”) payload = request.get_data()
- if not webhooks.verify_signature(signature, payload):
return “Invalid signature”, 403
- parse_event(payload)[source]
Parse webhook event payload.
- Parameters:
- Returns:
WebhookEvent object with parsed data
- Return type:
Example
# In your webhook endpoint event = webhooks.parse_event(request.json)
- for entry in event.entry:
- for change in entry.changes:
- if change.value.messages:
- for message in change.value.messages:
process_message(message)
- process_message(message)[source]
Process a single message from webhook.
- Parameters:
- Returns:
WebhookMessage object
- Return type:
Example
# Process incoming message webhook_message = webhooks.process_message(message_dict)
- if webhook_message.type == “text”:
print(f”Received text: {webhook_message.text.body}”)
- elif webhook_message.type == “image”:
print(f”Received image: {webhook_message.image.id}”)
- process_status(status)[source]
Process a status update from webhook.
- Parameters:
- Returns:
WebhookStatus object
- Return type:
Example
# Process status update webhook_status = webhooks.process_status(status_dict)
- if webhook_status.status == “delivered”:
print(f”Message {webhook_status.id} was delivered”)
- elif webhook_status.status == “read”:
print(f”Message {webhook_status.id} was read”)
- handle_verification(mode, token, challenge)[source]
Handle webhook verification request.
- Parameters:
- Returns:
Challenge string if verification successful, None otherwise
- Return type:
str | None
Example
# FastAPI example @app.get(“/webhook”) def verify_webhook(
hub_mode: str = Query(None, alias=”hub.mode”), hub_verify_token: str = Query(None, alias=”hub.verify_token”), hub_challenge: str = Query(None, alias=”hub.challenge”)
- ):
- result = webhooks.handle_verification(
hub_mode, hub_verify_token, hub_challenge
) if result:
return result
return Response(status_code=403)
- handle_event(signature, payload)[source]
Handle incoming webhook event with validation.
- Parameters:
- Returns:
Parsed WebhookEvent if valid
- Raises:
WhatsAppWebhookError – If signature is invalid
- Return type:
Example
# FastAPI example @app.post(“/webhook”) async def handle_webhook(
request: Request, x_hub_signature_256: str = Header(None)
- ):
body = await request.body()
- try:
event = webhooks.handle_event(x_hub_signature_256, body) # Process event… return {“status”: “ok”}
- except WhatsAppWebhookError as e:
return Response(status_code=403)
- extract_messages(event)[source]
Extract all messages from a webhook event.
- Parameters:
event (WebhookEvent) – WebhookEvent object
- Returns:
List of WebhookMessage objects
- Return type:
Example
event = webhooks.parse_event(payload) messages = webhooks.extract_messages(event)
- for message in messages:
print(f”From: {message.from_}”) print(f”Type: {message.type}”)
- extract_statuses(event)[source]
Extract all status updates from a webhook event.
- Parameters:
event (WebhookEvent) – WebhookEvent object
- Returns:
List of WebhookStatus objects
- Return type:
Example
event = webhooks.parse_event(payload) statuses = webhooks.extract_statuses(event)
- for status in statuses:
print(f”Message ID: {status.id}”) print(f”Status: {status.status}”)
HTTP Client
The underlying HTTP client provides additional methods for media operations:
- class whatsapp_sdk.http_client.HTTPClient(config)[source]
Bases:
objectSynchronous HTTP client for WhatsApp API requests.
Handles: - Request/response processing - Error handling and retries - Rate limiting - Authentication
- __init__(config)[source]
Initialize HTTP client.
- Parameters:
config (WhatsAppConfig) – WhatsApp configuration
- post(endpoint, json=None, **kwargs)[source]
Make POST request to WhatsApp API.
- Parameters:
- Returns:
Response data as dictionary
- Raises:
WhatsAppAPIError – For API errors
WhatsAppRateLimitError – For rate limit errors
WhatsAppAuthenticationError – For auth errors
- Return type:
- upload_multipart(endpoint, files, data=None, **kwargs)[source]
Make POST request with multipart/form-data for file uploads.
- Parameters:
- Returns:
Response data as dictionary
- Raises:
WhatsAppAPIError – For API errors
WhatsAppRateLimitError – For rate limit errors
WhatsAppAuthenticationError – For auth errors
- Return type:
- download_binary(url, **kwargs)[source]
Download binary content from a URL.
- Parameters:
- Returns:
Binary content as bytes
- Raises:
WhatsAppAPIError – For API errors
- Return type:
- HTTPClient.upload_multipart(endpoint, files, data=None, **kwargs)[source]
Make POST request with multipart/form-data for file uploads.
- Parameters:
- Returns:
Response data as dictionary
- Raises:
WhatsAppAPIError – For API errors
WhatsAppRateLimitError – For rate limit errors
WhatsAppAuthenticationError – For auth errors
- Return type:
Make POST request with multipart/form-data for file uploads.
Used internally by MediaService for uploading files with proper multipart encoding support.
- HTTPClient.download_binary(url, **kwargs)[source]
Download binary content from a URL.
- Parameters:
- Returns:
Binary content as bytes
- Raises:
WhatsAppAPIError – For API errors
- Return type:
Download binary content from a URL.
Used internally by MediaService for downloading media files as binary content with proper error handling and retry logic.