0

I want to pass a randomly generated password to my payload. This is what I have-

import requests
import json
import random
import string

#generate 12 character password
alphabet = string.ascii_letters + string.digits + '!@#%^*()'
newpassword = ''.join(random.choice(alphabet) for i in range(12))

url = "https://www.example.com"
payload = "{\n    \"id\": 123,\n    \"name\": \"John\",\n  \"itemValue\": "+newpassword+" \n}"
headers = {
    'Content-Type': 'application/json',
}
response = requests.put(url, headers=headers, data=json.dumps(payload))
print(response.text)

I'm not getting the desired output because it is not taking the new password string correctly. Please advise.

4
  • I get the following error- { "message": "An error has occurred." } Commented Feb 6, 2021 at 6:40
  • So you are bombarding a website with a randomly generated password thinking to break someones login? Wish this website has a captcha. Commented Feb 6, 2021 at 6:46
  • No, I'm trying to automate updating the password in a vault for security reasons. Commented Feb 6, 2021 at 7:06
  • I would suggest that first check the status code of your response. If it is not expected one (lets say 200), then print response.reason. Here you will get the complete error message Commented Feb 6, 2021 at 7:15

1 Answer 1

1

your payload is already a JSON string, so there's no need to call json.dumps(payload) , just use:

response = requests.put(url, headers=headers, data=payload)

calling json.dumps is needed when your payload is not a JSON string. for example:

payload = {"id": 123, "name": "John", "itemValue": newpassword}
requests.put(url, headers=headers, data=json.dumps(payload))

Also, you need to surround newpassword with quotes:

payload =  "{\n    \"id\": 123,\n    \"name\": \"John\",\n"
payload += "\"itemValue\": \"" + newpassword + "\" \n}"

In order to test it I changed your url to "https://httpbin.org/put" and it works fine. the output is:

{
  "args": {},
  "data": "{\n    \"id\": 123,\n    \"name\": \"John\",\n  \"itemValue\": \"Vj1YsqPRF3RC\" \n}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "69",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.25.1",
    "X-Amzn-Trace-Id": "Root=1-601e4aa5-2ec60b9839ba899e2cf3e0c9"
  },
  "json": {
    "id": 123,
    "itemValue": "Vj1YsqPRF3RC",
    "name": "John"
  },
  "origin": "13.110.54.43",
  "url": "https://httpbin.org/post"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.