Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 23

Setting Up Your First Flask App

Recommended resources

Hello! Welcome to the fifth module of your course. So far, you have done an incredible job building the "frontend" of our application—the part the user sees and interacts with in their browser. You've structured the page with HTML, styled it with CSS, and brought it to life with JavaScript.

But a web application has two sides. The other side is the backend, or the server. This is the hidden engine that runs on a computer elsewhere, performing the heavy lifting: running complex logic, accessing databases, and, in our case, communicating with the Gemini AI API. Your Python skills will be the foundation for building this engine.

In this lesson, we will build the first, most fundamental piece of our backend. You will learn how to install Flask and create a basic web server application. Flask is a Python framework that makes it surprisingly simple to create a web server that can listen for requests from a browser and send back responses.

Flask Webserver Client-Server Diagram
This diagram shows the basic client-server model. Our Flask application will be the "Server," and the user's web browser will be the "Client." They communicate using HTTP.

By the end of this lesson, you will have a simple but functional web server running on your own computer.

What is a Backend and Why Flask?

The backend is where your core application logic lives. While JavaScript in the browser can handle animations and user input, it can't securely manage API keys or perform the kind of large-scale processing we need for our AI tool. That's the job of our Python-based server.

We're using Flask to build this server. Flask is known as a "microframework" because it's small, lightweight, and easy to learn. It gives you the essential tools to build a web application without forcing you into a rigid structure, making it a perfect choice for your first project.

To learn a bit more about what Flask is, let's look at a quick introduction.

How To Create Your First Web Application Using Flask and Python

This article from DigitalOcean provides a concise overview of Flask and its purpose. It sets the stage for what we are about to build.

Read the 'Introduction' section only. It gives a high-level summary of what Flask is and why it's a good choice for developers.


Step 1: Preparing Your Project Environment

Before we install Flask, we must set up our project correctly. A critical best practice in Python development is to use a virtual environment. A virtual environment is an isolated copy of Python for a specific project. This means any packages you install for this project (like Flask) won't interfere with other Python projects on your computer.

This is an essential skill for any serious Python developer. The following tutorial is one of the most respected guides for learning Flask and explains this concept perfectly.

The Flask Mega-Tutorial, Part I: Hello, World!

Let's learn how to create and manage a virtual environment. This article from 'The Flask Mega-Tutorial' series is an excellent guide.

Read the section titled 'Installing Flask'. Pay close attention to the explanation of why virtual environments are important. Then, follow the steps to: Create a new project directory (e.g., my-ai-app). Navigate into that directory in your terminal. Create a virtual environment using python3 -m venv venv (or just python if python3 doesn't work). Activate the environment. The activation command is different for each operating system (Windows, Mac, or Linux), so be sure to use the correct one for your system. You'll know it's working when you see (venv) at the beginning of your terminal prompt.


Step 2: Installing Flask

Great! Now that your virtual environment is active, any package you install with pip will be placed inside it, keeping your project self-contained. Installing Flask is now just a single command.

The Flask Mega-Tutorial, Part I: Hello, World!

With your virtual environment active, you can now safely install Flask.

In the same 'Installing Flask' section you just read, find the command pip install flask and run it in your activated terminal. The article also shows how you can quickly verify the installation, which is a good habit.


Step 3: Writing Your First Web Server

With Flask installed, it's time to write some code. The amount of code needed for a basic web server is remarkably small.

In your project directory, create a new file named app.py. We'll now watch a short video that walks through the essential lines of code and explains what each one does.

Python Flask Tutorial: Full-Featured Web App Part 1 - Getting Started

This video provides an excellent line-by-line explanation of a minimal Flask application. This will help you understand the purpose of each part of the code.

Watch the segment from 03:55 to 07:04. The presenter will guide you through creating a Python file and adding the basic code. Focus on his explanation of importing Flask, creating the app instance, and what the @app.route() decorator does.

Here is the complete code for your app.py file. This includes a small addition at the end that makes running the server easy.

from flask import Flask

# Create an instance of the Flask application
app = Flask(__name__)

# Define a route for the home page URL ('/')
# This decorator tells Flask which URL should trigger our function.
@app.route('/')
def home():
    # This is the view function. It returns the response for this route.
    return "Hello, World!"

# This block allows you to run the app by executing this file directly.
# It's a standard convention in Python scripts.
if __name__ == '__main__':
    # app.run() starts the development server.
    # debug=True enables debug mode, which automatically reloads the server
    # when you save changes to the file. This is very useful for development.
    app.run(debug=True)

Let's quickly break this down:

  1. from flask import Flask: We import the main Flask class from the flask library.
  2. app = Flask(__name__): We create an "instance" of our web application. __name__ is a special Python variable that helps Flask know where to find resources.
  3. @app.route('/'): This is a decorator. It links the URL / (the root or home page of our site) to the function defined right below it.
  4. def home():: This is our "view function." It contains the logic that runs when a user visits the / route.
  5. return "Hello, World!": The view function returns the content that will be displayed in the user's browser. Right now, it's just plain text.
  6. if __name__ == '__main__':: This standard Python construct ensures that the server only runs when the script is executed directly (not when it's imported by another script).
  7. app.run(debug=True): This command starts Flask's built-in development web server.

Step 4: Running Your Server

This is the moment of truth! Let's run the server and see it in action.

  1. Open your terminal.
  2. Make sure you are in your project directory (my-ai-app or whatever you named it).
  3. Make sure your virtual environment is still active (you should see (venv)).
  4. Run the application with the following command:
    python app.py
    

You should see output in your terminal indicating that a server is running, usually on http://127.0.0.1:5000/. Now, open your web browser and navigate to that address. You should see the text "Hello, World!" on the page.

Flask Basic Web Server Demonstration
This is what a successful run looks like. The terminal shows the Flask server is running, and the browser displays the message returned by your Python code.

Congratulations, you've just built and run your first web server!

Test your understanding!

Based on the app.py code we just wrote, how would you change the application so that visiting http://127.0.0.1:5000/welcome displays the message "Welcome to my AI Assistant"?

Show answer

You would add a new route and view function to your app.py file like this:

@app.route('/welcome')
def welcome_page():
    return "Welcome to my AI Assistant"

After adding this code and saving the file, the debug mode will automatically restart the server. You can then visit http://127.0.0.1:5000/welcome in your browser to see the new message. The original "Hello, World!" at / will still work.


Conclusion

You've taken a huge step today, bridging the gap between standalone Python scripts and a live web application. This is the starting point for the entire backend of your AI-powered tool.

Key Takeaways:

  • A web server is a program that listens for requests from browsers and sends back responses.
  • Flask is a Python microframework that makes building web servers simple and flexible.
  • Virtual environments are essential for managing project-specific dependencies and are a professional standard in Python development.
  • A basic Flask app requires an app instance, a route (@app.route()), and a view function that returns a response.
  • You can run the development server using app.run(debug=True) inside your script.

In our next lesson, we will explore routes more deeply. You will learn how to define routes that can handle different types of requests from the browser, specifically GET and POST requests. This will be crucial for receiving user input from your frontend form.