Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 = simplejson.dumps(data)

payload = {'json_payload': data_json}

r = requests.post("http://localhost:8080", data=payload)

Here is the server code.

class Root(object):

     def __init__(self, content):

           self.content = content

           print self.content # this works

          exposed = True

    def GET(self):

         cherrypy.response.headers['Content-Type'] = 'application/json'

        return simplejson.dumps(self.content)

    def POST(self):

         self.content =        simplejson.loads(cherrypy.request.body.read())

Any ideas?

1 Answer

0 votes
by (106k points)

To post JSON using Python Requests you can use the below-mentioned code it will be helpful:-

url = "http://localhost:8080"  

data = {'sender': 'Alice', 'receiver': 'Bob', 'message':'We did it!'}

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

r = requests.post(url, data=json.dumps(data), headers=headers)

If you wish to know what is python visit this python tutorial and python interview questions.

If you wish to learn more about Python, visit the Python tutorial and Python Certification course by Intellipaat.

Related questions

0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 15, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Nov 20, 2019 in Java by Nigam (4k points)

Browse Categories

...