Reputation: 1051
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
Upvotes: 0
Views: 99
Reputation: 177901
The headers have to be sent before the data, but also how are you asking for the POST request? Here's an example that just uses a GET:
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
class ServiceHandler(BaseHTTPRequestHandler):
def do_GET(self):
response= {
"name":'junior',
"name2":'junior'
}
self.send_response(200)
self.send_header('Content-type', 'application/json')
data = json.dumps(response).encode()
self.end_headers()
self.wfile.write(json.dumps(response).encode())
server = HTTPServer(('',8080), ServiceHandler)
server.serve_forever()
>>> print(requests.get('http://127.0.0.1:8080').json())
{'name': 'junior', 'name2': 'junior'}
Upvotes: 1
Reputation: 87124
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'))
Upvotes: 1