Skip to content

Instantly share code, notes, and snippets.

@shreybatra
Last active February 20, 2019 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreybatra/6752ed56f060c9ce5d72e4498661bbbb to your computer and use it in GitHub Desktop.
Save shreybatra/6752ed56f060c9ce5d72e4498661bbbb to your computer and use it in GitHub Desktop.
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 = datetime.now().timestamp()
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__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment