Restful API framework wrapped around MongoEngine
Python HTML
Latest commit 91d1e7b Oct 12, 2016 @thomasst thomasst v0.2.2
Failed to load latest commit information.
docs changing doc theme to flask_small Aug 23, 2012
flask_mongorest Fix unicode validation errors + tests (#101) Oct 12, 2016
tests Fix unicode validation errors + tests (#101) Oct 12, 2016
.gitignore v0.2 Oct 6, 2016
.gitmodules adding sphinx docs Aug 23, 2012
AUTHORS POST/PUT response should always match GET (including datetime precision) Sep 1, 2012
LICENSE Initial Commit Aug 6, 2012 Support for Python 3 / latest MongoEngine Sep 27, 2016
circle.yml Use Circle Python versions Sep 27, 2016
requirements.txt Support for Python 3 / latest MongoEngine Sep 27, 2016
requirements3.txt Support for Python 3 / latest MongoEngine Sep 27, 2016
setup.cfg Support for Python 3 / latest MongoEngine Sep 27, 2016 v0.2.2 Oct 12, 2016
tox.ini Support for Python 3 / latest MongoEngine Sep 27, 2016

Flask-MongoRest Build Status

A Restful API framework wrapped around MongoEngine.


from flask import Flask
from flask_mongoengine import MongoEngine
from flask_mongorest import MongoRest
from flask_mongorest.views import ResourceView
from flask_mongorest.resources import Resource
from flask_mongorest import operators as ops
from flask_mongorest import methods

app = Flask(__name__)

    MONGODB_HOST = 'localhost',
    MONGODB_PORT = '27017',
    MONGODB_DB = 'mongorest_example_app',

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 = [methods.Create, methods.Update, methods.Fetch, methods.List]

With this app, following cURL commands could be used:

Create a Post:
curl -H "Content-Type: application/json" -X POST -d \
'{"title": "First post!", "author_id": "author_id_from_a_previous_api_call", "content": {"text": "this is our test post content"}}'
  "id": "1",
  "title": "First post!",
  "author_id": "author_id_from_a_previous_api_call",
  "content": {
    "text": "this is our test post content"

Get a Post:

  "id": "1",
  "title": "First post!",
  "author_id": "author_id_from_a_previous_api_call",
  "content": {
    "text": "this is our test post content"

List all Posts or filter by the title:

curl or curl
  "data": [
      "id": "1",
      "title": "First post!",
      "author_id": "author_id_from_a_previous_api_call",
      "content": {
        "text": "this is our test post content"
    ... other posts

Delete a Post:

curl -X DELETE
# Fails since PostView.methods does not allow Delete

Request Params

_skip and _limit => utilize the built-in functions of mongodb.

_fields => limit the response's fields to those named here (comma separated).

_order_by => order results if this string is present in the Resource.allowed_ordering list.

Resource Configuration

rename_fields => dict of renaming rules. Useful for mapping _id fields such as "organization": "organization_id"

filters => filter results of a List request using the allowed filters which are used like /user/?id__gt=2 or /user/?

related_resources => nested resource serialization for reference/embedded fields of a document

child_document_resources => Suppose you have a Person base class which has Male and Female subclasses. These subclasses and their respective resources share the same MongoDB collection, but have different fields and serialization characteristics. This dictionary allows you to map class instances to their respective resources to be used during serialization.


The AuthenticationBase class provides the ability for application's to implement their own API auth. Two common patterns are shown below along with a BaseResourceView which can be used as the parent View of all of your app's resources.

class SessionAuthentication(AuthenticationBase):
    def authorized(self):
        return current_user.is_authenticated()

class ApiKeyAuthentication(AuthenticationBase):
    @TODO ApiKey document and key generation left to the specific implementation
    def authorized(self):
        if 'AUTHORIZATION' in request.headers:
            authorization = request.headers['AUTHORIZATION'].split()
            if len(authorization) == 2 and authorization[0].lower() == 'basic':
                    authorization_parts = base64.b64decode(authorization[1]).partition(':')
                    key = smart_unicode(authorization_parts[0])
                    api_key = ApiKey.objects.get(key__exact=key)
                    if api_key.user:
                        setattr(current_user, 'api_key', api_key)
                    return True
                except (TypeError, UnicodeDecodeError, ApiKey.DoesNotExist):
        return False

class BaseResourceView(ResourceView):
    authentication_methods = [SessionAuthentication, ApiKeyAuthentication]

Running the test suite

This package uses nosetests for automated testing. Just run python nosetests to run the tests. No setup or any other prep needed.


Pull requests are greatly appreciated!