from .schemas import user_schema, ValidationError
@bp.route('/register', methods=['POST'])
def register():
try:
# Validate and deserialize the input data
data = user_schema.load(request.get_json())
except ValidationError as err:
return jsonify({"error": "Validation Error", "message": err.messages}), 400
# Check if username or email already exists
if User.query.filter_by(username=data['username']).first():
return jsonify({"error": "Username already exists"}), 400
if User.query.filter_by(email=data['email']).first():
return jsonify({"error": "Email already exists"}), 400
# Create a new user
new_user = User(username=data['username'], email=data['email'])
new_user.set_password(data['password'])
db.session.add(new_user)
db.session.commit()
return jsonify({
"id": new_user.id,
"username": new_user.username,
"email": new_user.email
}), 201
The code imports user_schema
and ValidationError
from .schemas
to handle user input validation. It validates and deserializes incoming JSON data using user_schema.load(request.get_json())
. If the data is invalid, the code raises a ValidationError
and returns a JSON response with an error message. This ensures that only properly formatted user data proceeds to the registration process. 🚀
Update the login endpoint
Update the /api/login
endpoint in app/routes.py
to use the validation schema:
@bp.route('/login', methods=['POST'])
def login():
try:
# Validate and deserialize the input data
data = user_schema.load(request.get_json)
except ValidationError as err:
return jsonify({"error": "Validation Error", "message": err.messages}), 400
username = data['username']
password = data['password']
# Find the user
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
access_token = create_access_token(identity=str(user.id))
return jsonify(access_token=access_token), 200
return jsonify({"error": "Invalid credentials"}), 401
The code validates and deserializes incoming JSON data using user_schema.load(request.get_json())
. If the data is invalid, it raises a ValidationError
and returns a JSON response with an error message. This ensures the login process only accepts properly formatted user input. 🚀
Step 3: Test error handling and validation
Let’s test the error handling and validation using curl
.
Test 404 Error
Try accessing a non-existent endpoint:
curl http://127.0.0.1:5000/api/nonexistent
Expected response
{
"error": "Not Found",
"message": "The requested resource was not found"
}
Test validation errors
Send invalid data to the /api/register
endpoint:
curl -X POST -H "Content-Type: application/json" -d '{"username": "testuser", "email": "invalid-email", "password": "testpass"}' http://127.0.0.1:5000/api/register
Expected response
{
"error": "Validation Error",
"messages": {
"email": ["Not a valid email address."]
}
}
Full code for part 4
You can find the complete code for this tutorial in the GitHub repository.
What’s Next?
In Part 5, we’ll add logging and monitoring to the application to track requests, errors, and performance. Stay tuned!
Facebook Comments