Forums

I cannot connect to graph.facebook.com using requests module. Code 401 returned

I am very sorry for the unreadability of the data variable but that doesn't matter much. I am trying to automate the sending of messages using the WhatsApp cloud API and Python's request module.

url = "https://graph.facebook.com/v14.0/<ID>/messages"
    headers = CaseInsensitiveDict()
    headers["Authorization"] = "Bearer <ACCESS_TOKEN>"
    headers["Content-Type"] = "application/json"
    data = '{ "messaging_product": "whatsapp", "to": "91' + str(number) + '", "type": "template", "template": { "name": "notifier_message", "language": { "code": "en_US" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "text": "' + salesman + '" }, { "type": "text", "text": "' + str(amount) + '" } ] } ] } }'
    resp = requests.post(url, headers=headers, data=data)

When I try to use this same code on my local PC's Django server, it works like charm, but it isn't working on pythonanywhere's Django servers. amount, salesman and number are all variables which I am extracting from a form on the website. When I am run this on pythonanywhere and check the value of the variable resp.status_code, it gives me just 401.

After some research, I found that free users can only connect to outer websites using https, but also found a whitelist which listed .facebook.com. I am not sure what this means, and if I can connect to graph.facebook.com or not.

I would be very grateful for any kind of help you maybe able to provide, maybe I have a code issue, or maybe the bitter reality that what I want might not be possible here. Thanks a lot!

I see graph.facebook.com is already on our whitelist, so it should work. 401 status usually means that the client is unauthorized, though.

Thanks a lottttt. I received a alert by facebook that my token has been invalidated because it was found on GitHub (I suppose someone stupid put it in there :P ). So I created a new token and it works!

Excellent!