Search code examples
python-3.xgetpostmanhttpserver

Python HTTPServer responding to curl but not to Postman GET request


Consider a simple server in Python3 with the module BaseHTTPRequestHandler.

import json
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
import bson.json_util

class GetHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        print("/n=================================")
        json_string = '{"hello":"world"}'
        self.wfile.write(json_string.encode())
        self.send_response(200)
        self.end_headers()
        return

if __name__ == '__main__':
    #from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost', 3030), GetHandler)
    print ('Starting server, use <Ctrl-C> to stop')
    server.serve_forever()

This is responding correctly with curl from the Terminal:

curl -i http://localhost:3030/

However when trying to send a request from Postman it is not responding. I tried the URL localhost:3030/, http://localhost:3030/ and also with the loopback address.

Why is that?


Solution

  • In all the examples I have seen it was not specifying the content type so I did the same way and seeing that curl worked I did not worry too much.

    However content type should be specified: adding these lines before self.wfile.write(...)solves the problem:

    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.end_headers()
    

    Please note that actually self.send_response(200) has been moved, not added.