Python Requests Post Json

HTTP Rotating & Static

  • 40 million IPs for all purposes
  • 195+ locations
  • 3 day moneyback guarantee


How to POST JSON data with Python Requests? – Stack …

I need to POST a JSON from a client to a server. I’m using Python 2. 7. 1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get “400 Bad Request”.
Here is my client code:
data = {‘sender’: ‘Alice’,
‘receiver’: ‘Bob’,
‘message’: ‘We did it! ‘}
data_json = (data)
payload = {‘json_payload’: data_json}
r = (“localhost:8080″, data=payload)
Here is the server code.
class Root(object):
def __init__(self, content):
ntent = content
print ntent # this works
exposed = True
def GET(self):
sponse. headers[‘Content-Type’] = ‘application/json’
return (ntent)
def POST(self):
ntent = (())
Any ideas?
ivanleoncz6, 3793 gold badges50 silver badges46 bronze badges
asked Mar 16 ’12 at 7:46
Starting with Requests version 2. 4. 2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:
>>> import requests
>>> r = (”, json={“key”: “value”})
>>> atus_code
>>> ()
{‘args’: {},
‘data’: ‘{“key”: “value”}’,
‘files’: {},
‘form’: {},
‘headers’: {‘Accept’: ‘*/*’,
‘Accept-Encoding’: ‘gzip, deflate’,
‘Connection’: ‘close’,
‘Content-Length’: ’16’,
‘Content-Type’: ‘application/json’,
‘Host’: ”,
‘User-Agent’: ‘python-requests/2. 3 CPython/3. 0’,
‘X-Request-Id’: ‘xx-xx-xx’},
‘json’: {‘key’: ‘value’},
‘origin’: ‘x. x. x’,
‘url’: ”}
Boris8, 1287 gold badges69 silver badges69 bronze badges
answered Oct 13 ’14 at 16:08
Zeyang LinZeyang Lin14. 6k1 gold badge11 silver badges10 bronze badges
It turns out I was missing the header information. The following works:
url = “localhost:8080”
data = {‘sender’: ‘Alice’, ‘receiver’: ‘Bob’, ‘message’: ‘We did it! ‘}
headers = {‘Content-type’: ‘application/json’, ‘Accept’: ‘text/plain’}
r = (url, (data), headers=headers)
ghickman5, 4936 gold badges38 silver badges51 bronze badges
answered Mar 31 ’12 at 3:26
Charles RCharles R14. 8k6 gold badges18 silver badges18 bronze badges
From requests 2. 2 (), the “json” parameter is supported. No need to specify “Content-Type”. So the shorter version:
(”, json={‘test’: ‘cheers’})
answered Dec 10 ’14 at 10:08
ZZYZZY3, 28917 silver badges20 bronze badges
The better way is:
url = ”
data = {
“cardno”: “6248889874650987”,
“systemIdentify”: “s08”,
“sourceChannel”: 12}
resp = (url, json=data)
answered May 4 ’17 at 7:26
ellenellen4774 silver badges5 bronze badges
Which parameter between data / json / files you need to use depends on a request header named Content-Type (you can check this through the developer tools of your browser).
When the Content-Type is application/x-www-form-urlencoded, use data=:
(url, data=json_obj)
When the Content-Type is application/json, you can either just use json= or use data= and set the Content-Type yourself:
(url, json=json_obj)
(url, data=jsonstr, headers={“Content-Type”:”application/json”})
When the Content-Type is multipart/form-data, it’s used to upload files, so use files=:
(url, files=xxxx)
answered Apr 12 ’20 at 7:53
xiaomingxiaoming5894 silver badges10 bronze badges
Works perfectly with python 3. 5+
import requests
r = (“localhost:8080”, json={‘json_payload’: data})
ntent =
return {‘status’: ‘success’, ‘message’: ‘updated’}
answered Jan 20 ’17 at 21:10
It always recommended that we need to have the ability to read the JSON file and parse an object as a request body. We are not going to parse the raw data in the request so the following method will help you to resolve it.
def POST_request():
with open(“FILE PATH”, “r”) as data:
JSON_Body = ()
response = (url=”URL”, data=JSON_Body)
assert atus_code == 200
answered Mar 19 at 14:44
Not the answer you’re looking for? Browse other questions tagged python json python-requests cherrypy or ask your own question.
Python Requests post Method - W3Schools

HTTP & SOCKS Rotating & Static Proxy

  • 72 million IPs for all purposes
  • Worldwide locations
  • 3 day moneyback guarantee


Python Requests post Method – W3Schools

❮ Requests Module
Make a POST request to a web page, and return the response text:
import requestsurl = ”
myobj = {‘somekey’: ‘somevalue’}x = (url, data = myobj)
Run Example »
Definition and Usage
The post() method sends a POST request to the specified url.
The post() method is used when you want to
send some data to the server.
(url, data={key: value}, json={key: value},
args means zero or more of the named arguments in the parameter table below. Example:
(url, data = myobj, timeout=2. 50)
Parameter Values
Try it
Required. The url of the request
Optional. A dictionary, list of tuples, bytes or a file object to send to the specified url
Optional. A JSON object to send to the specified url
Optional. A dictionary of files to send to the specified url
Optional. A Boolean to enable/disable fault
True (allowing redirects)
Optional. A tuple to enable a certain HTTP fault
Optional. A String or Tuple specifying a cert file or fault
Optional. A dictionary of cookies to send to the specified fault
Optional. A dictionary of HTTP headers to send to the specified fault None
Optional. A dictionary of the protocol to the proxy fault
Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True). Default
Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a fault None which means the request will continue
until the connection is closed
Optional. A Boolean or a String indication to verify the servers TLS certificate or fault True
Return Value
A sponse object.
❮ Requests Module
How do I send a POST request as a JSON? - Stack Overflow

How do I send a POST request as a JSON? – Stack Overflow

data = {
‘ids’: [12, 3, 4, 5, 6,… ]}
urllib2. urlopen(“, urllib. urlencode(data))
I want to send a POST request, but one of the fields should be a list of numbers. How can I do that? (JSON? )
asked Mar 17 ’12 at 0:53
If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request…
Python 2. x
import json
import urllib2
‘ids’: [12, 3, 4, 5, 6]}
req = quest(”)
d_header(‘Content-Type’, ‘application/json’)
response = urllib2. urlopen(req, (data))
Python 3. x
If you don’t specify the header, it will be the default application/x-www-form-urlencoded type.
answered Mar 17 ’12 at 1:19
jdijdi84. 7k19 gold badges153 silver badges190 bronze badges
I recommend using the incredible requests module.
url = ”
payload = {‘some’: ‘data’}
headers = {‘content-type’: ‘application/json’}
response = (url, (payload), headers=headers)
answered Mar 17 ’12 at 1:33
FogleBirdFogleBird67. 4k24 gold badges119 silver badges130 bronze badges
for python 3. 4. 2 I found the following will work:
import quest
body = {‘ids’: [12, 14, 50]}
myurl = ”
req = quest(myurl)
d_header(‘Content-Type’, ‘application/json; charset=utf-8’)
jsondata = (body)
jsondataasbytes = (‘utf-8’) # needs to be bytes
d_header(‘Content-Length’, len(jsondataasbytes))
response = quest. urlopen(req, jsondataasbytes)
Torxed20. 5k13 gold badges76 silver badges120 bronze badges
answered Nov 11 ’14 at 23:07
mike goldmike gold1, 38211 silver badges11 bronze badges
This works perfect for Python 3. 5, if the URL contains Query String / Parameter value,
Request URL = Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca
import requests
data = {“name”: “Value”}
r = (url, auth=(‘username’, ‘password’), verify=False, json=data)
answered Oct 13 ’16 at 9:34
MAXMAX1, 3863 gold badges13 silver badges22 bronze badges
Here is an example of how to use quest object from Python standard library.
from pprint import pprint
url = ”
values = {
“first_name”: “Vlad”,
“last_name”: “Bezden”,
“urls”: [
“, ], }
headers = {
“Content-Type”: “application/json”,
“Accept”: “application/json”, }
data = (values)(“utf-8”)
req = quest(url, data, headers)
with quest. urlopen(req) as f:
res = ()
except Exception as e:
answered Aug 8 ’19 at 14:24
Vlad BezdenVlad Bezden65. 1k20 gold badges218 silver badges162 bronze badges
You have to add header, or you will get 400 error.
The code works well on python2. 6, centos5. 4
import urllib2, json
postdata = {‘key’:’value’}
req = quest(url)
data = (postdata)
response = urllib2. urlopen(req, data)
answered Feb 24 ’14 at 13:56
nullptrnullptr1991 silver badge6 bronze badges
In the lastest requests package, you can use json parameter in () method to send a json dict, and the Content-Type in header will be set to application/json. There is no need to specify header explicitly.
payload = {‘key’: ‘value’}
(url, json=payload)
answered Feb 11 ’20 at 5:04
jdhaojdhao15k7 gold badges98 silver badges170 bronze badges
This one works fine for me with apis
data={‘Id’:id, ‘name’: name}
r = ( url = ‘apiurllink’, data = data)
answered Feb 11 ’20 at 8:00
Sudhir GSudhir G2333 silver badges7 bronze badges
Not the answer you’re looking for? Browse other questions tagged python json url post or ask your own question.

Frequently Asked Questions about python requests post json

How do I send a JSON POST request in Python?

request object from Python standard library. In the lastest requests package, you can use json parameter in requests. post() method to send a json dict, and the Content-Type in header will be set to application/json . There is no need to specify header explicitly.Mar 17, 2012

How do I request JSON data?

2. Building a JSON POST Request With HttpURLConnection2.1. Create a URL Object. … 2.2. Open a Connection. … 2.3. Set the Request Method. … 2.4. Set the Request Content-Type Header Parameter. … 2.5. Set Response Format Type. … 2.6. Ensure the Connection Will Be Used to Send Content. … 2.7. Create the Request Body. … 2.8.Oct 14, 2021

How do you send a POST request in Python?

To send a POST request using Python Requests Library, you must call the requests. post(url, data = my_data) method and specify the target URL as the first parameter and the POST data as the second parameter.Sep 30, 2021

Leave a Reply

Your email address will not be published.