Skip to content
Advertisement

Python HTTPServer: Reponse not getting sent (Looking to return JSON)

Hey there I am working on a Basic server with Python now I am testing out how I can return JSON data, but then now I am failing to return that JSON data.

This is how I am trying to send back JSON to client:

response= {
   "name":'junior',
   "name":'junior'
}
self.send_response(200)
self.wfile.write(bytes(json.dumps(response, ensure_ascii=False), 'utf-8'))
self.send_header('Content-type', 'application/json')
self.end_headers()

Below is the entire source code:

import ast
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from http import HTTPStatus

class ServiceHandler(BaseHTTPRequestHandler):
    
  def do_GET(self):
    print(self.path)


  def do_POST(self):
    content_len = int(self.headers.get('Content-Length'))
    post_body = self.rfile.read(content_len)  
    body = ast.literal_eval(post_body.decode("utf-8"))
    response= {
       "name":'junior',
       "name":'junior'
    }
    self.send_response(200)
    self.wfile.write(bytes(json.dumps(response, ensure_ascii=False), 'utf-8'))
    self.send_header('Content-type', 'application/json')
    self.end_headers()
        
   
#Server Initialization
server = HTTPServer(('127.0.0.1',8080), ServiceHandler)
server.serve_forever()

Can I please get some help on how I can return back JSON data

Advertisement

Answer

Send headers before the body like this:

self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(response, ensure_ascii=False), 'utf-8'))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement