Last active
February 20, 2019 13:21
-
-
Save shreybatra/6752ed56f060c9ce5d72e4498661bbbb to your computer and use it in GitHub Desktop.
A sample Flask API to showcase usage of MongoDB in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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