JSON response in Google App Engine with Python
Question: I want to build a REST service with Python and Google App Engine and have the
following code:

Edited Code:

    
    
    import webapp2
    from google.appengine.ext import db
    from google.appengine.api import users
    import json
    
    class Item(db.Model):
    
        author           = db.UserProperty(required=False)
        summary          = db.StringProperty(required=True)
        description      = db.StringProperty(multiline=True)
        url              = db.StringProperty()
        created          = db.DateTimeProperty(auto_now_add=True)
        updated          = db.DateTimeProperty(auto_now=True)
        dueDate          = db.StringProperty(required=True)
        finished         = db.BooleanProperty()
    
    class GetAllItems(webapp2.RequestHandler):
        def get(self):
            item = Item(summary="Summary", dueDate="Date")
            item.put()
    
            allItems = Item.all()
            data = []
            for entry in allItems:
                data.append(db.to_dict(entry))
    
            self.response.out.write(json.dumps(entry))
    
    app = webapp2.WSGIApplication(
        [
            ('/api/items', GetAllItems)
            ],
        debug=True)
    

How can i convert all items of this model into JSON and send it back as JSON?
I always get this Error:

    
    
    TypeError: <main.Item object at 0x0538B590> is not JSON serializable
    


Answer: I use now NDB instead of DB and the following code solved all my problems:

    
    
    import decimal
    import webapp2
    from google.appengine.ext import ndb
    import json
    from google.appengine.api import users
    
    
    class Item(ndb.Model):
        author = ndb.UserProperty(required=False)
        summary = ndb.StringProperty(required=True)
        description = ndb.StringProperty()
        url = ndb.StringProperty()
        created = ndb.DateTimeProperty(auto_now_add=True)
        updated = ndb.DateTimeProperty(auto_now=True)
        updated = ndb.StringProperty()
        dueDate = ndb.StringProperty(required=True)
        finished = ndb.BooleanProperty()
    
    
    class DateTimeEncoder(json.JSONEncoder):
        def default(self, obj):
            if hasattr(obj, 'isoformat'):
                return obj.isoformat()
            elif isinstance(obj, decimal.Decimal):
                return float(obj)
            else:
                return json.JSONEncoder.default(self, obj)
    
    
    class GetAllItems(webapp2.RequestHandler):
        def get(self):
            item = Item(summary="Summary", dueDate="Date")
            item.put()
    
            text = json.dumps([i.to_dict() for i in Item.query().fetch()], cls=DateTimeEncoder)
            self.response.out.write(text)
    
    
    app = webapp2.WSGIApplication(
        [
            ('/api/items', GetAllItems)
        ],
        debug=True)
    

