Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Francesco Boi Avatar asked Sep 13 '26 07:09

Francesco Boi


1 Answers

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.

like image 197
Francesco Boi Avatar answered Sep 18 '26 12:09

Francesco Boi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!