1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

There is no need to use deepcopy here. Just have a function that returns a new object when you need it. And while you're at it, just make the message and the result parameters of that function. Or even all of them:

def json_response(message, result, status="ok", code=0, error=False):
    return {
        "status" : status,
        "code" : code,
        "error" : error,
        "message" : message,
        "result" : result
    }

@route('/example')
def example():
    result = {
        "title" : "Test Title",
        "body" : "<p>Lorem ipsum dolor sit amet...</p>"
    }
    return json_response("Success", result)

Having all as parameters, but with default values, allows you to do this in the future:

json_response("Failure", None, status="fail", code=404, error=True)

In the end it depends on how often you need to use this template whether or not this is better than just directly returning the dictionary explicitly:

@route('/example')
def example():
    return {
        "status" : "ok",
        "code" : 0,
        "error" : False,
        "message" : "Success",
        "result" : {
            "title" : "Test Title",
            "body" : "<p>Lorem ipsum dolor sit amet...</p>"
        }
    }
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks for this. I was fixated on using the dictionary and hadn’t thought about using a function. It seems much more straightforward. \$\endgroup\$ – Chris May 23 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.