希望stackoverflow社区能帮到我。我想在python中使用POST api发送短信,这是我试过的:
>> 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)
我收到以下错误:
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>"
我甚至试过了这个请求URI:
>> response = requests.post('https://api.twilio.com/2010-04-01/Accounts/my-account-sid:my-auth-token/Messages', data=post_data)
仍然是同样的错误: - /
我的uri是错还是POST参数不完整?对于POST api,文档并不是很好: - /
更新: 任何仍在寻找答案的人,您可以查看已接受的答案或更新请求,如下所示:
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'))
答案 0 :(得分:1)
Twilio开发者传道者在这里。
很抱歉,您在这里找不到相关文档。希望我能提供帮助。
您缺少的是您的帐户SID和身份验证令牌作为您的HTTP基本身份验证credentials。正如您request to the Twilio API上的文档所述,您应该能够在URL中提供这些凭据,如下所示:
https://{AccountSid}:{AuthToken}@api.twilio.com/2010-04-01/Accounts
所以你的原始请求应该看起来像这样:
>> response = requests.post('https://{{ account_sid }}:{{ auth_token }}@api.twilio.com/2010-04-01/Accounts/{{ account_sid }}/Messages', data=post_data)
当您使用Python时,您可能会发现使用官方Twilio Python helper library更容易。使用库send an SMS message看起来有点像这样:
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)
这样,您就不必担心对请求进行身份验证,TwilioRestClient
对象会为您执行此操作。