0
votes

Hoping the stackoverflow community will help me out. I want to send sms using the POST api in python, here's what i have tried:

>> post_data = {"To": "my-phone-number", "From": TWILIO_NUMBER, "Body": "Test message", "AccountSid": "my-account-sid", "AuthToken":"my-auth-token"}
>> import requests
>> response = requests.post('https://api.twilio.com/2010-04-01/Accounts/my-account-sid/Messages', data=post_data)

I get the following error:

response.content     
"<?xml version='1.0' encoding='UTF-8'?>\n<TwilioResponse><RestException><Code>20003</Code><Detail>Your AccountSid or AuthToken was incorrect.</Detail><Message>Authentication Error - No credentials provided</Message><MoreInfo>https://www.twilio.com/docs/errors/20003</MoreInfo><Status>401</Status></RestException></TwilioResponse>"

I even tried this request URI:

>> response = requests.post('https://api.twilio.com/2010-04-01/Accounts/my-account-sid:my-auth-token/Messages', data=post_data)

Still the same error :-/

Is my uri wrong or the POST parameters incomplete ? Documentation is not great honestly for the POST api :-/

Update: Anyone who is still looking for answers, you can either see the accepted answer or update the request as shown below:

response = requests.post('https://api.twilio.com/2010-04-01/Accounts/my-account-sid/Messages', data=post_data, auth=('my-account-sid', 'my-auth-token'))
1

1 Answers

1
votes

Twilio developer evangelist here.

Sorry you didn't find the documentation great here. Hopefully I can help.

What you are missing is your account SID and auth token as your HTTP Basic Authentication credentials. As the documentation on your request to the Twilio API says, you should be able to provide those credentials in the URL like this:

https://{AccountSid}:{AuthToken}@api.twilio.com/2010-04-01/Accounts

So your original request should look a bit like this:

>> response = requests.post('https://{{ account_sid }}:{{ auth_token }}@api.twilio.com/2010-04-01/Accounts/{{ account_sid }}/Messages', data=post_data)

As you are using Python, you might find it easier to use the official Twilio Python helper library. To send an SMS message using the library looks a bit like this:

from twilio.rest import TwilioRestClient

account_sid = "{{ account_sid }}"
auth_token  = "{{ auth_token }}"

client = TwilioRestClient(account_sid, auth_token)

message = client.messages.create(body="Hello from Python",
    to= MY_PHONE_NUMBER,
    from_= MY_TWILIO_NUMBER)

This way, you don't have to worry about authenticating the request, the TwilioRestClient object will do that for you.