Skip to content

Instantly share code, notes, and snippets.

@hugohil hugohil/server.py
Created Jun 28, 2016

Embed
What would you like to do?
Basic python 2.7 REST API
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
PUBLIC_ENTRY = './public/index.html'
# This class will handles any incoming request
class handleRoutes(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
if (self.path == '/'):
file = open(PUBLIC_ENTRY)
self.sendResponse(file.read(), 200, 'text/html')
file.close()
return
if (self.path.startswith('/api/v1/')):
if (self.path.endswith('hello')):
return self.sendResponse('{"hello": "world"}', 200, 'application/json')
if (self.path.endswith('world')):
return self.sendResponse('{"world": "hello"}', 200, 'application/json')
else:
return self.sendResponse('Not found.', 404, 'text/plain')
def sendResponse(self, res, status, type):
self.send_response(status)
self.send_header('Content-type', type)
self.end_headers()
# Send the html message
self.wfile.write(res)
return
try:
# Create a web server and define the handler to manage the incoming requests
server = HTTPServer(('', PORT_NUMBER), handleRoutes)
print 'Started http server on port ' , PORT_NUMBER
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print '\nFarewell my friend.'
server.socket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.