Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to POST contents of JSON file to RESTFUL API with Python using requests module

Okay, I give up. I am trying to post the contents of a file that contains JSON. The contents of the file look like this:


{
     "id”:99999999,
     "orders":[
     {
             "ID”:8383838383,
             "amount":0,
             "slotID":36972026
     },
     {
             "ID”:2929292929,
             "amount":0,
             "slotID":36972026
     },
     {
             "ID”:4747474747,
             "amount":0,
             "slotID":36972026
     }]
}

Here's the code which is probably way off the mark:

#!/usr/bin/env python3

import requests
import json

files = {'file': open(‘example.json’, 'rb')}
headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}

r = requests.post('https://api.example.com/api/dir/v1/accounts/9999999/orders', files=files, headers=headers)
like image 776
Jeff F Avatar asked Feb 01 '15 05:02

Jeff F


1 Answers

This should work, but it's meant for very large files.

import requests

url = 'https://api.example.com/api/dir/v1/accounts/9999999/orders'
headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
r = requests.post(url, data=open('example.json', 'rb'), headers=headers)

If you want to send a smaller file, send it as a string.

contents = open('example.json', 'rb').read()
r = requests.post(url, data=contents, headers=headers)
like image 161
jack Avatar answered Oct 04 '22 00:10

jack