Karthik
Karthik

Reputation: 363

Converting cURL to Python Requests error

I'm trying to convert the cURL to Python request but doesn't work.

cURL: curl -kv -H 'Content-Type: application/json' 'https://IP-address/api/v1/login' -d '{"username":"api", "password":"APIPassword"}'

My Python requests code:

import requests

url = "https://IP-address/api/v1/login"

payload = "'{\"username\":\"api\", \"password\":\"APIPassword\"}'"
headers = {
    'Content-Type': "application/json",
    'cache-control': "no-cache",
    }

response = requests.request("GET", url, headers=headers, data=payload, verify=False)

print(response.text)

Which doesn't work and gives me 400 bad requests error.

I tried converting using the https://curl.trillworks.com/

which gives me the following code which doesn't work either.

import requests

url = 'https://IP-address/api/v1/login'

headers = {
    'Content-Type': 'application/json',
}

data = '{"username":"api", "password":"APIPassword"}'

output = requests.get(url, data=data, verify=False)

print (output)

Can anyone please help me identify the issue here.

Edit: I have edited 2nd script to produce output: Which gives 500 Error

Upvotes: 2

Views: 2158

Answers (2)

tanvi
tanvi

Reputation: 628

Another way to make sure you're sending valid JSON in your payload would be to use the json python library to format your payload via json.dumps(), which returns a string representing a json object from an object. This was especially useful to me when I needed to send a nested json object in my payload.

import json 
import requests

url = 'https://sample-url.com' 
headers = { 'Content-Type': 'application/json', 'Authorization': f'{auth_key}'}
payload =   {   "key": "value",
                "key": ["v1", "v2"],
                "key": {
                         "k": "v"
                        }
                ...
            }

r = requests.post(url, headers=headers, data=json.dumps(payload))

Upvotes: 0

t.m.adam
t.m.adam

Reputation: 15376

Use the json parameter in requests.post for json data. It also takes care of the headers.

data = {"username":"api", "password":"APIPassword"}
response = requests.post(url, json=data, verify=False)

Upvotes: 2

Related Questions