Python API: Flask-RESTfull + Docker + MongoDB

Today I’ll show you a simple project to create a RESTfull API dockenized using Flask-restfull framework easily.

Firstily a little overview about the project. I want to create a “Arrangemente” system to schedule my meetings per rooms. So I need to create two microservices. One to work with the arrangements and the second to work with the rooms.

Or arrangement API must be able to Create, Update and Delete a record. Also we must have to be able to search by arrange ID and from a datetime range with a start and a end datetime. The arrange object must have a title, a room code, a start datetime and a end datetime.

Or room API must be able to Create, Update and Delete records in the database. The Room object must have a name and a code.

In this project I’ve decided to use a non-relational database because we don’t have to many relations and foreingkeys. Also we can easy represent an arrangement as a document. We just need to know the room code. But this is not a essential parameter to my arrange exist.

Flask-RESTful

Flask-RESTful is a version ofthe Python framework to build RESTful API easy. This is very lightweigh and simple Python framework. This supports JSON as well, annotations and blueprints api. Also Flask is made to provide a simple way to build small and huge projects as well.

MongoDB

I choose Mongo because in this project we dont have many relations between the entities and is not a accoplated project. We can deal with documents easy.

Main Files

api/app.py


# -*- coding: utf-8 -*-
import sys

from flask import Flask, jsonify, url_for, redirect, request, Blueprint
from flask_restful import Api, Resource
from urllib import quote_plus, quote

from resources.arrange import Arrange
from resources.room import Room
from common.logger import Logger
from common.mongoDB import MongoDb


def routes(api, db):
api.add_resource(Index, "/v1", endpoint="index")
api.add_resource(Arrange, "/v1/arrange", "/v1/arrange/<string:id>",
endpoint="arrange", resource_class_kwargs={'db': db})
api.add_resource(Room, "/v1/room", "/v1/room/<string:id>", endpoint="room",
resource_class_kwargs={'db': db})


def main(host, port, debug):

# app = application(host, port, debug)
#Logger(app)
app.run(host, port, debug)

class Index(Resource):
def get(self):
return {"response": "health"}

# initialization of Flask Application
app = Flask(__name__)
app.register_blueprint(Blueprint('api', __name__))
mongo = MongoDb(app)
db = mongo.getDb()
routes(Api(app), db)

if __name__ == "__main__":
main(sys.argv[3:])

This file is responsable to the main part of or api. Here we declare or app, or DB instance and conection and the routes.

You can checkout the rest of the project on https://github.com/alvaropaco/py-arrangement/tree/master/api

Thanks =)