Learn how to find your target audience and match your business goals with their needs: Get the Target Audience Persona Template

How to Build a Full-Stack Web Application with Python and Vue.js

by Charisol

July 26, 2023

Share:

The development process for building full-stack websites results in a feature-rich, responsive, and interactive web experience when integrating the amazing capabilities of Python’s backend with the dynamic frontend framework of Vue.js.

Python, known for its simplicity and versatility, serves as the foundation for the backend, handling data processing, database interactions, and API endpoints. On the other hand, Vue.js, a progressive JavaScript framework, empowers developers to build dynamic and user-friendly interfaces on the frontend.

This comprehensive article will delve into the step-by-step process of creating a full-stack web application. From setting up the backend using Flask, a lightweight Python web framework, to configuring the frontend with Vue.js through the Vue CLI, we will explore each essential aspect of the development journey.

Throughout this guide, we will not only focus on setting up the environment but also show you how to establish a smooth connection between the backend and frontend, allowing them to interact seamlessly. 

By the end of this tutorial, you will have the basic knowledge required to create your full-stack web applications, leveraging the best of both Python and Vue.js to bring those ideas to life.

Whether you are a seasoned developer looking to expand your skill set or a newcomer eager to embark on your web development journey, this article will serve as a guide to explore the exciting world of full-stack development with Python and Vue.js.

Let’s dig in and ultimately develop this comprehensive and entertaining website!

a computer screen with a bunch of text on it

Source: Photo by Pixabay: https://www.pexels.com/photo/view-of-airport-247791/

Prerequisites

Before we get started, make sure you have the following installed on your system:

  1. Python: You can download and install Python from the official website (https://www.python.org/).
  2. Node.js and npm: Vue.js requires Node.js and npm to be installed. You can download and install them from the official website (https://nodejs.org/).
  3. Vue CLI: To scaffold Vue.js projects, install Vue CLI globally using npm by running the following command in your terminal or command prompt:

npm install -g @vue/cli

Steps in Building a Full-Stack Web Application with Python and Vue.js

Setting up the Backend with Python

After installing the above requirements, we will use Flask, a web framework, to create our API.

Step 1: Create a Project Directory

Here, we will create a project directory for the backend code. To do this, open your terminal or command prompt and input the following command: 

mkdir backend

cd backend

Step 2: Initialize a virtual environment

Initializing a virtual environment’ means the ability to isolate your Python development projects from the system installed in Python, including other Python environments and dependability. This gives you full control of your project and makes it easily reproducible. Execute the following command to achieve this:

python -m venv venv

Step 3: Activate the Virtual Environment

For Windows:

venv\Scripts\activate

For macOS and Linux:

source venv/bin/activate

Step 4: Install ‘Flask’:

Since the virtual environment is set up, install Flask using pip:

pip install Flask

Step 5: Create the Flask App:

Next, create a file named app.py in the backend directory and define a basic Flask application:

# app.py

from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello():

    return 'Hello from Flask!'

Step 6: Run the Flask App

Run the Flask app using the command below:

python app.py

You should see the following output:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

This means your Flask backend is up and running on http://127.0.0.1:5000/.

Setting up the Frontend with Vue.js

Now that the backend is ready, let’s set up the frontend using Vue.js.

Step 1: Create a Vue.js Project

Open your terminal or command prompt, navigate to your project’s root directory (where the ‘backend’ directory is located), and run the following command to create a new Vue.js project:

vue create frontend

This will prompt you to pick a preset. Choose the default preset (or manually select features as needed).

Step 2: Run the Vue.js Development Server

After the Vue.js project is created, navigate to the ‘frontend’ directory and run the development server using the following command:

cd frontend

npm run serve

You should see the following output:

App running at:

– Local:   http://localhost:8080/

– Network: http://192.168.0.101:8080/

Now, your Vue.js frontend is running on http://localhost:8080/

Step 3: Update Vue.js to Fetch Data from Backend

Let’s update the Vue.js app to get data from the Flask backend we initially created. Open the frontend/src/App.vue file and replace its content with the following:

<template>

  <div>

    <h1>{{ message }}</h1>

  </div>

</template>

<script>

export default {

  data() {

    return {

      message: "",

    };

  },

  mounted() {

    fetch("http://localhost:5000/")

      .then((response) => response.text())

      .then((data) => {

        this.message = data;

      });

  },

};

</script>

This code will fetch data from the Flask backend and display it in the Vue.js app.

Connecting the Backend and Frontend

Now that both the backend and frontend are set up, we need to link them so that the frontend can communicate effectively with the backend API.

In the frontend/src/App.vue file, we are already fetching data from the backend using the URL http://localhost:5000/, which is where our Flask backend is running.

Since our Vue.js development server runs on a different port (by default, it’s http://localhost:8080/), we need to configure Vue.js to proxy API requests to the Flask backend during development.

Step 1: Configure Vue.js Proxy

Create a file named vue.config.js in the frontend directory (if it doesn’t exist already) and add the following content:

module.exports = {

  devServer: {

    proxy: {

      '/api': {

        target: 'http://localhost:5000',

        changeOrigin: true,

      },

    },

  },

};

Step 2: Update Vue.js App to Use Proxy

Update the fetch URL in the frontend/src/App.vue file to use the /api prefix, which will be automatically proxied to the Flask backend during development:

<template>

  <div>

    <h1>{{ message }}</h1>

  </div>

</template>

<script>

export default {

  data() {

    return {

      message: "",

    };

  },

  mounted() {

    fetch("/api")

      .then((response) => response.text())

      .then((data) => {

        this.message = data;

      });

  },

};

</script>

Step 3: Restart the Vue.js Development Server

Restart the Vue.js development server by stopping it (if it’s running) using CTRL+C and then running npm run serve again.

When you visit http://localhost:8080/, the Vue.js app should fetch data from the Flask backend and display it on the page. 

Building a Simple To-Do List Website Using Python and Vue.js

With the installation, development, and connection phases complete, we will add a simple feature to our full-stack web application to illustrate how to build and integrate features using Python and Vue.js. This feature is a simple to-do list app where users can add and remove tasks whenever they choose. 

The tasks will be stored in the backend using a list, and Vue.js will handle the frontend to display and manage them. To do this, we will begin with the backend implementation:

Step 1: Modify the Backend API

In the app.py file (located in the backend directory), let’s update the backend API to handle tasks. Add the following code:

from flask import Flask, jsonify, request

app = Flask(__name__)

tasks = []

@app.route('/api/tasks', methods=['GET'])

def get_tasks():

    return jsonify(tasks)

@app.route('/api/tasks', methods=['POST'])

def add_task():

    data = request.get_json()

    task = data.get('task', '')

    tasks.append(task)

    return jsonify({'message': 'Task added successfully!'})

@app.route('/api/tasks/<int:index>', methods=['DELETE'])

def remove_task(index):

    if 0 <= index < len(tasks):

        del tasks[index]

        return jsonify({'message': 'Task removed successfully!'})

    else:

        return jsonify({'error': 'Invalid index!'}), 400

Note: In this updated API, we have three endpoints: GET /api/tasks to retrieve all tasks; POST /api/tasks to add a new task, and DELETE /api/tasks/<int:index> to remove a task by its index.

We will move on to the front-end implementation.

Step 2: Update the Vue.js App

In the frontend/src/App.vue file, let’s modify the Vue.js app to display the tasks and add the functionality to ‘add and remove’ tasks. Replace its content with the following code:

<template>

  <div>

    <h1> Charisol’s To-Do List</h1>

    <div v-for="(task, index) in tasks" :key="index">

      {{ task }}

      <button @click="removeTask(index)">Remove</button>

    </div>

    <input v-model="newTask" @keydown.enter="addTask" placeholder="Add a new task" />

    <button @click="addTask">Add</button>

  </div>

</template>

<script>

export default {

  data() {

    return {

      tasks: [],

      newTask: "",

    };

  },

  mounted() {

    this.fetchTasks();

  },

  methods: {

    fetchTasks() {

      fetch("/api/tasks")

        .then((response) => response.json())

        .then((data) => {

          this.tasks = data;

        });

    },

    addTask() {

      if (this.newTask.trim() !== "") {

        fetch("/api/tasks", {

          method: "POST",

          headers: {

            "Content-Type": "application/json",

          },

          body: JSON.stringify({ task: this.newTask }),

        })

          .then(() => {

            this.newTask = "";

            this.fetchTasks();

          });

      }

    },

    removeTask(index) {

      fetch(`/api/tasks/${index}`, {

        method: "DELETE",

      })

        .then(() => {

          this.fetchTasks();

        });

    },

  },

};

</script>

Our app is ready! This Vue.js app will display the to-do list, allow users to add new tasks by typing in the input field and hitting “Enter” or clicking the “Add” button, and provide a “Remove” button for each task to delete it.

Conclusion

Congratulations! You have successfully built a full-stack web application using Python as the backend language and Vue.js as the frontend framework. You learned how to set up a Flask backend API, create a Vue.js frontend, connect them to communicate with each other during development and build a simple to-do feature.

From here, you can expand and enhance your web application by adding more features, database integration, user authentication, and more. Happy coding!

Remember to check the official documentation of Flask (https://flask.palletsprojects.com/) and Vue.js (https://vuejs.org/) for more in-depth details and features.

In Charisol, our expert team of developers builds robust and responsive website and app development that bolsters your needs. Contact us today!

Author

Picture of Charisol

Charisol

Related Articles