Home > Software engineering >  Python requests. TypeError: a bytes-like object is required
Python requests. TypeError: a bytes-like object is required

Time:03-11

I'm trying to create a script that iterates through each row of a CSV and posts to an API call but am getting TypeError: a bytes-like object is required, not 'dict'.

The CSV is only 3 columns. Normally I can pass an object row[2] etc. but I don't understand why is happening here or how to fix it?

Thank you

import csv
import requests
from time import sleep

with open('/Users/me/Downloads/mailgun_test.csv',newline='') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
            files = {
            'from': ('Sender <[email protected]>'),
            'to': str(row[0]),
            'subject': ('Your ' str(row[2]) ' Verificiation Has Expired'),
            'template': ('tpp_expired'),
            'h:X-Mailgun-Variables': ({"company_name": str(row[1]), "verification_file_type": str(row[2])})
            }

            r = requests.post('https://api.mailgun.net/v3/domain/messages', files=files, auth=('api', 'key................'))
            print("=========================")
            print(r)
            print(r.text)
            sleep(2)```

CodePudding user response:

Send the data in the body for the post call. You can refer to the examples in the documentation: https://documentation.mailgun.com/en/latest/quickstart-sending.html#send-via-api

Note: switch over to python (required) language tab in the documentation.

Example from above docs:

def send_simple_message():
    payload = {"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
          "to": ["[email protected]", "YOU@YOUR_DOMAIN_NAME"],
          "subject": "Hello",
          "text": "Testing some Mailgun awesomness!"}
    return requests.post( "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
    auth=("api", "YOUR_API_KEY"),
    data=payload)
  • Related