How to return data in specific format from Python Flask API?

Joined
Aug 10, 2022
Messages
1
Reaction score
0
I am writing a get API using python flask.
This API is for a FAQ webpage in which there are multiple question and answers which are divided section wise.

Webpage Example: How Webpage section looks for FAQ

**Section 1**
Question : Question 1 for section1?
Answer : Answer 1 for section 1.

Question : Question 2 for section1?
Answer : Answer 2 for section1.

**Section 2**
Question : Question 1 for section2?
Answer : Answer 1 for section 1.

Question : Question 2 for section2?
Answer : Answer 2 for section1.


I have written this python API code


Python:
@app.route('/getProductFaqs')
    def productfaqs():
        try:
            conn = mysql.connect()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            cursor.execute("SELECT id, product_name, product_question, product_answer FROM questionFAQ")
            rows = cursor.fetchall()
            resp = jsonify(rows)
            resp.status_code = 200
            return resp
        except Exception as e:
            print(e)
        finally:
            cursor.close()
            conn.close()


which returns data in this format


JSON:
[
      {
        "id": 1,
        "product_answer": "answer product 1",
        "product_name": "product 1",
        "product_question": "What is product 1?"
      },
      {
        "id": 2,
        "product_answer": "answer product 2",
        "product_name": "product 2",
        "product_question": "What is product 2?"
      },
      {
        "id": 3,
        "product_answer": "answer product 3",
        "product_name": "product 3",
        "product_question": "What is product 3?"
      },
      {
        "id": 4,
        "product_answer": "answer product 4",
        "product_name": "product 4",
        "product_question": "What is product 4?"
      }
    ]

However my requirement for API response is in this format


JSON:
[
      {
        productid: 1[
          {
            Question: question1?
            Answer: answer1.
          },
          {
            Question: question2?
            Answer: Answer2.
          }
        ]
      },
     {
        productid: 2[
          {
            Question: question1?
            Answer: answer1.
          },
          {
            Question: question2?
            Answer: Answer2.
          }
        ]
      }
    ]

Can please someone help me out with this formatting of response.
Thankyou in Advance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,056
Messages
2,570,441
Members
47,125
Latest member
MDBT

Latest Threads

Top