Tutorial

How to Send WhatsApp Messages with Python

Any statistics or percentages in this article are general industry figures or illustrations, not QuackAPI measurements or promises. Results depend on your audience, consent and sending patterns. QuackAPI connects to WhatsApp as a linked device (an unofficial method), so read our risk and acceptable use policy before sending.

February 15, 20265 min read

Prerequisites & Installation

Before you start sending WhatsApp messages with Python, you need to install the requests library and set up your QuackAPI account. The requests library makes HTTP calls simple and intuitive.

Make sure you have Python 3.7 or higher installed on your system. You can verify your Python version by running python --version in your terminal.

bash
pip install requests

Getting Your API Key

After creating your QuackAPI account, navigate to your Profile Settings page. Your unique API key starts with wa_ and is used to authenticate all API requests.

Store your API key securely as an environment variable. Never hardcode API keys directly in your source code or commit them to version control.

python
import os

API_KEY = os.environ.get("QUACKAPI_API_KEY")
BASE_URL = "https://quackapi.com/v1/messages/send"

Sending Text Messages

The simplest message type is a plain text message. You need to specify the device ID, recipient phone number in international format, the message content, and the message type.

python
import requests

headers = {
    "Content-Type": "application/json",
    "x-api-key": API_KEY
}

payload = {
    "deviceId": 1,
    "to": "923001234567",
    "content": "Hello from Python!",
    "type": "text"
}

response = requests.post(BASE_URL, json=payload, headers=headers)
print(response.json())

Sending Images and Documents

QuackAPI supports sending images with optional captions, as well as PDF and other document files. For images, set the type to image and provide the image URL in the content field. For documents, use the pdf type and include a filename.

python
# Send an image with caption
image_payload = {
    "deviceId": 1,
    "to": "923001234567",
    "content": "https://example.com/photo.jpg",
    "type": "image",
    "caption": "Check out this photo!"
}
requests.post(BASE_URL, json=image_payload, headers=headers)

# Send a PDF document
doc_payload = {
    "deviceId": 1,
    "to": "923001234567",
    "content": "https://example.com/invoice.pdf",
    "type": "pdf",
    "filename": "invoice.pdf"
}
requests.post(BASE_URL, json=doc_payload, headers=headers)

Error Handling

Production applications should always include proper error handling. Check the HTTP status code and parse the error response to handle common issues like invalid API keys, offline devices, or rate limiting.

python
try:
    response = requests.post(BASE_URL, json=payload, headers=headers)
    response.raise_for_status()
    result = response.json()
    print(f"Message sent! ID: {result['id']}")
except requests.exceptions.HTTPError as e:
    error_data = e.response.json()
    print(f"API Error: {error_data.get('message', 'Unknown error')}")
except requests.exceptions.ConnectionError:
    print("Failed to connect to the API server")

Complete Working Example

Here is a complete, production-ready Python script that wraps the QuackAPI API in a reusable class. You can import this module into any Python project to start sending WhatsApp messages immediately.

If you are evaluating providers before setting up, see how QuackAPI compares to Twilio for WhatsApp — especially on pricing and whether Meta Business approval is required.

python
import os
import requests

class QuackAPIClient:
    def __init__(self, api_key=None):
        self.api_key = api_key or os.environ.get("QUACKAPI_API_KEY")
        self.base_url = "https://quackapi.com/v1/messages/send"
        self.headers = {
            "Content-Type": "application/json",
            "x-api-key": self.api_key
        }

    def send_text(self, device_id, to, message):
        payload = {"deviceId": device_id, "to": to, "content": message, "type": "text"}
        return self._send(payload)

    def send_image(self, device_id, to, image_url, caption=""):
        payload = {"deviceId": device_id, "to": to, "content": image_url, "type": "image", "caption": caption}
        return self._send(payload)

    def _send(self, payload):
        response = requests.post(self.base_url, json=payload, headers=self.headers)
        response.raise_for_status()
        return response.json()

# Usage
client = QuackAPIClient()
result = client.send_text(1, "923001234567", "Hello from QuackAPI!")
print(result)

Ready to get started?

Send WhatsApp Messages via API — Free

No Meta Business verification. No credit card. Connect your WhatsApp in under 2 minutes and start sending messages through the REST API.

Related Articles