Reputation: 1608
I'm running MicroPython on an ESP8266. The code should send an SMS HTTP POST request to Twilio's restAPI. I tried to get it working with urequests. but I keep getting a 401 UNAUTHORIZED response. Please some advise. The code:
import urequests
def send_sms():
twilio_account_sid = "{AcctSID}"
twilio_auth_token = "{AuthToken}"
from_phn_nbr = "+{FromPhoneNbr}"
to_phn_nbr = "+{ToPhoneNbr"))
twilio_proto = "https://"
twilio_host = "api.twilio.com"
twilio_path = "/2010-04-01/Accounts/{AcctSID}/Messages"
twilio_url = twilio_proto + twilio_host + twilio_path
twilio_data = "'From': '{from_phn_nbr}', \
'To': '{to_phn_nbr}', \
'Body': 'Hai'"
twilio_headers = {
'Authorization': 'Basic {AcctSID}:{AuthToken}',
'Content-Type': 'application/x-www-form-urlencoded',
'WWW - Authenticate': 'Basic realm = "Twilio API'
}
try:
resp = urequests.post(url=twilio_url,
data=twilio_data,
headers=twilio_headers)
print(resp.status_code, resp.reason)
except Exception as exc:
print("\nException occured.")
sys.print_exceptin(exc)
Upvotes: 1
Views: 416
Reputation: 1608
@dentex
Using Postman:
Past 'Authorization' value into your code like this:
twilio_headers = {
'Authorization': 'Basic QUMxMmZhNzFlYzU5MzZkNzYyMDYzNWM2Njg1NzNlZWNkNDo2OTBiY2Q5OTA2MDc3NmIzYmQ0NzgwOGE5ZTc2NmM5Yg==',
'Content-Type': 'application/x-www-form-urlencoded',
'WWW-Authenticate': 'Basic realm = Twilio API'
}
Upvotes: 0
Reputation: 73090
Twilio developer evangelist here.
I don't know the urequests
library, but when using HTTP basic authentication it is not enough to simply concatenate the username, a colon, and a password. You need to base 64 encode that concatenated string too.
That's all I can think of from your implementation. Let me know if it helps.
Upvotes: 2