RESTful API using Flask and MongoDB

Objective
Create a RESTful API using Flask web developement framwork and MongoDB. Flask is a micro web framework written in Python.
Getting started
Prerequisites:
It is recommended to create virtual environment for the purpose of seperate project environment and clean code. To create python virtual environment in Linux and Windows platform, please follow the given link.
Library | Command |
---|---|
Flask | pip install flask |
Flask-mongoengine | pip install flask-mongoengine |
BSON | pip install bson |
Description
This application implements CRUD (create-read-update-delete) operation by HTTP methods (GET, POST, PUT, DELETE). The CRUD operation performs on three schemas (Professor, ResearchGroup and Student). Moreover, the professors can be searched by designation and research group name. Similarly, the students can be searched by research group name. To check out the schemas and the path definitions, please click the links.
File structure
flaskREST
|- app.py
|__database
|- db.py
|- models.py
The app.py defines the routes and the database connection. The models.py defines the schemas and the db.py defines the database initialization.
Database configuration
The mongodb database is configured by the following code where flask-db represents the name of the database.
# database config
app.config['MONGODB_SETTINGS'] = {
'host': 'mongodb://localhost/flask-db'
}
The basic structure of flask app is :
# import libraries
from flask import Flask, jsonify, request, Response
app = Flask(__name__) #creating flask application
if __name__ == '__main__':
app.run()
CRUD operations
The basic structure of RESTful API :
@app.route('/<endpoint>', methods=['GET','POST','PUT','DELETE'])
def Function():
# this function will be triggered when the client sends request to the endpoint.
PASS
Note: To get familiar with atomic updates, please follow the link. Atomic updates are needed during UPDATE operation in relational database.
To start and run the application without reloading
To start and run the application without reloading, please remove the app.run() from the application module (app.py) and execute the following command.
FLASK_APP=app.py FLASK_ENV=developement flask run
Terminal output:
* Serving Flask app "app.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 188-695-452
The server will run at http://localhost:5000. Download (postman) OR use command line tool (curl) to execute the operations. The following link has the instructions to execute CRUD in both postman and curl.
Download code: Github