Jessica Chambers
Jessica Chambers

Reputation: 1316

Python Requests: Passing Auth token

I'm using MailJet's SMS API and I'm having trouble getting the token/authentification syntax right.

In cURL, the request should look like (cf Docs):

curl -s \
     -X POST \
     --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
     https://api.mailjet.com/v4/sms-send \
     -H 'Content-Type: application/json' \
     -d '{
        "From": "MJPilot",
        "To": "+33600000000",
        "Text": "Have a nice SMS flight with Mailjet!"
      }'

But I don't know how to convert this phrasing to Python, this is my current idea:

import requests, json

headers = {
    'Authorization': 'Bearer ' + 'MYTOKEN',
    'Content-Type': 'application/json',
}
tel='XXXX'
message = "this is a message"
payload= {"From":"Me", "To":tel, "message":message}
r_sms = requests.post("https://api.mailjet.com/v4/sms-send", data=payload, headers=headers)
print("SMS SENT" + str(r_sms.json()))

with the following response:

SMS SENT{'ErrorIdentifier': 'f403ce05-1db3-4c30-ac74-314fa93a9e84', 'ErrorCode': 'mj-0002', 'ErrorMessage': 'Malformed JSON, please review the syntax and properties types.', 'StatusCode': 400}

I know my token is valid because I can run the request correctly via Postman

Upvotes: 0

Views: 673

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

Your payload is json, so the kwarg is json, not data:

r_sms = requests.post("https://api.mailjet.com/v4/sms-send", json=payload, headers=headers)

Also, in your payload, it looks like it should be "Text" not "message"

Upvotes: 1

Related Questions