Reputation: 45
By doing python -m http.server
you can invoke a simple web server which serves files in a directory.
My question is how I can use this to make multiple API endpoints with BaseHTTPRequestHandler
E.g. if I were to make a file called “helloworld.py” in the api directory, with this code:
from http.server import BaseHTTPRequestHandler
class app(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header(“Content-type”, “text/plain”)
self.end_headers()
self.wfile.write(b”Hello World”)
return
And the visited http://localhost/api/helloworld
it would display the text Hello World.
Is there a way to do this?
TL;DR How can you incorporate BaseHTTPRequestHandler functions into a http.server and execute them as backend handlers?
Thanks!
Upvotes: 2
Views: 1091
Reputation: 21
You can use regex to check self.path
for the desired endpoint. It can be applied to do_POST
as well.
import re
from http.server import BaseHTTPRequestHandler, HTTPServer
class app(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
if re.search('/api/helloworld', self.path):
message = "Hello, World"
self.wfile.write(bytes(message, "utf8"))
with HTTPServer(('', 8000), app) as server:
server.serve_forever()
python helloworld.py
will run the server indefinitely, then
$ curl localhost:8000/api/helloworld
Hello, World%
Upvotes: 2