Ithy Logo

Creating a Simple Flask Application with Frontend and Backend

Step-by-step guide to building a full-stack web application using Flask

flask web application setup

Key Takeaways

  • Comprehensive Setup: Establish a clear project structure with separate directories for templates and static files.
  • Seamless Integration: Connect frontend and backend using Flask routes and JavaScript for dynamic interactions.
  • Scalable Foundation: Utilize virtual environments and Flask extensions to enhance and scale your application.

Introduction

Flask is a lightweight and flexible Python web framework that allows developers to build web applications with ease. This guide provides a comprehensive example of a simple Flask application that incorporates both frontend and backend components. By following these steps, you'll create a functional web app that can serve HTML pages and handle backend logic seamlessly.

Project Structure

Organizing your project with a clear structure is crucial for maintaining and scaling your application. Here's how to set up your project directory:


flask_app/
├── app.py
├── requirements.txt
├── templates/
│   └── index.html
└── static/
    ├── style.css
    └── script.js
    

Setting Up the Environment

Step 1: Create Project Directory and Navigate Into It

Open your terminal and execute the following commands to create and enter the project directory:


mkdir flask_app
cd flask_app
    

Step 2: Set Up a Virtual Environment

Setting up a virtual environment isolates your project dependencies:


python3 -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
    

Step 3: Install Flask

Install Flask using pip:


pip install Flask
    

Step 4: Create Requirements File

Freeze your dependencies into a requirements.txt file:


pip freeze > requirements.txt
    

Backend Implementation

Creating app.py

The app.py file contains the backend logic of your application. Here's a simple example:


from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/greet', methods=['POST'])
def greet():
    name = request.form.get('name')
    return render_template('index.html', greeting=f'Hello, {name}!')

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {
        "message": "Hello from Flask!",
        "items": ["Item 1", "Item 2", "Item 3"]
    }
    return jsonify(data)

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

Explanation

  • Imports: Import necessary modules from Flask.
  • App Initialization: Initialize the Flask application.
  • Routes:
    • @app.route('/'): Serves the main HTML page.
    • @app.route('/greet', methods=['POST']): Handles form submissions and returns a personalized greeting.
    • @app.route('/api/data', methods=['GET']): Provides a JSON API endpoint.
  • Run the App: Enables debug mode for development purposes.

Frontend Implementation

Creating Templates

The frontend is built using HTML, CSS, and JavaScript. Flask looks for HTML templates in the templates directory.

1. templates/index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple Flask App</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Welcome to the Simple Flask App</h1>
    
    {% if greeting %}
        <p>{{ greeting }}</p>
    {% endif %}
    
    <form action="{{ url_for('greet') }}" method="POST">
        <label for="name">Enter your name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Greet Me</button>
    </form>
    
    <hr />
    
    <h2>Fetch Data from API</h2>
    <button id="fetchButton">Fetch Data</button>
    <div id="dataResponse"></div>
    
    <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
    

Explanation

  • Template Variables:
    • {{ url_for('static', filename='style.css') }}: Links the CSS file.
    • {{ greeting }}: Displays personalized greeting if available.
    • {{ url_for('greet') }}: Sets the form action to the /greet route.
  • Form: Allows users to submit their name and receive a greeting.
  • Fetch Data Section: Includes a button to fetch data from the API and display it.

2. static/style.css


body {
    font-family: Arial, sans-serif;
    text-align: center;
    margin-top: 50px;
}

form {
    margin-top: 20px;
}

input {
    padding: 8px;
    width: 200px;
}

button {
    padding: 8px 16px;
    margin-left: 10px;
}

#dataResponse {
    margin-top: 20px;
    font-weight: bold;
}
    

Explanation

  • Styling: Centers the content and adds spacing for better aesthetics.
  • Form Elements: Styles input fields and buttons for consistency.
  • Data Response: Styles the area where API data will be displayed.

3. static/script.js


document.addEventListener("DOMContentLoaded", () => {
    const fetchButton = document.getElementById("fetchButton");
    const dataResponse = document.getElementById("dataResponse");
    
    fetchButton.addEventListener("click", async () => {
        try {
            const response = await fetch("/api/data");
            const data = await response.json();
            
            if (response.ok) {
                dataResponse.innerHTML = `<p>${data.message}</p>
                                          <ul>${data.items.map(item => `<li>${item}</li>`).join('')}</ul>`;
            } else {
                dataResponse.textContent = "Error fetching data.";
            }
        } catch (error) {
            dataResponse.textContent = "An error occurred!";
            console.error(error);
        }
    });
});
    

Explanation

  • Event Listener: Waits for the DOM to load before attaching the click event.
  • Fetch API: Sends a GET request to the /api/data endpoint.
  • Response Handling: Displays the fetched data or an error message.

Running the Application

Step 1: Install Dependencies

Ensure all dependencies are installed by running:


pip install -r requirements.txt
    

Step 2: Start the Flask Server

Run the Flask application using the following command:


python app.py
    

Step 3: Access the Application

Open your web browser and navigate to http://127.0.0.1:5000/. You should see the homepage with a welcome message and a form to enter your name. Submitting the form will display a personalized greeting. Additionally, clicking the "Fetch Data" button will retrieve and display data from the backend API.


Conclusion

By following this guide, you've set up a simple yet functional Flask application that integrates both frontend and backend components. This foundation can be expanded with additional features such as user authentication, database interactions, and more complex frontend frameworks like React or Vue.js. Flask's flexibility and simplicity make it an excellent choice for building scalable web applications.

References


Last updated January 12, 2025
Ask me more