Tikkaty
Tikkaty

Reputation: 802

How do I return single object with JSON in Python with Flask

I have the below code which is trying to return an object back to JSON. I'm trying to return back the MenuItem object to the caller

#Make JSON API
@app.route('/restaurant/<int:restaurant_id>/menu/<int:menu_id>/JSON')
def restaurantMenuJSONONE(restaurant_id,menu_id):
    item = session.query(MenuItem).filter_by(id = menu_id).one()
    return jsonify(MenuItems=item)

Error I'm getting:

TypeError: <database_setup.MenuItem object at 0xb6071d8c> is not JSON serializable

database_setup.py snips

class MenuItem(Base):
    __tablename__ = 'menu_item'

    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

#JSON
    @property
    def serialize(self):
        #return object
        return {
            'name' : self.name,
            'description' : self.description,
            'id' : self.id,
            'price' : self.price,
            'course' : self.course,
        }

Upvotes: 0

Views: 2202

Answers (1)

Tikkaty
Tikkaty

Reputation: 802

Solved it with:

return jsonify(MenuItem=item.serialize)

I also solved it with by creating a list and passing the list in, but its a lot more work than using serialize :)

Upvotes: 2

Related Questions