Skip to content

Instantly share code, notes, and snippets.

@Jasata
Created February 22, 2020 19:19
Show Gist options
  • Save Jasata/f582f0e5dc5780c9a8078aec0f2d39e5 to your computer and use it in GitHub Desktop.
Save Jasata/f582f0e5dc5780c9a8078aec0f2d39e5 to your computer and use it in GitHub Desktop.
Minimal JSON REST API (ROS 1 access for Jupyter)
#! /usr/bin/env python2
#
# ROS 1 "Kinetic Kame" server
# EOL date at April 2021, but this version uses Python 2.7
#
# Demo code for Jupyter access, need accesspoints and all the
# associated data packet handling.
#
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json
PORT = 8080
# Demo payload, random stuff
PAYLOAD = {
'id': 'rat',
'value': 42,
'pocket': {
'smurf': True,
'chain': [ 1, 'a', 7, ('beep', -2)]
}
}
class ROSJSONHandler(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_HEAD(self):
self._set_headers()
def do_GET(self):
path = self.path.split("?")[0]
if path == "/":
payload = PAYLOAD
elif path == "/hello":
payload = { "Hello" : "World" }
else:
# Complaint response
self.send_response(405)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("405 Method Not Allowed")
return
# JSON response
self._set_headers()
self.wfile.write(json.dumps(payload))
return
if __name__ == "__main__":
httpd = HTTPServer(('', PORT), ROSJSONHandler)
print("Serving on port {}".format(PORT))
httpd.serve_forever()
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment