Skip to content

Instantly share code, notes, and snippets.

Last active Feb 20, 2019
What would you like to do?
A sample Flask API to showcase usage of MongoDB in Python
from flask import Flask, request,jsonify
from pymongo import MongoClient
from bson.objectid import ObjectId
from datetime import datetime
app = Flask(__name__)
client = MongoClient()
db = client.blogdb
blogs = db.blogs
@app.route('/eazydevelop/blog', methods=['GET','POST'])
def blog():
if request.method == 'POST':
data = request.json
name = data.get('name','Unnamed Blog')
created_by = data.get('created_by','Anonymous')
created_on =
result = blogs.insert_one({
'name': name,
'created_by': created_by,
'created_on': created_on
response = {
'message': 'Inserted successfully.',
'obj_id': str(result.inserted_id)
return jsonify(response), 201
elif request.method == 'GET':
result = blogs.find({},{'_id':0})
response = {
'data': list(result)
return jsonify(response)
@app.route('/eazydevelop/blog/<blog_id>', methods=['GET'])
def single_blog(blog_id):
result = blogs.find_one({'_id':ObjectId(blog_id)})
result['_id'] = str(result['_id'])
response = {
'data': result
return jsonify(response)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment