February 2018
Intermediate to advanced
456 pages
9h 56m
English
In our service.py, add the following import:
import json
Now add the following to our WebServer class:
@http('POST', '/messages')
def post_message(self, request):
data_as_text = request.get_data(as_text=True)
try:
data = json.loads(data_as_text)
except json.JSONDecodeError:
return 400, 'JSON payload expected'
try:
message = data['message']
except KeyError:
return 400, 'No message given'
self.message_service.save_message(message)
return 204, ''
With our new POST entrypoint, we start off by extracting the data from the request. We specify the parameter as_text=True, because we would otherwise get the data back as bytes.
Once we have that data, we can then attempt to load it from JSON into a Python dictionary. ...
Read now
Unlock full access