Getting 404 error when running Flutter app with Flask backend

I’m having trouble with my Flask backend for a Flutter app. When I start the server using python3 server.py, it seems to run fine. But when I try to access it, I get a 404 error.

Here’s my Flask code:

from flask import Flask, request, jsonify
from flask_cors import CORS
import subprocess

app = FlaskApp(__name__)
CORS(app)

@app.before_request
def log_request():
    print(f"Incoming request: {request.path}")

@app.route('/run-script/', methods=['POST'])
def run_script():
    try:
        script_name = request.form.get('script_name')
        if not script_name:
            return jsonify({'status': 'error', 'message': 'Script name missing'})

        result = subprocess.run(['python', f'scripts/{script_name}'], capture_output=True, text=True)

        if result.returncode == 0:
            return jsonify({'status': 'success', 'output': result.stdout})
        else:
            return jsonify({'status': 'error', 'message': result.stderr})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

The server console shows:

* Running Flask app 'server'
* Debug mode: off
* Running on http://127.0.0.1:5000
* Running on http://192.168.1.100:5000
Incoming request: /
127.0.0.1 - - [21/Mar/2025 10:15:30] "GET / HTTP/1.1" 404 -

Why am I getting a 404 error and how can I fix it?

hey swiftcoder15, looks like ur hitting the root path (‘/’) which isnt defined in ur flask app. try adding a route for ‘/’ or making sure ur flutter app sends requests to ‘/run-script/’. hope this helps!

hey there! have u considered checking ur flutter app’s API calls? maybe ur not hitting the correct endpoint? also, it might be worth adding a simple ‘/’ route in ur flask app just to confirm it’s working. what does ur flutter code look like for making requests?

The 404 error occurs because the root path (‘/’) is not defined in the Flask application. The code currently provides an endpoint only for ‘/run-script/’, which means any request to ‘/’ will result in a 404 response. One solution is to add a root endpoint that confirms whether the server is running, which can help in diagnosing connection issues. Another solution is to verify that your Flutter app’s API requests are targeting the correct endpoint. It is also important to ensure that the application is using the appropriate IP address and port for the environment in which it is running.