Created
December 25, 2017 17:55
-
-
Save ratulbasak/7f96b2364ab659a62ca5f2cde7d97ac6 to your computer and use it in GitHub Desktop.
flask_simple_api
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 | |
from flask import jsonify | |
from flask import request | |
from flask_pymongo import PyMongo | |
app = Flask(__name__) | |
app.config['MONGO_DBNAME'] = 'restdb' | |
app.config['MONGO_URI'] = 'mongodb://localhost:27017/restdb' | |
mongo = PyMongo(app) | |
@app.route("/") | |
def hello(): | |
return "<h1 style='color:blue'>This is Flask API!</h1>" | |
@app.route('/star', methods=['GET']) | |
def get_all_stars(): | |
star = mongo.db.stars | |
output = [] | |
for s in star.find(): | |
output.append({'name' : s['name'], 'distance' : s['distance']}) | |
return jsonify({'result' : output}) | |
@app.route('/star/', methods=['GET']) | |
def get_one_star(name): | |
star = mongo.db.stars | |
s = star.find_one({'name' : name}) | |
if s: | |
output = {'name' : s['name'], 'distance' : s['distance']} | |
else: | |
output = "No such name" | |
return jsonify({'result' : output}) | |
@app.route('/star', methods=['POST']) | |
def add_star(): | |
star = mongo.db.stars | |
name = request.json['name'] | |
distance = request.json['distance'] | |
star_id = star.insert({'name': name, 'distance': distance}) | |
new_star = star.find_one({'_id': star_id }) | |
output = {'name' : new_star['name'], 'distance' : new_star['distance']} | |
return jsonify({'result' : output}) | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0',debug=True) |
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
click==6.7 | |
Flask==0.12.2 | |
Flask-PyMongo==0.5.1 | |
itsdangerous==0.24 | |
Jinja2==2.10 | |
jsonify==0.5 | |
MarkupSafe==1.0 | |
pycrypto==2.6.1 | |
pymongo==3.6.0 | |
uWSGI==2.0.15 | |
virtualenv==15.1.0 | |
Werkzeug==0.13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment