Home > database >  Python- GET request from user input
Python- GET request from user input

Time:10-08

I am trying to make a POST request in python3 without hardcoding, what I am trying is:

  1. after running the program user will be prompted to provide informations.
  2. these information will be passed to the 'payload' and 'header' block.

I wrote this code:

import requests
import json
import pprint

url='https://gorest.co.in/public/v1/users'
token = input("Enter your access token: ")
name = input ("Enter full name: ")
gender = input("Enter gender: ")
email = input("Enter email: ")
status: input("Enter status: ")

payload = json.dumps({
    'name': 'name',
    'gender': 'gender',
      'email': 'email',
      'status': 'status'
    }
)

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token)'
}

response = requests.request('POST', url, data=payload, headers=headers)
pprint.pprint(response.json())

Bur receiving error:

{'data': {'message': 'Authentication failed'}, 'meta': None}

CodePudding user response:

it is because here the error is

payload = json.dumps({
    'name': 'name',
    'gender': 'gender',
      'email': 'email',
      'status': 'status'
    }
)

you are passing name = "name" as constant string by putting quotes variable name you can fix this by chancing above code as

payload = json.dumps({
    'name': name,
    'gender': gender,
      'email': email,
      'status': status
    }
)

also change headers to:

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': token
}
  • Related