pythonflask

Error about the validity of JSON used by request


I got an flask application and one of the route add a user. The route is called when a form has been completed and submitted. The thing is, when I submit the form, I got a flash message saying Expecting value: line 1 column 1 (char 0). To my understanding, the application is seemingly not accepting my payload but I am left clueless as to why.

#Front end
@app.route('/add-user', methods=['POST'])
def addUser():
    username = request.form.get('username')
    email = request.form.get('email')
    password = request.form.get('password')

    # Vérification des données
    if not username or not email or not password:
        flash("Tous les champs sont obligatoires.", "error")
        return redirect('/')

    payload = {
        "username": username,
        "email": email,
        "password": password
    }

    # Appel de l'API pour ajouter un utilisateur
    try:
        response = requests.post('http://' + BACK_END_IP + ':' + BACK_END_PORT + '/add-user', json=payload)
        if response.status_code == 200:
            flash("Utilisateur ajouté avec succès.", "success")
            return redirect('/')
        else:
            error_message = response.json().get("error", "Erreur inconnue.")
            flash(f"Erreur : {error_message}", "error")
            return redirect('/')
    except requests.exceptions.RequestException as e:
        flash(f"Impossible de se connecter à l'API. Détails : {str(e)}", "error")

    return redirect('/')

#Back end
@app.route('/add-user', methods=['POST'])
def addUser():
    current_user = get_user_from_token(request)
    if current_user.admin:
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')

        if not username or not email or not password:
            return jsonify({"error": "Tous les champs sont requis."}), 400

        # Creation de user et account
        try:
            new_user = User(public_id=str(uuid.uuid4()), username=username, password=hash_password(password), email=email,
                            admin=False, two_factor_enabled=False, valid_code=None, valid_code_exp=None,
                            reset_pswd_code=None, reset_pswd_exp=None)
            db.session.add(new_user)
            db.session.commit()
            account_user = Account(user=new_user.id, public_id=str(uuid.uuid4()), balance=0)
            db.session.add(account_user)
            db.session.commit()

            return jsonify({"message": "Utilisateur ajouté avec succès."}), 200
        except Exception as e:
            # Capture et affichage de l'erreur
            db.session.rollback()
            return jsonify({'message': f"Une erreur est survenue : {str(e)}"}), 500
    else:
        return jsonify({'message': 'You are not admin'}), 401

I tried to use jsonify() on payload and it and it just led to an error I tested the backend request on postman and it work. I just put it there for comprehension


Solution

  • Try to add headers to your requests.post to ensure it's recognized as JSON:

    response = requests.post(
        'http://' + BACK_END_IP + ':' + BACK_END_PORT + '/add-user',
        json=payload,
        headers={'Content-Type': 'application/json'}
    )
    

    Also check what data is receiving backend:

    data = request.get_json()
    print(data)
    # or try this:
    print(request.json.items())
    

    In my project i used this and it work:

    request.json.get('email')
    

    If this doesn't help, try instead of request.get_json(), use request.form.get().