Search code examples
pythonpostgresqlflaskflask-restful

What am I missing in my flask restful api output is null and repeated


from flask import Flask
from flask_restful import Resource, fields, marshal_with,Api
import psycopg2

conn=psycopg2.connect("dbname=jobkhulyodb user=postgres password=password")
cur=conn.cursor()

app=Flask(__name__)
api=Api(app)

resource_fields = {
    'job_title': fields.String,
    'job_description': fields.String,
}

class Todo(Resource):
    @marshal_with(resource_fields, envelope='resource')
    def get(self, **kwargs):
        cur.execute("SELECT job_title,job_description from jobs")
        return cur.fetchall()


api.add_resource(Todo, '/foo', endpoint='todo')

if __name__=='__main__':
    app.run()

The api is build with Flask, flask_restful and postgresql Followed the documentation and as per it I created a resource fields and fetched the same resource from database using postgresql commands in the return fields. Where and what am I doing wrong the output looks something like in the picture. The database has 2 rows only but the result shows null and appearing 2 times.

output enter image description here


Solution

  • you are getting a list of tuple with cur.fetchall(), so this code must do what you need:

    ...
    def get(self, **kwargs):
        ...
        list_ = []
        for elem in cur.fetchall():
            list_.append({ 'job_title': elem[0], 'job_description': elem[1] })
        return list_