Hello,
I am currently developing an application using FastAPI that sends messages via the WhatsApp Business API. While the application works perfectly on my local machine, I am encountering issues when I deploy it to PythonAnywhere.
Here are some details about my setup:
Environment: I am using a free account on PythonAnywhere. Code: The POST request is made using the requests library, and I have verified that the token and phone number ID are correct:
from fastapi import APIRouter, Depends
from configs import verify_api_key, WPP_TOKEN, PHONE_NUMBER_ID
from pydantic import BaseModel
import requests
import logging
router = APIRouter()
class Target(BaseModel):
phone_number: str
url = f'https://graph.facebook.com/v20.0/{PHONE_NUMBER_ID}/messages'
headers = {
'Authorization': f'Bearer {WPP_TOKEN}',
'Content-Type': 'application/json',
}
@router.post("/")
async def root(target: Target, api_key: str = Depends(verify_api_key)):
logging.info(f"Enviando mensagem para {target.phone_number}")
data = {
'messaging_product': 'whatsapp',
'to': target.phone_number,
'text': {
'body': 'Olá! Esta é uma mensagem enviada via API do WhatsApp.'
}
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
return response.json()
except Exception as e:
logging.error(f"Ocorreu um erro inesperado: {str(e)}")
return {"error": "Erro inesperado."}
Error Message: The error I am receiving is:
Ocorreu um erro inesperado: HTTPSConnectionPool(host='graph.facebook.com', port=443): Max retries exceeded with url: /v20.0/****number*****/messages (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x728590484640>: Failed to establish a new connection: [Errno 101] Network is unreachable'))
I suspect that there may be restrictions on outgoing connections from my PythonAnywhere account, especially since the code runs smoothly locally.
Could someone please confirm if there are any limitations on free accounts regarding outgoing connections to the WhatsApp API? If so, what steps can I take to resolve this issue?
Thank you for your assistance!
Best regards, Rodrigo