Search code examples
pythontornado

Tornado PUT Request Missing Body


I'm trying to make a put request using a tornado ASyncHTTPClient like so:

  data = { 'text': 'important text',
           'timestamp': 'an iso timestamp' }

  request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', body = urllib.urlencode(data))

  response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)

However, when the request hits its desired endpoint, it appears not to have a body, despite said body being properly encoded and defined above. Is there something that I'm overlooking here?



Solution

  • If the other end is expecting JSON, you probably need to set a "Content-Type" header. Try this:

    data = { 'text': 'important text',
           'timestamp': 'an iso timestamp' }
    
    headers = {'Content-Type': 'application/json; charset=UTF-8'}
    
    request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', headers = headers, body = simplejson.dumps(data))
    
    response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)
    

    This way, the header tells the server you're sending JSON, and the body is a string that can be parsed as JSON.