Returning JSON using a GET request from server

Viewed 5854

I have a simple server from here, and when the GET function is called, I would like it to return a JSON file, as show in the relevant code snippet below:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        with open('test.json') as data_file:    
            data = json.load(data_file)
        self.wfile.write(data)

My json file:

{"foo": "bar", "boo": "far"}

The application requesting the file (client.py):

import requests
import json

r = requests.get('http://localhost:8080')
print r.json()

However, when trying to run client.py I get the following error:

ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Am I correctly loading the test.json file in the do_GET function?

Thanks for your help :)

3 Answers

To be able to catch a JSON response from http.server using requests library, another words to use response.json() you should make the following on the server side:

from http.server import BaseHTTPRequestHandler
import json


class GetHandler(BaseHTTPRequestHandler):

def do_GET(self):
    json_data = {'token': 'qfrwefewrtweygds--fefef==wef'}
    json_to_pass = json.dumps(json_data)
    self.send_response(code=200, message='here is your token')
    self.send_header(keyword='Content-type', value='application/json')
    self.end_headers()
    self.wfile.write(json_to_pass.encode('utf-8'))

This thing worked for me.

Related