I am making a simple API for news items using Python and the Bottle framework.
I return a Python dictionary from my endpoints as Bottle converts this to JSON automatically in the response to the client.
I wanted to ensure a consistent structure to the responses, so I have declared a template dictionary. The code for each endpoint makes a deep copy of this then modifies the relevant data before returning it.
import bottle
from bottle import route
from copy import deepcopy as deepcopy
# Dictionary for response template
response_dict = {
"status" : "ok",
"code" : 0,
"error" : False,
"message" : "",
"result" : {}
}
# Example route
@route('/example')
def example():
return_dict = deepcopy(response_dict)
return_dict["message"] = "Success"
return_dict["result"] = {
"title" : "Test Title",
"body" : "<p>Lorem ipsum dolor sit amet...</p>"
}
return return_dict
I would like to know if there is a better way to use a template for a JSON response and whether the structure of my dictionary is appropriate.