I\'m trying to build a Flask API and I have one endpoint that is supposed to create a user and another one that is suppose to check if a user is present in the database:
I would do something like this for your use-case:
@API.route('/users', defaults={'email': None} ,methods=['GET', 'POST'])
@API.route('/users/', methods=['GET', 'POST'])
def new_user(email):
if(email):
user = User.query.filter_by(email=email).first()
if user:
return jsonify(user=user.to_json()), 200
else:
return jsonify(error=404), 404
else:
user_json = json.loads(request.get_json())
first_name = user_json.get('first_name')
last_name = user_json.get('last_name')
email = user_json.get('email')
password = user_json.get('password')
user = User(first_name=first_name, last_name=last_name, email=email, password=password)
db.session.add(user)
db.session.commit()
return jsonify(user=user.to_json()), 200