REST¶
HTTP_REQUEST
object.Warning
The following example is for non-vhost entries. This is useful for simpel setups. Read below for a REST Vhost option.
@http.route('/')
def main_entry(request):
print(request.headers)
return request.build_headers() + b'<html><body>Test body</body></html>
This is a minimal example of how to respond with some default basic headers and a default content.
Methods and headers¶
An example to react to PUT requests:
@http.route('/')
def main_entry(request):
if request.method == 'PUT':
print('We got a PUT request with headers:', request.headers)
REST with Virtual Hosts¶
Warning
You first need to grab the http instance object, since virtual host entry-points are usually defined in a separate file from where the http variable was created.
This example also shows you how to grab that instance.
import slimHTTP
http = slimHTTP.instances[':80']
@http.route('/', vhost='example.com')
def main_entry(request):
print(request.headers)
return request.build_headers() + b'<html><body>Test body</body></html>
REST with JSON¶
To convert and work with the request data, you could do something along the lines of:
@http.route('/')
def main_entry(request):
data = json.loads(request.payload.decode('UTF-8'))
print(data['key'])
And to respond, you could build ontop of it by doing:
@http.route('/')
def main_entry(request):
data = json.loads(request.payload.decode('UTF-8'))
print(data['key'])
return request.build_headers({'Content-Type' : 'application/json'}) + bytes(json.dumps({"key" : "a value"}, 'UTF-8')
Which would instruct slimHTTP to build a basic header response with one additional header, the Content-Type and utilize json.dumps to dump a dictionary structure.
Note