Search code examples
pythonjsoncherrypybottlepython-requests

Sending JSON through requests module and catching it using bottle.py and cherrypy


I have a server which needs to be able to accept JSON and then process it and then send JSON back. The code at my server side is using bottle.py with cherrypy. The route in concern is the following:

@route ('/tagTweets', method='POST')
def tagTweets():

    response.content_type = 'application/json'

    # here I need to be able to parse JSON send along in this request.

For requesting this page and testing the functionality, I'm using requests module code:

The data that I have to send is list of tweets. The data is itself fetched from some server which returns list of tweets. For fetching tweets, I'm using requests.get and then using json method of response object. This is working fine. Now I after some processing on this, I have to send this json, just like I fetched to another server.

url     = "http://localhost:8080/tagTweets"
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)

I'm not able to figure out how to gain access to the json send along the request.


Solution

  • For a application/json POST, simply access request.json:

    @route ('/tagTweets', method='POST')
    def tagTweets():
         response.content_type = 'application/json'
         sender = request.json['sender']
         receiver = request.json['receiver']
         message = request.json['message']