'Converting a CURL into python script

I am trying to convert a Curl POST request into a python script, and i am not getting the desired output, please let me know what i am doing wrong here.

CURL request
 curl -s -w '%{time_starttransfer}\n' --request POST \
       --url http://localhost:81/kris/execute \
       --header 'content-type: application/json' \
       --data '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'

This runs the uptime command in the node for which the ip is provided and returns a JSON output:

{"command":"uptime","output":["{\"body\":\" 17:30:06 up 60 days, 11:23,  1 user,  load average: 0.00, 0.01, 0.05\\n\",\"host\":\"10.0.0.1\"}"]}0.668894

When i try to run the same with python, it fails and never gets the output

Code :

import urllib3
import json

http = urllib3.PoolManager()

payload = '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'
encoded_data = json.dumps(payload)

resp = http.request(
     'POST',
     'http://localhost:81/kris/execute ',
     body=encoded_data,
     headers={'Content-Type': 'application/json'})
print(resp)


Solution 1:[1]

I would recommend you use the requests library. It's higher level than urllib and simpler to use. (For a list of reasons why it's awesome, see this answer.)

Plus it requires only minor changes to your code to work:

import requests

payload = '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'

resp = requests.post(
     'http://localhost:81/kris/execute',
     data=payload,
     headers={'Content-Type': 'application/json'})
print(resp.text)

Note that the method POST is the function instead of a parameter and that is uses the named param data instead of body. It also returns a Response object, so you have to access its text property to get the actual response content.


Also, you don't need to json.dumps your string. That function is used to convert Python objects to JSON strings. The string you're using is already valid JSON, so you should just send that directly.

Solution 2:[2]

Here is an online utility you can check out to convert curl requests to python code.

Curl to python converter

Another alternative is Postman application. There you will have the option to convert curls to code for various languages, in the code section.

It a very good practice to check if the api requests are working by running the curl in postman.

And for your case, here is the code using python requests library.

    import requests

headers = {
    'content-type': 'application/json',
}

data = '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'

response = requests.post('http://localhost:81/kris/execute', headers=headers, data=data)

Hope that helps! Happy Coding!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2