How to use Python to execute a cURL command?

How to use Python to execute a cURL command?

For sake of simplicity, maybe you should consider using the Requests library.

An example with json response content would be something like:

import requests
r = requests.get(https://github.com/timeline.json)
r.json()

If you look for further information, in the Quickstart section, they have lots of working examples.

EDIT:

For your specific curl translation:

import requests
url = https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
payload = open(request.json)
headers = {content-type: application/json, Accept-Charset: UTF-8}
r = requests.post(url, data=payload, headers=headers)

Just use this website. Itll convert any curl command into Python, Node.js, PHP, R, or Go.

Example:

curl -X POST -H Content-type: application/json --data {text:Hello, World!} https://hooks.slack.com/services/asdfasdfasdf

Becomes this in Python,

import requests

headers = {
    Content-type: application/json,
}

data = {text:Hello, World!}

response = requests.post(https://hooks.slack.com/services/asdfasdfasdf, headers=headers, data=data)

How to use Python to execute a cURL command?

import requests
url = https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
data = requests.get(url).json

maybe?

if you are trying to send a file

files = {request_file: open(request.json, rb)}
r = requests.post(url, files=files)
print r.text, print r.json

ahh thanks @LukasGraf now i better understand what his original code is doing

import requests,json
url = https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
my_json_data = json.load(open(request.json))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

Leave a Reply

Your email address will not be published. Required fields are marked *