asp
asp

Reputation: 835

Python equivalent for Curl giving 400 Response

Trying to re-write shell curl to python script with requests module...

My shell script :

#!/bin/bash

ip=$1
url=https://xxx.xx.xx.com
secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
expand=computerStatus


curl --silent -X POST "$url/api/computers/search?expand=$expand" -H "Content-Type: application/json" -H "api-secret-key: $secret" -H "api-version: v1" -d '{"maxItems": 10,"searchCriteria": [{"fieldName": "hostName","stringTest": "equal", "stringValue": "'"$ip"'"}]}' -k > $file

above works fine in bash.

I am trying to convert to similar python equivalent

What I tried

import json
import requests
import sys

ip = sys.argv[1]

sys_info = []

url=https://xxx.xx.xx.com
secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
expand=computerStatus

headers = {
    'Content-Type': 'application/json',
    'api-secret-key': secret,
    'api-version': 'v1',
}

params = (
    ('expand', 'expand'),
)

data = '{"maxItems": 10,"searchCriteria": [{"fieldName": "hostName","stringTest": "equal", "stringValue": ip}]}'

response = requests.post('https://url/api/computers/search?expand=expand', headers=headers, params=params, data=data)

print(response)

<Response [400]>

I am getting 400 response.. not sure where i am missing in syntax...

Upvotes: 1

Views: 291

Answers (1)

sergenp
sergenp

Reputation: 545

data needs to be a dictionary, try this:

data = {
    "maxItems": 10, 
    "searchCriteria": [{"fieldName": "hostName","stringTest": "equal", "stringValue": ip}]
    }

Also convert params to a dictionary as well:

 params = {"expand" : expand}

And when posting:

response = requests.post(f'https://{url}/api/computers/search', headers=headers, params=params, data=data)

### or alternatively you can

response = requests.post(f'https://{url}/api/computers/search?expand={expand}', headers=headers, data=data)

Upvotes: 1

Related Questions