Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python requests. TypeError: a bytes-like object is required

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 <sender@sender.com>'),
            '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)```

>Solution :

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": ["bar@example.com", "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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading