Search code examples
pythonpython-3.xurllibhttp.server

Path based routing in Python


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()

Solution

  • Use an if condition to check if parsed.path is the same as your desired endpoint i.e shakespear

    def do_GET(self):
      ...
      if self.path == '/shakespear':
        self.send_response(200)
        #do stuff
        ...
    

    Keep in mind that / is part of the path string. With self.path using urlparse is unnecessary

    It 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 the path attribute.

    Pass the url to urlparse:

    from urllib.parse import urlparse
    url = "http://127.0.0.1:8080/shakespear"
    parsed = urlparse(url)
    

    This returns a ParseResult whose path attribute you can access:

    print(parsed)
    ParseResult(scheme='http', netloc='127.0.0.1:8080', path='/shakespear', 
    params='', query='', fragment='')
    
    print(parsed.path)
    '/shakespear'