I am trying to write the python code, that return the json output when I curl localhost:8000
. I want to get the value only when I do curl localhost:8000/shakespear
. As of the current code I am getting the value at curl localhost:8000
main.py
#!/usr/bin/env python
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import json
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
self.send_response(200)
self.end_headers()
self.wfile.write(json.dumps({
'myfavourite author name': 'shakespear',
}).encode())
return
if __name__ == '__main__':
server = HTTPServer(('0.0.0.0', 8000), RequestHandler)
print('Starting server at http://localhost:8000')
server.serve_forever()
Use an if condition to check if
parsed.path
is the same as your desired endpoint i.eshakespear
Keep in mind that
/
is part of thepath
string. Withself.path
usingurlparse
is unnecessaryIt is meant to be used when you're working with a url that you need parsed.
Example:
As explained in the docs, urlparse returns a
ParseResult
with thepath
attribute.Pass the url to
urlparse
:This returns a
ParseResult
whosepath
attribute you can access: