Skip to content

Commit 3028f19

Browse files
committed
API completed. Add: getAllData(), getOneFromData, addOneToData(), updateOneFromData(), deleteOneFromData(), mongoDB connection, requeriments.txt, ./imgs/.png
0 parents  commit 3028f19

File tree

4 files changed

+81
-0
lines changed

4 files changed

+81
-0
lines changed

imgs/Flask-REST-API-mongoDB.png

2.11 MB
Loading

requeriments.txt

584 Bytes
Binary file not shown.

src/__pycache__/app.cpython-310.pyc

1.85 KB
Binary file not shown.

src/app.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from flask import Flask, jsonify, request
2+
from flask_mongoengine import MongoEngine
3+
4+
app = Flask(__name__)
5+
6+
app.config["MONGO_URI"] = {
7+
"db": "personsData",
8+
"host": "localhost",
9+
"port": 27017
10+
}
11+
12+
db = MongoEngine()
13+
db.init_app(app)
14+
15+
16+
class User(db.Document):
17+
name = db.StringField()
18+
age = db.IntField()
19+
birthday = db.StringField()
20+
21+
def to_json(self):
22+
return {"name": self.name, "age": self.age, "birthday": self.birthday}
23+
24+
25+
@app.route("/api/", methods=["GET"])
26+
def getAllData():
27+
user = User.objects()
28+
return user.to_json()
29+
30+
31+
@app.route("/api/<string:name>", methods=["GET"])
32+
def getOneFromData(name):
33+
user = User.objects(name=name).first()
34+
if not user:
35+
return jsonify({"Error": "Data not found."})
36+
else:
37+
return user.to_json()
38+
39+
40+
41+
@app.route("/api/", methods=["POST"])
42+
def addOneToData():
43+
user = User(
44+
name=request.json["name"],
45+
age=request.json["age"],
46+
birthday=request.json["birthday"]
47+
)
48+
49+
user.save()
50+
return user.to_json()
51+
52+
53+
@app.route("/api/<string:name>/", methods=["PUT"])
54+
def updateOneFromData(name):
55+
user = User.objects(name=name).first()
56+
if not user:
57+
return jsonify({"Error": "Data not found."})
58+
else:
59+
user.update(
60+
name=request.json["name"],
61+
age=request.json["age"],
62+
birthday=request.json["birthday"])
63+
64+
users = User.objects()
65+
return users.to_json()
66+
67+
68+
@app.route("/api/<string:name>/", methods=["DELETE"])
69+
def deleteOneFromData(name):
70+
user = User.objects(name=name).first()
71+
if not user:
72+
return jsonify({"Error": "Data not found."})
73+
else:
74+
user.delete()
75+
76+
users = User.objects()
77+
return users.to_json()
78+
79+
80+
if __name__ == "__main__":
81+
app.run(debug=True)

0 commit comments

Comments
 (0)