Getting Started with Flask: How to Build Web Apps in Python

What is Flask?

Flask is a lightweight web framework for Python. It helps you create web servers, define URLs (routes), and serve content — all with minimal code.

It’s perfect for beginners and small to medium projects because:

  • It’s simple and flexible
  • Has a clean and intuitive API
  • Lets you add only what you need

Step 1: Install Flask

First, install Flask using pip:

pip install Flask

Step 2: Create Your First Flask App

Create a file called app.py with this code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Flask!"

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

Step 3: Run Your App

In your terminal, run:

python app.py

You’ll see something like:

 * Running on http://127.0.0.1:5000/

Open your browser and go to http://127.0.0.1:5000/. You should see:

Hello, Flask!

Step 4: Understand Routes

Routes define URLs and what happens when a user visits them.

Try adding another route:

@app.route("/about")
def about():
    return "This is the about page."

Restart your app and visit http://127.0.0.1:5000/about

Step 5: Returning HTML Templates

Instead of plain text, you can return HTML. Create a folder called templates, then create a file index.html inside it:

<!DOCTYPE html>
<html>
<head>
    <title>My Flask App</title>
</head>
<body>
    <h1>Welcome to Flask!</h1>
</body>
</html>

Modify app.py to render this template:

from flask import Flask, render_template

app = Flask(__name__)

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

Restart the server and reload your homepage.

Step 6: Handling User Input (Forms)

Create a simple form in templates/form.html:

<!DOCTYPE html>
<html>
<body>
    <form action="/greet" method="POST">
        <input type="text" name="username" placeholder="Enter your name">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Add these routes to app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/form")
def form():
    return render_template("form.html")

@app.route("/greet", methods=["POST"])
def greet():
    name = request.form.get("username")
    return f"Hello, {name}!"

Visit http://127.0.0.1:5000/form to try it out.

Bonus Tips:

  • Use debug=True during development to auto-reload and get detailed errors
  • Explore Flask extensions like Flask-SQLAlchemy for databases or Flask-Login for authentication
  • Break your app into modules as it grows

Leave a Reply

Your email address will not be published. Required fields are marked *