Home > OS >  How can i take data one line at a time from a txt file and use it as a variable to send requests?
How can i take data one line at a time from a txt file and use it as a variable to send requests?

Time:01-08

I'm currently working on a small side-project that i thought was cool. However, I've reached a big road blockage. I'm trying to get it to read a username from a text file and upload it to an API, however i keep getting error code 400 with a server response stating that the username field was empty in the request. I also added a print statement to confirm the credential variable was set correctly, and it was making me think it's a communication error from me to the API. I think another problem may be that i set the content type to "plain/text". I ran Wireshark to see the exact request i made, and it looks like everything is scrunched together. Here is my current code;

import requests
import time

with open('./user.txt', 'r') as f:
    creds = f.read()


print(f"Current User: {creds}")

url = 'http://example.com/api'
data = {f"nickname":"{creds}","password":"{creds}","email":"","referral":"null"}
headers = {'Content-Type': 'text/plain'}

response = requests.post(url, data=data, headers=headers)

I'm pretty new to using the requests library, and so im sorry if this is a bad question to ask, but any help will be really appreciated.

edit; Wireshark states that my request data is "nickname={creds}&password={creds}".

Thanks !

CodePudding user response:

import time
import requests
import json

with open('./user.txt', 'r') as f:
    for line in f:
        creds = line.strip()
        print(f"Current User: {creds}")

        url = 'http://example.com/api'
        data = {f"nickname":"{creds}","password":"{creds}","email":"","referral":"null"}
        headers = {'Content-Type': 'application/json'}

        response = requests.post(url, data=json.dumps(data), headers=headers)
        print(response.status_code)
        print(response.text)

CodePudding user response:

The problem was with my header type! I didn't need to use JSON or plain/text. I used application/x-www-form-urlencoding, which i got from the file's history. The application now reads each username and password, and sends it to the server!

  • Related