Created
June 28, 2016 12:55
-
-
Save hugohil/2992ee3a6d66e5aa206cf1f64df4dee4 to your computer and use it in GitHub Desktop.
Basic python 2.7 REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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