Creating a Flask + React Project with Vite: Combining Python Backend and React Frontend

Posted by

How to Create a Flask + React Project with Vite | Python Backend + React Frontend

How to Create a Flask + React Project with Vite | Python Backend + React Frontend

In this article, we will go through the steps to create a project using Flask as the backend and React as the frontend with Vite as the build tool. This setup allows us to utilize Python for the backend and React for the frontend, making it a powerful combination for full-stack web development.

Prerequisites

Before we begin, make sure you have the following tools installed on your system:

  • Python (https://www.python.org/)
  • Node.js (https://nodejs.org/)
  • npm (comes with Node.js)

Creating the Flask Backend

First, let’s create the Flask backend for our project. Follow these steps:

  1. Open a terminal and create a new directory for your project.
  2. Navigate to the project directory and create a virtual environment by running python -m venv venv.
  3. Activate the virtual environment by running venvScriptsactivate on Windows or source venv/bin/activate on MacOS and Linux.
  4. Install Flask by running pip install Flask.
  5. Create a new Python file (e.g., app.py) and write the following code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)
		

Creating the React Frontend with Vite

Next, let’s create the React frontend with Vite. Follow these steps:

  1. Open a new terminal window and navigate to the project directory.
  2. Create a new React app using Vite by running npx create-vite-react frontend --template react.
  3. Install Axios for making HTTP requests by running npm install axios.

Connecting the Frontend to the Backend

Finally, let’s connect the frontend to the backend by making an HTTP request from the React frontend to the Flask backend. Follow these steps:

  1. In your React component, import Axios by adding import axios from 'axios';.
  2. Create a function to make an HTTP request to the Flask backend:
const fetchData = async () => {
    const response = await axios.get('http://localhost:5000/');
    console.log(response.data);
};
		

Now you can call this function in your component to fetch data from the Flask backend.

That’s it! You have successfully created a Flask + React project with Vite, with Python as the backend and React as the frontend. Happy coding!