I'm currently following this example to get an API up and running (my code below)
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
import mysql.connector
db_connect = create_engine('mysql+pymysql://root:pass@localhost/news')
app = Flask(__name__)
api = Api(app)
class Events(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select id, title, description, date, scheduled,favourite,count_audio,count_video,count_articles from events;")
result = [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]
return jsonify(result)
api.add_resource(Events, '/events') # Route_1
if __name__ == '__main__':
app.run(port='5002')
And I want to end up with a nested array, tags, and a nested object, location, as below
[{
"description": "TEST DESCRIPTION",
"id": 1,
"title": "TEST TITLE",
"date": "2020-09-02",
"scheduled":"true",
"favourite":"true",
"tags": ["celebration", "national holiday"],
"location": {
"state": {
"name": "new zealand",
"affiliation": ["United Nations"]
},
"province": "",
"urbanisation": "Wellington"
}
},
{
"description": "LONG DESCRIPTION",
"id": 2,
"title": "SECOND ENTRY",
"date": "2020-09-03",
"scheduled":"false",
"favourite":"false",
"tags": ["election", "national holiday"],
"location": {
"state": {
"name": "Brazil",
"affiliation": [""]
},
"province": "",
"urbanisation": ""
}
}]
Is something like this even possible? Do I need to rethink my API to have endpoints covering each nested object?
api.add_resource(Events, '/events')
api.add_resource(tags, '/events/tag')
api.add_resource(location, '/events/location')
Or, do I nest dictionaries as in this answer.