-1

I want to send a json file to keen.io in their documentation they use the following command

curl "https://api.keen.io/3.0/projects/PROJECT_ID/events/EVENT_COLLECTION?api_key=WRITE_KEY" -H "Content-Type: application/json" -d @purchase1.json

I am thinking how can I use this to work with python

Imo
  • 1,455
  • 4
  • 28
  • 53
  • Possible duplicate of [Calling an external command in Python](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – Yaroslav Admin Oct 09 '15 at 08:52
  • Do you want to do this use a Python module? or just run a GNU program like `curl` use Python? – Remi Guan Oct 09 '15 at 08:59
  • I tried using sub process I get an error message File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory – Imo Oct 09 '15 at 09:01
  • It means that `curl` didn't found the file(your json file). Try use the full path like `/home/user/foobar/purchase1.json` – Remi Guan Oct 09 '15 at 09:03
  • And you also can try `os.system()` function in `os` module. – Remi Guan Oct 09 '15 at 09:04

3 Answers3

1

You could use the requests library to achieve this.

import requests
uri = "https://api.keen.io/3.0/projects/{}/events/{}?api_key={}".format(PROJECT_ID, EVENT_COLLECTION, API_KEY)
json_payload = open('purchase1.json', 'rb').read()
requests.post(uri, json=json_payload)

You can read through their documentation for more information.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46
  • 2
    First, I don't think that json file needs open in binary mode. Second, I recommend use `with` open the file. – Remi Guan Oct 09 '15 at 09:01
1

you can use subprocess module to run the curl command using subprocess.call() method.

eg :

 subprocess.call('curl "https://api.keen.io/3.0/projects/PROJECT_ID/events/EVENT_COLLECTION?api_key=WRITE_KEY" -H "Content-Type: application/json" -d @purchase1.json', shell=true)
Srikanth Bhandary
  • 1,707
  • 3
  • 19
  • 34
0

You can also use subprocess to execute the command and then catch the output https://docs.python.org/2/library/subprocess.html

Dirk N
  • 717
  • 3
  • 9
  • 23