paus paus - 4 months ago 108
Python Question

How to proceed multipart/form-data or application/x-www-form-urlencoded request using requests module in python?

Our API clients support only multipart/form-data and application/x-www-form-urlencoded format. So, when I try to access their API:

import requests
import json

url = "http://api.client.com/admin/offer"
headers = {"Content-Type": "multipart/form-data", "API-Key": "ffffffffffffffffffffffffffffffffffffffff"}
data = {"Content-Type": "multipart/form-data", "title": "Demo offer", "advertiser": "f4a89a7h1aq", "url": "http://demo.com/", "url_preview": "http://demo.com/", "description": "Bla bla bla", "freshness": "fresh", "total": "2.0", "revenue": "1.8"}
r = requests.post(url, headers=headers, data=json.dumps(data))

print r.text


I get this:

{"status":2,"error":"Submitted wrong data. Check Content-Type header"}


How to overcome this issue?

Thanks!

Answer

Our API clients support only multipart/form-data and application/x-www-form-urlencoded format

Yet you are setting the Content-type header to application/json, which is not multipart/form-data nor application/x-www-form-urlencoded.

Setting the content type in the body of the HTTP request will not help.

It appears that the server does not support JSON. You should try posting the data as a standard form like this:

import requests
import json

url = "http://api.client.com/admin/offer"
headers = {"API-Key": "ffffffffffffffffffffffffffffffffffffffff"}
data = {"title": "Demo offer", "advertiser": "f4a89a7h1aq", "url": "http://demo.com/", "url_preview": "http://demo.com/", "description": "Bla bla bla", "freshness": "fresh", "total": "2.0", "revenue": "1.8"}
r = requests.post(url, headers=headers, data=data)

print r.text

By default requests.post will set the Content-type header to application/x-www-form-urlencoded and will "urlencode" the data in the body of the request. This should work because you state that the server supports application/x-www-form-urlencoded.

Comments