How to use Python to execute a cURL command? How to use Python to execute a cURL command? python python

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 requestsr = 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 requestsurl = '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. It'll 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 requestsheaders = {    'Content-type': 'application/json',}data = '{"text":"Hello, World!"}'response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)


import requestsurl = "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,jsonurl = "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.textprint print req.json # maybe?