ben olsen
ben olsen

Reputation: 703

Curl to Python Request - Json

I would like to convert this Curl code into Python request.

curl -X POST https://KEY:[email protected]/api/v1/products.xml -F 
"product[name]=Test" -F "product[product_type]=digital" -F 
"product[price]=12.50" -F "product[attachment]=@/filepath.png"

this is what I have but I am getting an 500 Error

    from requests_oauthlib import OAuth1Session
    import requests
    from requests_oauthlib import OAuth1
    import json
    from oauthlib.oauth1 import SIGNATURE_TYPE_QUERY, SIGNATURE_TYPE_BODY
    from requests_toolbelt import MultipartEncoder

    url = 'https://KEY:[email protected]/api/v1/products' # Yes i did put Key and secret 
    headers = {"Accept": "application/json"}    
    payload = {'product[name]': 'test','product[product_type]': 'digital','product[price]': '23','product[attachment]': ('C:\Users\APPE\Desktop\SendOWL\\audi.jpg', open('C:\Users\APPE\Desktop\SendOWL\\audi.jpg', 'rb'),)}


    result = requests.post(url,headers=headers, params=payload)

Upvotes: 2

Views: 814

Answers (1)

t.m.adam
t.m.adam

Reputation: 15376

  • In curl, the -F or --form parameter is used to post multipart form data (files). In requests you can post files with the files parameter.

  • In requests, the params parameter is used for query string data. If you want to send your data in the body of the POST request, you should use the data parameter.

  • For basic authentication you can just use the auth parameter.

So, your python code should look something like this,

import requests

url = 'https://www.sendowl.com/api/v1/products.xml' 
headers = {"Accept": "application/json"}   
auth = ('KEY', 'SECRET') 
data = {'product[name]':'test', 'product[product_type]':'digital', 'product[price]':'23'}
files = {'product[attachment]': open('C:\Users\APPE\Desktop\SendOWL\\audi.jpg', 'rb')}
r = requests.post(url, auth=auth, headers=headers, data=data, files=files)

print(r.text)

Upvotes: 2

Related Questions