Nick
Nick

Reputation: 70

Curl command through python

I am attempting to programmatically run a curl command. I have os imported, but I can not seem to get effective results with the following code. (Dummy hackathon API data)

os.system('curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "{\"merchant_id\": \"57cf75cea73e494d8675ec49\",\"medium\": \"balance\",\"purchase_date\": \"2017-01-22\",\"amount\": 1,\"description\": \"string\"}" "http://api.reimaginebanking.com/accounts/5883e3351756fc834d8ebe89/purchases?key=b84d3a153e2842b8465bcc4fde3d1839"')

For some odd reason, the above code does not effectively just run a system command.

Upvotes: 0

Views: 576

Answers (1)

Kshitij Saraogi
Kshitij Saraogi

Reputation: 7639

Method 01:

You can use the subprocess module to execute a shell command from Python.

Example:

>>> import subprocess
>>> cmd = '''curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "{\"merchant_id\": \"57cf75cea73e494d8675ec49\",\"medium\": \"balance\",\"purchase_date\": \"2017-01-22\",\"amount\": 1,\"description\": \"string\"}" "http://api.reimaginebanking.com/accounts/5883e3351756fc834d8ebe89/purchases?key=b84d3a153e2842b8465bcc4fde3d1839"'''
>>> args = cmd.split()
>>> subprocess.call(args)

If you can using Python version 3.5(or later), you can use the subprocess.run command instead.

METHOD 02:

Use requests if you:
- Want to write a Pythonic code for the POST request. - Prefer clean and extensible code!

>>> import requests
>>> headers = {"Content-Type": "application/json", "Accept": "application/json"}
>>> data = {"merchant_id\": "57cf75cea73e494d8675ec49\","medium\": "balance\", "purchase_date\": "2017-01-22\","amount\": 1, "description\": "string\"}
>>> url = "http://api.reimaginebanking.com/accounts/5883e3351756fc834d8ebe89/purchases?key=b84d3a153e2842b8465bcc4fde3d1839"
>>> response = requests.post(url, data=data, headers=headers)

Upvotes: 1

Related Questions