AnD AnD - 2 months ago 12
reST (reStructuredText) Question

How to return JSON from Python REST API

I have a Python API that receives data from mysql select query. The data looks like this:

| val | type | status |
| 90 | 1 | a |

That data was received well in python. Now I want to present that data as JSON to my REST client - how?

Here is my python code:

def somefunction(self, by, identifier):
# validate args
procedure = 'mysproc' + str(by)

with self.connection.cursor() as cursor:
result = cursor.fetchone()

print("+++ Result: " + str(result) + " +++")
result = "Request Failed"

return json.dumps(result)

with that, my client is receiving:

"[90, 1, "a"]"


is there a way for me to receive it as a proper JSON? like:

{'val': 90, 'type': 1 , : 'status': "a"}


You will first need to get the mysql query to return a dict object instead of a list. If your library is MySQLdb then this answer: Python - mysqlDB, sqlite result as dictionary is what you need.

Here is a link to the docs for MySQLdb:

I think if you pass in the cursor class you want to use when you create your cursor the result of fetchone will be a dictionary.

with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor:

Running json.dumps(result) on a dictionary will give the output you are looking for.