0

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Neither one is quite working for me. DO they both need to be run in python 2? Is there a way I can look at the json output
@Nick The methods work for both major Python versions.
@Nick For the 2nd method, you can get the response as JSON by calling response.json()
@Nick I think you can use print function for this. I would also like to suggest you go through the documentation of the respective libraries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.