6

I need to send data as json with requests module in Python.

For example:

import json
import requests
f = requests.Session()
data = {
    "from_date": "{}".format(from_date),
    "to_date": "{}".format(to_date),
    "Action": "Search"
}

get_data = f.post(URL, json=data, timeout=30, verify=False)

But after run this code, it showed this error:

get_data = f.post(URL, json=data, timeout=30, verify=False)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 497, in post
return self.request('POST', url, data=data, **kwargs)
TypeError: request() got an unexpected keyword argument 'json'

I'm on Ubuntu 16.04 and my Python version is 2.7.6

How to issue this problem?

DRPK
  • 2,023
  • 1
  • 14
  • 27
mySun
  • 1,550
  • 5
  • 32
  • 52

2 Answers2

16

your data is a dict, you should convert it to json format like this:

json.dumps(data)

import json
import requests
f = requests.Session()

headers = {'content-type': 'application/json'}
my_data = {
"from_date": "{}".format(from_date),
"to_date": "{}".format(to_date),
"Action": "Search"
 }

get_data = f.post(URL, data=json.dumps(my_data), timeout=30, headers=headers, verify=False)
DRPK
  • 2,023
  • 1
  • 14
  • 27
  • Hi, Don't work json.dumps(my_data). after get data show `response [415]`. – mySun Oct 28 '17 at 16:21
  • @mySun : 415 means that the media type is unsupported. The most likely case is that you are either missing the Content-Type header in your request, or it's incorrect.( not for my code!! or any bug!!! that website or url do not get your json format ) my code is correct! i answered your question about unexpected keyword argument 'json' plz tick me :) – DRPK Oct 28 '17 at 16:26
  • I run my code on my Laptop and works easily, But after upload on server show this error ! :-( – mySun Oct 28 '17 at 16:28
  • @mySun: try it again! i added headers ... tag – DRPK Oct 28 '17 at 16:32
  • Thank you so much for help me :-) – mySun Oct 28 '17 at 16:38
  • As of requests 2.4.2, released 3 years ago, you can use the `json` argument to have the data encoded to JSON for you (plus have the right content type header set). The OP simply has an older version. – Martijn Pieters Oct 28 '17 at 16:59
  • See http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests – Martijn Pieters Oct 28 '17 at 17:01
0

Looking here I suspect that your json keyword should actually be data, i.e.,

get_data = f.post(URL, data=data, timeout=30, verify=False)
DRPK
  • 2,023
  • 1
  • 14
  • 27
Kyloe Graves
  • 19
  • 1
  • 3