librelist archives

« back to archive

Flask-MongoRest: a restful API framework for MongoEngine

Flask-MongoRest: a restful API framework for MongoEngine

Anthony Nemitz
2012-08-06 @ 22:53
Hello Flaskers --

I wanted to introduce a new project which will hopefully help any of you 
creating restful api's on top of MongoEngine.

* authentication plugin support and ability to limit a view by HTTP method
* nested document (related_resources) and shared collection serialization 
* orderby, pagination, and filtering of collections 
* renaming of document fields (person_id => person)
* form validation

Check out the project at:

I'd love to hear your feedback and pull requests!




from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.mongorest import MongoRest
from flask.ext.mongorest.views import ResourceView
from flask.ext.mongorest.resources import Resource
from flask.ext.mongorest import operators as ops
from flask.ext.mongorest.methods import *

app = Flask(__name__)

db = MongoEngine(app)
api = MongoRest(app)

class User(db.Document):
    email = db.EmailField(unique=True, required=True)

class Content(db.EmbeddedDocument):
    text = db.StringField()

class ContentResource(Resource):
    document = Content

class Post(db.Document):
    title = db.StringField(max_length=120, required=True)
    author = db.ReferenceField(User)
    content = db.EmbeddedDocumentField(Content)

class PostResource(Resource):
    document = Post
    related_resources = {
        'content': ContentResource,
    filters = {
        'title': [ops.Exact, ops.Startswith],
        'author_id': [ops.Exact],
    rename_fields = {
        'author': 'author_id',

@api.register(name='posts', url='/posts/')
class PostView(ResourceView):
    resource = PostResource
    methods = [Create, Update, Fetch, List, Delete]

Anthony Nemitz