Flask is a micro-framework — it gives you routing and request handling without imposing structure. You choose your own tools for databases, forms, and authentication.

Installation

  python -m venv .venv
source .venv/bin/activate
pip install flask
  

Minimal Application

  # app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, Flask!'

@app.route('/user/<name>')
def greet(name):
    return f'Hello, {name}!'

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

Run it:

  python app.py
# Visit http://127.0.0.1:5000/
  

Project Structure

For larger apps, use the application factory pattern:

  myapp/
├── app/
│   ├── __init__.py      # create_app() factory
│   ├── routes.py        # route definitions
│   ├── models.py        # database models
│   └── templates/       # Jinja2 templates
├── config.py
├── requirements.txt
└── run.py
  
  # app/__init__.py
from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config.from_object('config.Config')

    from .routes import main
    app.register_blueprint(main)

    return app
  
  # run.py
from app import create_app

app = create_app()

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

Handling Requests

  from flask import request, jsonify

@app.route('/api/items', methods=['GET', 'POST'])
def items():
    if request.method == 'POST':
        data = request.get_json()
        # process data...
        return jsonify(data), 201
    return jsonify([{"id": 1, "name": "Item"}])
  

Templates with Jinja2

  from flask import render_template

@app.route('/posts')
def posts():
    posts = [{"title": "First Post", "body": "Hello!"}]
    return render_template('posts.html', posts=posts)
  
  <!-- templates/posts.html -->
{% for post in posts %}
  <h2>{{ post.title }}</h2>
  <p>{{ post.body }}</p>
{% endfor %}
  

Blueprints — Modular Routes

  # app/routes.py
from flask import Blueprint

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return 'Home'

@main.route('/about')
def about():
    return 'About page'
  

Flask’s simplicity makes it ideal for learning web development and building focused microservices.

Next: Database Integration with SQLAlchemy.