I try to use RESTplus
to fetch objects. My implementation follows the Restplus
tutorial. I managed to fetch a single object. However, I can not fetch a list with all objects.
This is a minimal implementation to reproduce the shortcoming:
from flask import Flask
from flask_restplus import Api, Resource, fields
from mongoengine import Document, connect
from mongoengine.fields import *
app = Flask(__name__)
connect()
api = Api(app)
user_model = api.model('user', {'name': fields.String})
user_model_list = api.model('User List', {'users':fields.List(fields.Nested(user_model))})
class User(Document):
name = StringField()
@api.route('/Users')
class UserApi(Resource):
@api.marshal_with(user_model_list)
def get(self):
return User.objects().all()
@api.route('/User')
class UserApi(Resource):
@api.marshal_with(user_model)
def get(self):
return User.objects().first()
# Insert data into database
@app.before_first_request
def init():
User(name='John').save()
User(name='Sue').save()
User(name='Li').save()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000
This is the output of GET http://127.0.0.1:5000/Users
{
"users": null
}
The problem in my approach was that the MongoEngine returns a mongoengine.queryset.queryset.QuerySet
ant not a list. After converting the QuerySet to a List, it worked even without as_list=True
or marshal_list_with()
.
@api.route('/User')
class UserApi(Resource):
@api.marshal_with(user_model)
def get(self):
return list(User.objects().first())