11from flask import Flask , request , jsonify
22from models import db , Student
33
4-
54app = Flask (__name__ )
65app .config ['SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///students.db'
76app .config ['SQLALCHEMY_TRACK_MODIFICATIONS' ] = False
@@ -22,7 +21,16 @@ def get_students():
2221@app .route ('/students' , methods = ['POST' ])
2322def add_student ():
2423 data = request .get_json ()
25- student = Student (name = data ['name' ], age = data ['age' ])
24+
25+ # Validation
26+ if not data :
27+ return jsonify ({"error" : "Missing JSON body" }), 400
28+ if 'name' not in data or not isinstance (data ['name' ], str ) or not data ['name' ].strip ():
29+ return jsonify ({"error" : "Invalid or missing 'name'" }), 400
30+ if 'age' not in data or not isinstance (data ['age' ], int ):
31+ return jsonify ({"error" : "Invalid or missing 'age'" }), 400
32+
33+ student = Student (name = data ['name' ].strip (), age = data ['age' ])
2634 db .session .add (student )
2735 db .session .commit ()
2836 return jsonify ({"id" : student .id }), 201
@@ -31,8 +39,19 @@ def add_student():
3139def update_student (id ):
3240 student = Student .query .get_or_404 (id )
3341 data = request .get_json ()
34- student .name = data ['name' ]
35- student .age = data ['age' ]
42+
43+ # Validation
44+ if not data :
45+ return jsonify ({"error" : "Missing JSON body" }), 400
46+ if 'name' in data :
47+ if not isinstance (data ['name' ], str ) or not data ['name' ].strip ():
48+ return jsonify ({"error" : "Invalid 'name'" }), 400
49+ student .name = data ['name' ].strip ()
50+ if 'age' in data :
51+ if not isinstance (data ['age' ], int ):
52+ return jsonify ({"error" : "Invalid 'age'" }), 400
53+ student .age = data ['age' ]
54+
3655 db .session .commit ()
3756 return jsonify ({"message" : "Updated" }), 200
3857
@@ -47,4 +66,3 @@ def delete_student(id):
4766 with app .app_context ():
4867 db .create_all ()
4968 app .run (debug = True )
50-
0 commit comments